How to Run the Azure CLI With a Service Connection in Azure Pipelines
The AzureCLI@2 task signs in with the service connection you name, so your inline az commands run against the subscription without a manual login.
Create an Azure Resource Manager service connection, then use AzureCLI@2 with azureSubscription set to that connection name. The task handles authentication before running your inlineScript.
Steps
- Create an ARM service connection under Project settings to Service connections.
- Add an
AzureCLI@2step and setazureSubscriptionto its name. - Set
scriptType(bash or pscore) and putazcommands ininlineScript.
Pipeline
azure-pipelines.yml
steps:
- task: AzureCLI@2
inputs:
azureSubscription: 'prod-arm-connection'
scriptType: bash
scriptLocation: inlineScript
inlineScript: |
az group list --output table
az webapp restart --name checkout-api --resource-group web-rg
displayName: Manage Azure resourcesGotchas
azureSubscriptiontakes the service connection name, not a subscription ID.- Set
addSpnToEnvironment: trueto expose the service principal id and key as variables. - The connection needs a role assignment that grants the actions your commands perform.
Related guides
How to Use Workload Identity Federation for Azure in Azure PipelinesAuthenticate Azure Pipelines to Azure without stored secrets using a workload identity federation service con…
How to Deploy a Web App With the AzureWebApp Task in Azure PipelinesDeploy a built package to Azure App Service from Azure Pipelines with the AzureWebApp@1 task, pointing it at…