Search code examples
gitlabgitlab-cigitlab-ce

Set CI/CD variables depending on environment


We have multiple environments (staging, production...) and I don't want to put sentitive informations like database passwords inside the codebase. For this, I want to use environment variables provided by GitLab CI/CD.

However I don't know how to tell GitLab to run a different set of variables depending on my environment.

What I've done so far:

1- Create environments : Via UI (Project => Operations => Environments : Here I created 2 environments, STAGING and PRODUCTION

2- Create variables Via UI (Project => Settings => CI/CD => Variables : Here I created the variable DB_PASSWORD twice (with of course different values assigned) , one with environment scope set to STAGING, the other one to PRODUCTION.

Now what I want to do is run my project's pipeline. So I go to Project => CI/CD => Pipelines => Run Pipeline and here I expect GitLab CI to ask me if I would like to run my pipeline with the set of variables set for STAGING or PRODUCTION but it doesn't.

How I am supposed to tell GitLab that I want to run my pipeline using DB_PASSWORD variable with the value corresponding to the environment I want to target?


Solution

  • You need to specify the environment in your gitlab-ci.yml file, see here

    Example from official gitlab docs:

    stages:
      - test
      - build
      - deploy
    
    test:
      stage: test
      script: echo "Running tests"
    
    build:
      stage: build
      script: echo "Building the app"
    
    deploy_staging:
      stage: deploy
      script:
        - echo "Deploy to staging server"
      environment:
        name: staging
        url: https://staging.example.com
      only:
        - master
    

    In this example when running deploy_staging the environment is set to staging and thus you can access the defined Variables for the environment, like so:

    deploy_staging:
      stage: deploy
      script:
        - echo "Deploy to staging server"
      environment:
        name: staging
        url: https://staging.example.com
      variables:
        DB_PASS: ${DB_PASSWORD}              # which is your defined variable within Gitlab CI
      only:
        - master