To continue with my post from yesterday, which was about using the Graph API in relation to using the Azure Cloud infrastructure, I will now explain how to start a build pipeline in Azure DevOps using PowerShell.

Requirements

This time, we will use with instead of OAuth 2 for authentication, Basic Auth.

For this, we will need a so-called Personal Access Token (PAT):

Visit https://dev.azure.com/<ORG-ID>/_usersSettings/tokens, click on your avatar on top-right side, select ..., then User settings and finally Personal access token.

Now click the button + New Token, give the new token a name and select for all your organizations Build - Read & execute in Scopes section.

Copy and save the new token somewhere, so you are able to access it for the upcoming steps later.

Explaining the code

The underlying example script can be found on GitHub.

For all REST API calls, I use the Invoke-RestMethod cmdlet again.

To read the settings for the API call from the command line parameters, a Get-BuildSettings function is located in Utils.ps1.

The PAT, we generated in the previous step, is used as password for the Basic Auth authentication flow, while we do not need a username:

$buildSettings = Get-BuildSettings $args

# example: https://dev.azure.com/<YOUR-ORGANIZATION>
$azureDevOpsOrgURL = $Env:TGF_AZURE_DEVOPS_ORGURL
# generate at https://dev.azure.com/<YOUR-ORGANIZATION>/_usersSettings/tokens
$azureDevOpsPAT = $Env:TGF_AZURE_DEVOPS_PAT

# create value for Basic Auth
$basicAuth = ":$($azureDevOpsPAT)"
$base64Auth = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($basicAuth))

# the full ID of the branch
$refName = "refs/heads/$($buildSettings.Branch)"

# now do the API request ...

$url = "$($azureDevOpsOrgURL)/" `
    + [System.Web.HttpUtility]::UrlEncode($buildSettings.Project) `
    + "/_apis/pipelines/" `
    + [System.Web.HttpUtility]::UrlEncode($buildSettings.Build) `
    + "/runs?api-version=6.1-preview.1"

$headers = @{
    "Authorization" = "Basic $($base64Auth)"
    "Content-Type" = "application/json"
}

$json = @{
    "resources" = @{
        "repositories" = @{
            "self" = @{
                "refName" = $refName
            }
        }
    }
} | ConvertTo-Json

$response = Invoke-RestMethod -Uri $url -Method POST -Headers $headers -Body $json

# output response
$response

Conclusion

I have successfully tested the scripts on MacOS and they should also be executable on Windows and Linux, since PowerShell is platform-independent and I have only used common techniques.

Have fun while trying it out! 🎉