Variable Usage in CI/CD Pipelines

CI/CD Fundamentals

3. Usage of Variables in CI/CD Pipelines

Secret variables are injected as environment variables during pipeline execution, enabling you to securely use them in your CI/CD scripts or commands, without hard-coding them in the .gitlab-ci.ymlfile.

3.1. Step by Step Guide

1. Adding Variables to Your Project

  1. Navigate to your project in GitLab.

  2. Go to Settings > CI/CD.

  3. Expand the Variables section.

    CI/CD settings, Variables section: an empty CI/CD Variables table with the columns Key, Value, Environments and Actions and an Add variable button.

  4. Click on Add variable.

  5. Enter the Key and Value for the variable.

  • We will create 2 variables for this example:
    • Variable 1:
      • Key: NORMAL_VAR_1
      • Value: ThisIsNormalValue1
    • Variable 2:
      • Key: NORMAL_VAR_2
      • Value: ThisIsNormalValue2

Add variable panel with the fields Type, Environments, Visibility, Flags (Protect variable and Expand variable reference ticked), Description, Key and Value, and the buttons Add variable and Cancel.

  1. Optionally, set the scope of the variable (Project-Level or Group-Level) and mark it as Protected or Masked.
    • Protected: Only available in protected branches or tags.
    • Masked: Prevents the variable’s value from being displayed in job logs.
    • Note: We will cover protected and masked variables in later lessons.
  2. Click Add variable to save the secret variable.

2. Using Variables in .gitlab-ci.yml

Once secret variables are added to your project, you can reference them directly within your .gitlab-ci.yml configuration file.

Example: Using a Secret Variable in a Job to Deploy an Application

deploy_production: 
  stage: deploy 
  script: 
    - deploy_script.sh $PRODUCTION_API_KEY 
  environment: 
    name: production 
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

In this example, $PRODUCTION_API_KEY is a secret variable injected into the deploy_script.sh script during pipeline execution.