Selig Drahcir
Selig Drahcir

Reputation: 79

Azure DevOps yaml pipeline variable expansion fails when variables are set in the stage

Using an Azure DevOps yaml pipeline, my variable expansion works if the variables are set in the root but not if they are set in the stage. Can anyone explain what I need to do to get the variable expansion to work with variables set in the stage?

#azure-pipelines.yml

# If I uncomment the lines below my variable expansion will work
# variables:
#   - group: Foo

stages:
  - stage: Bar
    # If I uncomment the lines below my variable expansion will **not** work
    # variables:
    #   - group: Foo
    jobs:
      - deployment:
        #  The expansion of $(environment) below...
        #  - works if the variables are set in the root
        #  - fails if the variables are set in the stage (error message: Environment $(environment) could not be found. )
        environment: $(environment)

Upvotes: 0

Views: 3331

Answers (1)

Brittan DeYoung
Brittan DeYoung

Reputation: 121

I think there are two issues here. One is that you are trying to use the variable name of “environment” when this is a predefined variable for deployment stages . See this azure doc on pre defined variables: https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml#deployment-job-variables-devops-services

You can see that environment is first in the list, so it is overriding yours.

So because the variable name is predefined on a deploy job, it is failing to set it for that job.

You should switch to a variable name that is not the same as a pre defined variable.

The second issue with that is that the variables for the stage are pulled in as that stage is running, but the environment is a definition of that deploy. This means it needs access to that variable before it runs in order to compile the pipeline file. Causing a chicken and egg problem. Typically if you want the deployment environment to be dynamic I would suggest using pipeline parameters and using template expression to dynamically set the environment. This is because parameters are available at compile time of the pipeline file.

https://learn.microsoft.com/en-us/azure/devops/pipelines/process/runtime-parameters?view=azure-devops

Hope this helps.

Upvotes: 2

Related Questions