Using Azure DevOps Pipeline Variables in PowerShell Script Files

Using Azure DevOps Pipeline Variables in PowerShell Script Files

Azure Pipelines inherently provides the ability for PowerShell scripts to be defined and executed inline.

- task: AzureCLI@2
  displayName: Bicep apply
  inputs:
    azureSubscription: MyAzureDevOpsConnectionName
    scriptType: pscore
    scriptLocation: inlineScript
    inlineScript: az deployment group create --resource-group $(AZ_PLATFORM_RESOURCE_GROUP_NAME) --name $(AZ_DEPLOYMENT_NAME)-$(AZ_ENV_NAME) 

Unfortunately, this can become very confusing in many situations and also repetitive, since, for example, an Azure Bicep deployment task is required in several stages, so that the task is repeated accordingly.

It can help that the PowerShell script is no longer declared inline, but via a scriptPath.

- task: AzureCLI@2
  displayName: Bicep apply
  inputs:
    azureSubscription: MyAzureDevOpsConnectionName
    scriptType: pscore
    scriptLocation: scriptPath
    inlineScript: $(Pipeline.Workspace)/bicep/run.ps1

What the script is missing now are the variables, whereby one must note that by default variables are available only within the file. This means that the variable $(AZ_PLATFORM_RESOURCE_GROUP_NAME).

To make variables available from outside in a PowerShell script file you need the $ENV: prefix.

# run.ps1
az deployment group create `
  --resource-group $($ENV:AZ_PLATFORM_RESOURCE_GROUP_NAME) `
  --name "$($ENV:AZ_DEPLOYMENT_NAME)-$($ENV:AZ_ENV_NAME)"

Now you can clean up your pipeline YAML file and reuse PowerShell commands very easily.