G
G
goodweather2022-01-25 05:52:28
Continuous Integration
goodweather, 2022-01-25 05:52:28

Gitlab CI. How to set different values ​​of variables for different branches?

I tried to solve the problem like this:

image: alpine

variables: &global_variables
    ENV_VARIABLE: ${VAR_$CI_COMMIT_BRANCH}

stages:
    - test

test_job:
    stage: test
    variables:
        <<: *global_variables
    script:
        - echo "This job ran on the $CI_COMMIT_BRANCH branch."
        - echo "$CI_COMMIT_BRANCH - $ENV_VARIABLE"


I set the following variables in the CI settings:

VAR_master: "This is the master"
VAR_dev: "This is the dev"

And when I push to the master everything works for me, I get the message "This is the master". However, when I do the same in dev, I don't get the expected "This is a dev" message.

Why can this happen?
Or maybe my problem is solved in another way? How can I do that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Bladegreat, 2022-01-28
@Bladegreat

You can use rules for this .

build-container:
  stage: build
  rules:
    - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH'
      variables:
        image_tag: "$CI_REGISTRY_IMAGE"
      changes:
        - Dockerfile
    - if: '$CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH'
      variables:
        image_tag: "$CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG"
      changes:
        - Dockerfile
  services:
    - docker:18-dind
  before_script:
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
  script:
    - docker build --pull -t ${image_tag} .
    - docker push ${image_tag}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question