Course contentsShow
← Cloud and Infrastructure
Lesson 1736 of 2,98936. GitLab CI/CDFree lesson

Environment Variables in GitLab CI

Use predefined CI variables, define custom variables, and understand variable precedence and scope.

Environment Variables in GitLab CI

What You'll Learn

You'll learn how to use predefined CI variables, define custom variables, and understand how variable precedence and scope work in GitLab CI pipelines.

The Basics of CI Variables

Environment variables in GitLab CI are key-value pairs that make your pipelines dynamic and reusable. Think of them like labeled containers that hold information your jobs need—deployment URLs, version numbers, credentials, or configuration settings.

GitLab provides predefined variables automatically. These include CI_COMMIT_SHA (the commit hash), CI_PROJECT_NAME (your project name), CI_PIPELINE_ID (unique pipeline identifier), and dozens more. You don't create these—they're already there, ready to use in your scripts.

Defining Custom Variables

You can define custom variables at multiple levels:

  • Pipeline level: In .gitlab-ci.yml under variables:
  • Job level: Within a specific job definition
  • Project/Group level: Through GitLab's UI settings
variables:
  DEPLOY_ENV: "production"
  APP_VERSION: "1.2.3"

build_job:
  variables:
    BUILD_FLAGS: "-v"
  script:
    - echo "Building version $APP_VERSION"
    - echo "Environment is $DEPLOY_ENV"

Variable Precedence and Scope

Variables follow a precedence hierarchy (highest to lowest):

  1. Job-level variables (most specific)
  2. Pipeline-level variables in .gitlab-ci.yml
  3. Project/Group settings variables
  4. Predefined CI variables

Scope determines where variables are accessible. Job-level variables only exist in that job, while pipeline-level variables are available to all jobs in that pipeline.

Key Takeaway: Environment variables make GitLab CI pipelines flexible and secure—use predefined variables for CI metadata, define custom variables for configuration, and remember that job-level variables override pipeline-level ones.