Search code examples
azure-devopsyamlazure-pipelines-yaml

Azure DevOps YAML Pipeline set deploy environment based on variable


I am trying to write an Azure DevOps YAML pipeline where I set the deployment environment dynamical in a predecessor job. Here is a conceptual example of what I am trying to do:

pool:
  vmImage: 'ubuntu-latest'

stages:
- stage: SetVariable
  jobs:
  - job: SetVariableJob
    steps:
    - script: |
        echo "##vso[task.setvariable variable=environmentName;isOutput=true]TestEnvironmentName"
      name: setvarStep

- stage: Deploy
  dependsOn: SetVariable
  variables:
    environmentName: $[ dependencies.SetVariable.outputs['SetVariableJob.setvarStep.environmentName'] ]
  jobs:
  - deployment: DeployWeb
    environment: $(environmentName)
    strategy:
      runOnce:
        deploy:
          steps:
          - script: echo Hello, $(environmentName)!

Something is wrong, as the echo Hello, $(environmentName)! just outputs: Hello, !


Solution

  • azure-pipelines.yml

    pool:
      vmImage: 'ubuntu-latest'
    
    variables:
    - name: envname
      value: test
    
    stages:
    - stage: SetVariable
      jobs:
      - job: SetVariableJob
        steps:
        - script: |
            echo "##vso[task.setvariable variable=environmentName;isOutput=true]TestEnvironmentName"
          name: setvarStep
    
    - stage: Deploy
      dependsOn: SetVariable
      variables:
        environmentName: $[ stageDependencies.SetVariable.SetVariableJob.outputs['setvarStep.environmentName'] ]
      jobs:
      - deployment: DeployWeb
        environment: ${{ variables.envname }}
        strategy:
          runOnce:
            deploy:
              steps:
              - script: echo Hello, $(environmentName)!
    

    There are three things to pay attention to

    dynamically setting variables using setvariable has different format-pattern in different scenarios

    1. across stages setvariable, link
    2. deployment job setvariable, docs have sample code
    3. deployment job environment name should be fixed during whole-yaml file compilation, so do not provide the value which generated during the process.