Home > Enterprise >  How to pass environment variables in gitlab dynamically?
How to pass environment variables in gitlab dynamically?

Time:12-28

I am working on database deployment using gitlab CICD. Now there are two databases e.g. ABC and XYZ. One team is working on DB ABC and we are working on DB XYZ. Now the logic is same but if we need to pass DB name according to the team in gitlab pipeline, Whats the process fotr that ? for example if team 1 is working they will select DB ABC and all changes will be reflected on ABC and same for the other. I have already set up variables in gitlab-ci.yml but the task is manual as one team has to overwrite name of DB of other team and when it merges to master it chanhges the variable name everytime which is hard to manage .

    variables:
  DB_NAME_dev: DEMO_DB
  DB_NAME_qa: DEMO_DB
  DB_NAME_prod: DEMO_DB

Now if team 2 wants to work on their pipeline they have to change the value of DB_NAME_dev to their database which is a manual task. Is there a smart way to select DB name and the pipeline runs only for that database rather than manually editing the DB name ?

CodePudding user response:

How do you pass variables in GitLab? An alternative is to use Gitlab Variables. Go to your project page, Settings tab -> CI/CD, find Variables and click on the Expand button. Here you can define variable names and values, which will be automatically passed into the gitlab pipelines, and are available as environment variables there.

CodePudding user response:

You can also use the git branch method. Let's say the 'ABC' and 'XYZ' team pushes their code to specific branches (eg. branch starting with 'abc' or 'xyz'). For those, you need to export variables in before_script with only parameter.

Create branch-specific jobs in your CI file:

abc-dev-job:
  before_script:
    - export DB_NAME_dev: $DEMO_DB_abc
    - export DB_NAME_qa: $DEMO_DB_abc
    - export DB_NAME_prod: $DEMO_DB_abc
  only:
    - /^abc/.*$/@gitlab-org/gitlab

xyz-dev-job:
  before_script:
    - export DB_NAME_dev: $DEMO_DB_xyz
    - export DB_NAME_qa: $DEMO_DB_xyz
    - export DB_NAME_prod: $DEMO_DB_xyz
  only:
    - /^xyz/.*$/@gitlab-org/gitlab

This pipeline will only run when Team 'XYZ' or 'ABC' pushes their code to their team-specific branches which might start with the prefix xyz or abc (eg. xyz-dev, xyz/dev, abc-dev, etc.) And it will use variables accordingly. Note: you need to define variables in CI/CD settings. Thank you!

  • Related