Search code examples
gitlabgitlab-cigitlab-ci-runner

if condition variables in gitlab-ci.yml


I have a simple request but can't find any sample code for it.

Suppose I want to set an environment variable depending on the branch name. Something like this (though I know this code doesn't work)

variables:
  rules:
    - if: '$CI_COMMIT_BRANCH != "master"'
      variables:
        env: "dev"
    - if: '$CI_COMMIT_BRANCH == "master"'
      variables:
        env: "prod"
  stackName: projectA-${env}

So the stackName or other variables can use ${env} as suffix in the name and I can also use ${env} in jobs , scripts or stages

How can I set it?


Solution

  • Answer my question after about 1 year. Here is my solution, and a simple solution.

    I refered the idea from @Time recommended.

    gitlab pipeline's environments are similar concept of CircleCI's context , if you are familar it.

    • create environments first, such as develop, staging, production, etc
    • create variables but assigned to different environments

    enter image description here

    • you can set the variables with same names, but assigned to different environments.

    When use it, you can add below codes to each task

    staging_build:
      stage: build
      environment:
        name: staging
      script:
        - echo ${AWS_ACCESS_KEY_ID}
      only:
        - staging
    
    production_build:
      stage: build
      environment:
        name: production
      script:
        - echo ${AWS_ACCESS_KEY_ID}
      only:
        - main