Search code examples
azure-devopsazure-pipelinesazure-pipelines-yaml

Azure Pipeline deploy job with dynamic environment


We have two environments defined, "stage" and "prod". Prod requires approval for deploying, where as stage does not.

What I'm trying to achieve is that if the pipeline runs against the master branch, it should use the prod environment, and all other branches should use the stage environment.

Problem is that I can't seem to be able to change the environment in runtime. I've also tried using templates, which sort of works, except that I can't pass runtime information as parameters to the template.

I also tried using two deployment jobs, one for each environment and then chose job based on conditions, however, as soon as the pipeline involves the prod environment, whether it's going to be used or not, it will ask for approval.


Solution

  • I will start with first last one:

    I also tried using two deployment jobs, one for each environment and then chose job based on conditions, however, as soon as the pipeline involves the prod environment, whether it's going to be used or not, it will ask for approval.

    Resource restriction are evaluated on stage level so if you put those deployment jobs on the same stage (or you didn't define a stage - then you have implicit stage) - this is the reason why it asks for approval. If you move deployment jobs to seprate stages you won't be asked for approval. Please keep in mind to move condition to a stage level.

    Another apporach it would be conditional for envrionment as follows:

    jobs:  
    - deployment: DeployWeb
      displayName: deploy Web App
      ${{ if eq(variables['Build.SourceBranchName'], 'master') }}:
        environment: 'Dev'
      ${{ if ne(variables['Build.SourceBranchName'], 'master') }}:
        environment: 'campo-dev'
      strategy:
        # Default deployment strategy, more coming...
        runOnce:
          deploy:
            steps:
            - checkout: self 
            - script: echo my first deployment