Skip to content
Latchkey

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@2 step and set azureSubscription to its name.
  • Set scriptType (bash or pscore) and put az commands in inlineScript.

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 resources

Gotchas

  • azureSubscription takes the service connection name, not a subscription ID.
  • Set addSpnToEnvironment: true to expose the service principal id and key as variables.
  • The connection needs a role assignment that grants the actions your commands perform.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →