0

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)
Selig Drahcir
  • 37
  • 1
  • 7

1 Answers1

2

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.

  • I renamed the variables which - as I think you expected - didn't help. I don't think pipeline parameters can help because, long term, I want three stages, each with a different variable group. I've posted another question which hopefully makes my issue more obvious. https://stackoverflow.com/questions/69295715/variable-expansion-not-working-as-expected-in-azure-devops-yaml-pipeline-when-st – Selig Drahcir Sep 23 '21 at 07:34
  • @SeligDrahcir added a comment to your second question detailing what i meant by using parameters. Please let me know if this answers your question. basically you need to either statically set the environment name, use global variables, or use parameters and template expression. – Brittan DeYoung Sep 23 '21 at 12:07