Hello!

Last month I posted how to run the Azure PowerShell Task on a Self-Hosted Build Agent but because using self-hosted agents is something I’m not that interested in anymore here is an alternative to use the Hosted Build Agents.

There’s two steps to this: first you need to use the AzureCLI@2 task. This has an option to include the spn details, or in other words the login details of the Azure Resource Manager subscription you have specified in the azureSubscription parameter. You do this by setting addSpnToEnvironment to true. In this task you create environment variables of the service principal id, the key, and the tenant id.

now that you have login details as envvars you can use these in a PowerShell task, specifically NOT an Azure PowerShell task. In this task you need to install Az, then login as a service principal. After you’ve logged in remove the envvars so that they don’t persist any longer than they need to.


trigger:
- main

pool:
  vmImage: ubuntu-latest

steps:

- task: AzureCLI@2
  displayName: "Get Service Principal Variables"
  inputs:
    azureSubscription: $(azureSubscription)
    scriptType: 'bash'
    scriptLocation: 'inlineScript'
    inlineScript: |
      echo "##vso[task.setvariable variable=spId]$servicePrincipalId"
      echo "##vso[task.setvariable variable=spKey]$servicePrincipalKey"
      echo "##vso[task.setvariable variable=tid]$tenantId"
    addSpnToEnvironment: true

- task: PowerShell@2
  displayName: "Connect to Azure "
  inputs:
    targetType: "inline"
    script: |
        Install-Module Az -Scope CurrentUser -Force -Verbose -RequiredVersion 5.3.0
        $credential = New-Object System.Management.Automation.PSCredential ("${env:SPID}", (ConvertTo-SecureString ${env:SPKEY} -AsPlainText -Force))
        Connect-AzAccount -Credential $Credential -Tenant  ${env:TID} -ServicePrincipal
        Remove-Item env:\SPKEY
        Remove-Item env:\SPID
        Remove-Item env:\TID
    pwsh: true