For my current project assignment I was asked to share a PowerShell script which creates VSTS build + phase dynamically. To make this blog short let me show a simple build definitions sample.
With no wait here is the code
$Token = "Personal Access Token" $Authentication = [Text.Encoding]::ASCII.GetBytes(":$Token") $Authentication = [System.Convert]::ToBase64String($Authentication) $Headers = @{ Authorization = ("Basic {0}" -f $Authentication) } $Body = Get-Content "C:\Projects\servicenow\buildDef.json" $Uri = "https://about-powershell.visualstudio.com/servicenow/_apis/build/definitions?api-version=5.0-preview.6" $Result = Invoke-WebRequest -Method Post -Uri $Uri -Headers $Headers -Body $Body -ContentType "application/json" $Result
Step 1: You need Personal Access Token (PAT). Go get it.
Step 2: Convert to base64 string.
Step 3: Define your build (In my case its a JSON file)
Step 4: Consume the end point as per the documentation.
Before – Empty Builds and Pipeline
After the successful execution of the script! Out new build is created with one phase but no expected working phase (This is for demo)
{ "process": { "phases": [ { "steps": [], "name": "Phase 1", "refName": "Phase_1", "condition": "succeeded()", "target": { "executionOptions": { "type": 0 }, "allowScriptsAuthAccessOption": false, "type": 1 }, "jobAuthorizationScope": "projectCollection", "jobCancelTimeoutInMinutes": 1 } ], "type": 1 }, "repository": { "properties": { "cleanOptions": "0", "labelSources": "0", "labelSourcesFormat": "$(build.buildNumber)", "reportBuildStatus": "true", "gitLfsSupport": "false", "skipSyncSource": "false", "checkoutNestedSubmodules": "false", "fetchDepth": "0" }, "id": "4ba24767-e5a6-4987-80cc-ebaeca01fdbc", "type": "TfsGit", "name": "servicenow", "url": "https://about-powershell.visualstudio.com/servicenow/_git/servicenow", "defaultBranch": "refs/heads/master", "clean": "false", "checkoutSubmodules": false }, "processParameters": {}, "drafts": [], "name": "CreatedUsingPowerShell", "type": "build", "queueStatus": "enabled" }
Just export the existing build as JSON to get more insights!