Andrew Craswell
Andrew Craswell

Reputation: 674

Azure Devops multi-stage pipeline environment name not set properly

I'm building a multi-stage pipeline, and I'm using a lot of templates as the deploy jobs, tasks, and stages for each environment has a lot of shared logic. So on the stage I'm setting a environmentName variable, then using that in each of the jobs:

  - stage: StageReleaseProd
    displayName: Stage Release (Prod)
    variables:
      environmentName: 'prod'
    jobs:
      - deployment: DeployWebApp
        displayName: Deploy Wep App
        pool:
          vmImage: $(vmImage)
        environment: $(environmentName)
        strategy:
          runOnce:
            deploy:
              steps:
                - template: config/pipelines/templates/_deploy.task.yml
                  parameters:
                    environmentName: $(environmentName)

Often times this works really well. I can see all the environments in the ADO UI and can add approval checks between stages. But I'm also frequently hitting this:

enter image description here

Sometimes the variable doesn't get interpolated. It feels like this happens 50% of the time, but I also can't deduce a pattern as to why. For now my workaround is to hardcode the environment variable without using parameters, but that severely limits how I can templatize all our pipelines.

Upvotes: 1

Views: 7538

Answers (1)

DreadedFrost
DreadedFrost

Reputation: 2970

The issue lies with when job name is being populated. In multi stage ADO pipelines if the variable is being used in a job or stage name it is being used at compile time vs run time. Try referencing your variable like ${( variables.envronmentName })

Here are the different ways to reference a variable and the implications of doing so: enter image description here

The other thing to call out with variables, as they are a little tricky to keep track of in multi stage pipelines, is that there is the ability to store variables in an ADO variable group. Depending how the solution is structured this may actually simplify things for you.

Another option if you truly want to make this a variable is define a variable template. This would be done by creating a seperate yaml file similar to:

variables:
  environmentNameDEV: dev

Then reference this template in your azure-pipelines-yml file like:

variables:
- template: variables.yml

And lastly when creating your stage name:

- stage: ${{ variables.environmentNameDEV }}

Downside is a separate variable name for each environment. Upside is if all repos use the same variable template can ensure consistency across everything with naming standards.

Upvotes: 2

Related Questions