Why can't I use a variable to define the environment property in the Azure Pipeline YAML config file?

Viewed 740

I'm trying to create a deploy pipeline YAML template for all environments/stages. I've set up the Environments on Azure DevOps so that I can add checks and approvals on the Test and Prod environments before they get deployed. I've set up a library group for each stage and each one of them has a variable called 'env' which defines the current stage running in the pipeline. For some reason, the environment property under the deployment job (see code snippet below) doesn't read that variable.

Has anyone faced this issue before, or is there a reason why the variable won't be read for that specific property?

Note: I've tested the variables and they do work, for example, the stage property outputs as 'deploy-dev/test/prod' (depending on the environment)

- stage: deploy-$(env)
  jobs:
  - deployment: DeployWeb
    displayName: deploy Web App
    pool:
      vmImage: 'Ubuntu-latest'
    # creates an environment if it doesn't exist
    environment: 'smarthotel-$(env)'
    strategy:
      runOnce:
        deploy:
          steps:
          - script: echo Hello world
1 Answers

You can't do this because it have to be know at compilation phase.

But you can try this (lets name this file deploy.yml):

parameters:
- name: env
  type: string
  default: 'dev'

stages:
- stage: deploy-${{ parameters.env }}
  jobs:
  - deployment: DeployWeb
    displayName: deploy Web App
    pool:
      vmImage: 'Ubuntu-latest'
    # creates an environment if it doesn't exist
    environment: 'smarthotel-${{ parameters.env }}'
    strategy:
      runOnce:
        deploy:
          steps:
          - script: echo Hello world

and then you need to run as follows (in build.yml file):


stages:
- template: deploy.yml
  paramaters:
    env: dev
- template: deploy.yml
  paramaters:
    env: qa
- template: deploy.yml
  paramaters:
    env: prod
Related