This is a common use case: You have multiple deployment environments and you need to use environment variables depending on the trigger branch and the target environment. Environment groups in Azure DevOps allow you to do so, and save you the hustle of handling suffixes and prefixes in your code and in your azure-pipelines.yml scripted pipeline. Keep it clean, keep it organized.

Terraform use case

Here we have a terraform project and we want to use the same variable names for three different environements (Production - Build - Sandbox). Of course, we want the values to change accordingly. Under Pipelines > Library, we create a variable group for each env and populate it with our variables and their respective values (you can also just do it for one env and clone it to create the other groups).

Notice that you can link these variable groups to Azure Key Vaults, so that is a great way to use secrets, certificates, keys … with the same variable name (of course the value changes between the Sandbox Vault and the Production Vault).

azure-pipelines.yml

Now our Env Groups are ready to be used within the pipelines.

- ${{ if eq(variables['Build.SourceBranchName'], 'main')}}:
  - group: Sienna-Hub-TF-VARs-Production
- ${{ if eq(variables['Build.SourceBranchName'], 'build')}}:
  - group: Sienna-Hub-TF-VARs-Build
- ${{ if eq(variables['Build.SourceBranchName'], 'develop')}}:
  - group: Sienna-Hub-TF-VARs-Sandbox

And within our Task, the appropriate value for the subscription id will be used depending on the source branch.

- task: TerraformCLI@0
      displayName: 'Apply Terraform'
      inputs:
        command: 'apply'
        environmentServiceName: service
        runAzLogin: true
        allowTelemetryCollection: true
        providerAzureRmSubscriptionId: '$(TF_VAR_subscriptionid)'