How can I set the stage environment from a condition

Hello,
I would like to know whether it is possible to achieve something like this:

deploy:
  stage: deploy
  environment: if($CI_COMMIT_BRANCH == "main") then "production" else "staging"

Or if there is another better way I can do this. This is because I wish to use a single gitlab-ci.yml file to deploy my app. I managed to create both environments with their environment variables. Therefore I would like the stage to run with variables under the correct environnment.

Thanks.

You should create two jobs

deploy-to-production:
  stage: deploy
  rules:
     - if: '$CI_COMMIT_BRANCH == main'
  environment: "production"

deploy-to-staging:
  stage: deploy
  rules:
     - if: '$CI_COMMIT_BRANCH != main' # or any other condition
  environment: "production"

If you have many things in your deploy job and don’t want to repeat yourself you can create a generic hidden job and extend it.

.deploy: # the dot for hidden job
  variables:
    COMMON_VAR: VAR1
  script: echo "deploy"
  before_script: echo "something"

deploy-to-production:
  extends: .deploy
  rules:
     - if: '$CI_COMMIT_BRANCH == main'
  environment: "production"

deploy-to-staging:
  extends: .deploy
  rules:
     - if: '$CI_COMMIT_BRANCH != main' # or any other condition
  environment: "staging"

Even better you can rid of the generic job

deploy-to-staging:
  script: echo "deploy"
  before_script: echo "something"
  rules:
     - if: '$CI_COMMIT_BRANCH != main'
  environment: "staging"

deploy-to-production:
  extends: deploy-to-staging
  rules: # override this
     - if: '$CI_COMMIT_BRANCH == main'
  environment: "production" # and this
2 Likes

A thought which I cannot verify at the moment, typing on my iPad:

Use conditional rules to specify a variable (added in GitLab 13.10, example also in the pipeline efficiency workshop: Projects | GitLab)

Likely the global workflow:rules:variables are needed: Keyword reference for the `.gitlab-ci.yml` file | GitLab

Use the defined variable as a value reference for the environment attribute.

Copying the docs example, with adding the job - should work, please review.

variables:
  DEPLOY_VARIABLE: "staging"

workflow:
  rules:
    - if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
      variables:
        DEPLOY_VARIABLE: "production"  # Override globally-defined DEPLOY_VARIABLE


job-deploy:
  environment: $DEPLOY_VARIABLE
  # …
1 Like

Thank you so much for this!! Took me to the right direction in solving this!!

1 Like