When you create an Azure DevOps Pipeline, you will have a configuration to pass to generate your application package. This configuration can have variables like environment variables, folder path, logins, passwords…
Below are a few ways you can achieve the same
- Define variables inside YAML
- Define variables inside DevOps Library
- Define variables inside Azure Key Vault
Variables inside YAML
By default, all these configurations can be directly defined inside your azure-pipeline.yml
file. This latter will be saved inside your code source repository. This is an easy thing to keep all your build configurations with your project
variables:
- name: 'agentPoolName'
value: 'my-cicd-pool'
or
variables:
- agentPoolName:'my-cicd-pool'
Variables inside DevOps Library
Above is an easy way, but as you can imagine, passwords must not be saved clearly in your code repository for security reasons. This is where the Library variables come into play.
variables:
- group: my-variable-group
To setup, go to Pipelines > Library > Variable groups and create a new Variable group.
The advantages of Library variables are you can define your secrets there, rather than hard-coding them. One other major advantage, when you have multiple environments is, these groups can be iterated in your YAML code, while in a stage or job.
parameters:
- name: environments
type: object
default:
- env_code: dev
env_name: Development
- deploy_env_code: uat
env_name: UAT
# Environment-wise variable groups usage
- ${{ each env in parameters.environments }}:
- stage:
displayName: Build ${{ env.env_name }}
variables:
- group: ${{ env.env_code }}
jobs:
- job: Task-Build
displayName: 'Task Build'
pool: $(agentPoolName)
variables:
api-key: $(api-key)
Once you specify the -group
Azure will find the group via the service connection you setup and read the variables inside groups.
Variables inside Azure Key Vault
The most secured way to access secrets is via your YAML pipelines are through the Azure Key-Vault service and you can achieve this easily with help of task — task: AzureKeyVault@2
# Azure Key Vault
# Download Azure Key Vault secrets
- task: AzureKeyVault@2
inputs:
connectedServiceName: ${{ service_name }}
keyVaultName: ${{ vault_name }}
secretsFilter: '*'
runAsPreJob: true # Runs before the job starts
# Environment-wise variable groups usage
- ${{ each env in parameters.environments }}:
- stage:
displayName: Build ${{ env.env_name }}
jobs:
- job: Task-Build
displayName: 'Task Build'
pool: $(agentPoolName)
variables:
api-key: $(api-key)
You can read more about here Azure Key vault secrets automation & integration in DevOps pipelines
Concussion
There are several ways to pass variables (secured and unsecured) to Azure DevOps pipelines. I found all these options are simple to use and sufficiently secure for your needs. I hope this note helped you understand the underlying concept of associating and accessing variables in Library and Azure Pipelines.