Skip to main content
In this guide, you’ll learn how to define and manage variables at different scopes within a GitLab CI/CD pipeline. Proper use of variables helps you follow DRY principles, streamline maintenance, and reduce the risk of errors when updating image names, versions, or other configuration values.
GitLab CI/CD supports both custom variables and predefined variables. Use them to parameterize your pipeline and avoid hard-coding values.

1. Pain Point: Hard-Coded Values in Every Job

Here’s a typical pipeline that builds, tests, and pushes a Docker image. Notice how the registry, username, image name, and version are repeated in each job:
Maintaining pipelines like this is error-prone. Every change to imageName or version requires edits in multiple places.

2. Variable Scopes: Global vs. Job-Level

GitLab CI/CD provides two scopes for custom variables:
  • Global variables can be overridden by job-level variables with the same name.
  • Job-level variables are isolated to their job and not visible elsewhere.

3. Defining Global Variables

Move shared configuration into a global variables: block. This makes your pipeline DRY and easier to update.
  • DEPLOY_SITE is available to both jobs.
  • REVIEW_PATH applies only to deploy_review_job.

4. Refactoring Docker Jobs with Shared Variables

First, here’s a version that still repeats variables at the job level:
Each job redeclares USERNAME, REGISTRY, IMAGE, and VERSION—we can improve this.

5. Promoting Common Variables to Global Scope

Define all shared variables at the top level. Only sensitive or job-specific variables stay within the job.
Now only PASSWORD remains in docker_push, while USERNAME, REGISTRY, IMAGE, and VERSION are defined once.

6. Leveraging Predefined CI/CD Variables for Dynamic Tagging

Instead of a static latest tag, use $CI_PIPELINE_ID or $CI_COMMIT_SHA to uniquely tag each build:
Every pipeline run now pushes ascii-artwork:<pipeline_id>, making image versions traceable.

7. Viewing Expanded Variables in Job Logs

When the pipeline runs, GitLab replaces variables with their values:
Here, $VERSION was replaced by the numeric pipeline ID.

8. Job-Level Variables Are Isolated

Job-specific variables do not carry over to other jobs:
Log output:
$PASSWORD is empty because it was only defined in the docker_push job.
Avoid exposing sensitive variables in job logs. Use Masked Variables or Protected Variables to secure credentials and secrets.

9. Next Steps

Watch Video