Run Tests Up to 70% Faster than Traditional Test Grids

HyperExecute Is an AI-Native Test Orchestration Platform to Run Your Automation Test Suites with Blazing Fast Speed.

GitLab Environment Variables: How to Set, Mask and Scope CI/CD Variables

GitLab environment variables explained: set CI/CD variables in YAML or settings, mask and protect secrets, use predefined variables and fix empty values.

Published

Summarise with AI

GitLab CI/CD variables are the environment variables that GitLab makes available to every job's shell. You can define them in .gitlab-ci.yml under the variables: section, or in Settings > CI/CD > Variables at the project, group or instance level. Secrets go in the settings (they should be masked and protected). GitLab also injects a number of predefined variables such as CI_COMMIT_BRANCH and CI_COMMIT_SHA.

Looking for the environment variables that configure the self-managed GitLab server itself? That's a different topic altogether (see GitLab's environment variables for GitLab Self-Managed). This guide is about CI/CD jobs.

This guide covers where you define each type of variable, what value takes precedence when two variables collide, how to mask and protect secrets, which of the pre-defined variables are used by the test jobs the most and how you pass the values on to the tests that are actually running on the cloud grid. Variables are the inputs to any test orchestration setup; the same test suite will run against staging or production, smoke or full, depending on what the variable says.

TL;DR

GitLab environment variables are CI/CD variables that GitLab exposes to every job's shell. Define non-secret values in .gitlab-ci.yml, secrets in Settings > CI/CD > Variables (masked and protected), and use predefined variables for commit and branch facts. When two variables share a name, the higher-precedence one wins.

GitLab Variable Sources and Settings

  • GitLab CI environment variables: GitLab CI environment variables come from variables: in .gitlab-ci.yml, from project, group or instance settings, and from GitLab itself. A job-level value overrides the top-level one.
  • GitLab CI predefined variables: GitLab sets predefined variables such as CI_COMMIT_SHA and CI_COMMIT_REF_SLUG automatically. CI_COMMIT_BRANCH is absent in merge request and tag pipelines.
  • GitLab masked variables: A masked value shows as [MASKED] in job logs and needs one line, no spaces and 8+ characters. Masking is a log filter, not access control.
  • GitLab protected variables: A protected variable reaches only pipelines on protected branches or protected tags, so a job on an unprotected feature branch reads it as empty.
  • GitLab CI file variable: A file type variable saves its value to a temporary file and holds that file's path. Allowed in .gitlab-ci.yml: No; set it in project, group or instance settings.
  • GitHub Actions comparison: GitHub workflows set the same kind of values with an env map and configuration variables; see GitHub Actions environment variables.
  • HyperExecute: TestMu AI's HyperExecute takes GitLab values through repeated --vars flags and maps them into env in hyperexecute.yaml; with strict: true, a misspelled name stops the CLI with exit code 1.

What Are GitLab CI/CD Variables?

GitLab CI/CD variables are key-value pairs which GitLab passes to the jobs as environment variables. The GitLab documentation refers to them as "a type of environment variable" and describes their use in controlling jobs and pipelines, storing values you want to reuse and keeping secrets out of the repository.

There are three sources:

SourceWhere it's setWho can change itTypical use
.gitlab-ci.yml variables: (top level or job level)In the repositoryAnyone who can pushNon-secret config: TEST_ENV, NODE_VERSION
Project/group / instance variablesSettings > CI/CD > Variables (or the API)Maintainer (project), Owner (group), Administrator (instance)Secrets and per-environment values
Predefined variablesSet by GitLab automaticallyNobodyCommit, branch, pipeline and job facts

GitLab's docs are very clear on the subject of secrets: "Sensitive variables containing values like secrets or keys should be added in the UI." Anything that's in your .gitlab-ci.yml is going to be readable by everyone who can read the repository. (If you're running Jenkins as well, then have a look at how to set your Jenkins pipeline environment variables.)

For a quick visual walkthrough of this concept, watch the video below from TestMu AI.

Youtube thumbnail

Subscribe to the TestMu AI YouTube channel for more tutorials on testing and automation.

How Do I Set Environment Variables in .gitlab-ci.yml?

Add a variables: block at the top level for defaults that every job sees, and a variables: block inside a job for values that job specifically needs. A variables: block at the job level with the same name as one at the top level will override the top-level one.

# .gitlab-ci.yml
variables:            # defaults for every job
  TEST_ENV: "staging"
  NODE_VERSION: "20"

stages: [build, test]

build-job:
  stage: build
  image: node:20
  script:
    - npm ci
    - echo "APP_VERSION=$(node -p 'require("./package.json").version')" >> build.env
  artifacts:
    reports:
      dotenv: build.env

unit-tests:
  stage: test
  image: node:20
  variables:
    TEST_ENV: "ci"    # job level: overrides the top-level "staging"
  script:
    - echo "Testing $APP_VERSION on $TEST_ENV for $CI_COMMIT_REF_SLUG"
    - npm test

Three rules from GitLab's docs that save debugging time:

  • Quote values. VAR1: 012345 is parsed as an octal number; VAR1: "012345" stays a string.
  • Use $VAR or ${VAR} in scripts. On Windows runners, PowerShell will use $env:VAR and cmd will use %VAR%.
  • after_script runs in a separate shell. Variables you export in before_script reach script, but not after_script.
Youtube thumbnail

Recorded in 2021. GitLab's variables screen has changed since (masked is now the default and there is a Masked and hidden option), so follow the steps in this article for the current UI.

How Do I Add a Masked or Protected Variable in GitLab?

Secrets such as API keys go in Settings > CI/CD > Variables rather than in the YAML. Each variable in that section has a type, a visibility setting, a protection flag and an environment scope (environment scope is available for project variables on all tiers; group-level environment scope requires Premium or Ultimate).

SettingWhat it doesRequirements and limits
MaskedValue shows as [MASKED] in job logs. Default since GitLab 18.3.Single line, no spaces, 8+ characters, must not match the name of an existing predefined or custom variable
Masked and hiddenMasked, and the value can't be revealed in the UI after savingCan only be chosen when the variable is created
ProtectedOnly pipelines on protected branches or protected tags get the valueMerge request pipelines can optionally access it
Environment scopeLimits the value to an environment (*, production, review/*)Project variables: all tiers. Group variables: Premium or Ultimate
Expand variable referenceLets the value reference other variablesOff by default for UI variables; can't be combined with masking
Type: FileSaves the value to a temp file; the variable holds the file pathProject, group and instance variables only, not .gitlab-ci.yml

Masking is a log filter rather than access control. The GitLab documentation makes it clear that masking "is not a guaranteed way to prevent malicious users from accessing variable values". Treat anyone who can edit .gitlab-ci.yml on a branch that's receiving a variable as someone who can read that variable. Use protected variables so that feature branches never end up with production keys. If you're also using GitHub, then the same applies to GitHub Actions secrets.

Note

Note: Run the suite that these variables configure on cloud infrastructure. TestMu AI HyperExecute will run your Selenium, Playwright, Cypress and Appium suites in parallel from a single YAML file and can be triggered from any of the major CI pipelines (including GitLab). Start free.

Which GitLab Variable Wins if Two Have the Same Name?

GitLab applies a fixed precedence order. From highest to lowest, per the CI/CD variables documentation (December 2026):

  • Pipeline execution policy or scan execution policy variables (only for jobs the policy adds)
  • Manual job variables
  • Pipeline variables (Run pipeline page, schedules, API, ci.variable push option, upstream pipelines)
  • Project variables
  • Group variables (closest subgroup wins)
  • Instance variables
  • dotenv report variables from jobs in dependencies or needs
  • .gitlab-ci.yml variables: rules:variables in the job, then job variables, then workflow:rules:variables, then top-level variables
  • Deployment variables
  • Predefined variables
GitLab CI/CD variable precedence from policy variables down to predefined variables

The practical consequence: a project variable named TEST_ENV silently beats TEST_ENV in your YAML. If a value in a job isn't what the YAML says, check Settings > CI/CD > Variables first.

Which of the GitLab Predefined Variables Do the Test Jobs Use the Most?

GitLab sets these automatically (full list in the predefined variables reference). Availability matters: several exist only in certain pipeline types.

VariableValueAvailable in
CI_COMMIT_SHA / CI_COMMIT_SHORT_SHAFull commit SHA / first 8 charactersAll pipelines
CI_COMMIT_REF_NAMEBranch or tag being builtAll pipelines
CI_COMMIT_REF_SLUGRef name lowercased, max 63 bytes, non-alphanumerics replaced by -All pipelines; safe in URLs and host names
CI_COMMIT_BRANCHBranch nameBranch pipelines only; absent in merge request and tag pipelines
CI_COMMIT_TAGTag nameTag pipelines only
CI_DEFAULT_BRANCHProject's default branchAll pipelines
CI_MERGE_REQUEST_IIDMerge request numberMerge request pipelines only (open MR)
CI_MERGE_REQUEST_SOURCE_BRANCH_NAME / ..._TARGET_BRANCH_NAMEMR source/target branchMerge request pipelines only
CI_PIPELINE_ID, CI_JOB_IDPipeline and job IDsEvery job
CI_PROJECT_DIRPath the repository is cloned toEvery job
CI_NODE_INDEX / CI_NODE_TOTALIndex / count of parallel copies of a jobCI_NODE_INDEX only in jobs using parallel:; CI_NODE_TOTAL is 1 when the job doesn't use parallel:

CI_COMMIT_BRANCH is the one that causes the most confusion. A rule such as if: $CI_COMMIT_BRANCH == "main" will never match in a merge request pipeline as that variable isn't set in that context. Use CI_MERGE_REQUEST_IID to detect merge request pipelines and CI_COMMIT_REF_SLUG if you need a branch-like value in all pipeline types. CI_NODE_INDEX and CI_NODE_TOTAL are what drive the splitting of suites across parallel job copies.

Run tests up to 70% faster on the TestMu AI cloud grid

How Do I Pick Between Smoke and Full Tests With Variables?

rules:variables are only set when a rule matches, and they are at the top of the .gitlab-ci.yml precedence list. This job runs the full suite on the default branch and a smoke suite on merge requests:

e2e-tests:
  stage: test
  image: node:20
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      variables:
        TEST_SUITE: "full"
    - if: $CI_MERGE_REQUEST_IID
      variables:
        TEST_SUITE: "smoke"
  script:
    - npm run "test:$TEST_SUITE"

If neither rule matches (e.g. a tag pipeline), the job doesn't run, and so TEST_SUITE is never empty inside it.

Mixing merge-request rules with jobs that have no rules can start two pipelines for one push to a branch with an open merge request. GitLab's workflow rules docs give the standard fix: run merge request pipelines when an MR is open, and branch pipelines otherwise.

workflow:
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
      when: never
    - if: $CI_COMMIT_BRANCH

How Do I Pass a Variable From One GitLab Job to Another?

Shell variables die with the job. To pass a value on to a later job you write it to a dotenv file and declare it as a dotenv report (as build-job does in the first example). Later jobs (either those which list it in needs or dependencies) will then receive APP_VERSION as a normal variable.

GitLab's dotenv variable rules are very strict: UTF-8 only, no blank lines, no # comments, variable names can only contain letters, digits and underscores, no multiline values, quotes are preserved literally and the file size is capped at 5 kb. The GitLab docs also state: "Don't include sensitive data like credentials, API keys, or tokens in dotenv files. Pipeline users can access dotenv file contents."

Can GitLab Load Variables From a .env File or a Secrets Manager?

GitLab doesn't read a .env file on its own; your job script has to do that. For non-secret config that you're committing to the repository, you'd set -a; . ./ci.env; set +a in your before_script to export every KEY=value line to the rest of the job. For a secret file you wouldn't commit, just store the entire file as a File type variable (which gives the job a path) and then load that path instead:

integration-tests:
  stage: test
  image: node:20
  before_script:
    - 'test -f "$TEST_SECRETS_FILE" || { echo "TEST_SECRETS_FILE is not set or not available on this branch"; exit 1; }'
    - set -a; . "$TEST_SECRETS_FILE"; set +a
  script:
    - npm run test:integration

Here TEST_SECRETS_FILE is a protected File type project variable whose value is the .env file contents. Values loaded in this way are not masked in logs, so never echo them.

For Premium and Ultimate teams, GitLab can also pull secrets at job time from an external provider. The external secrets documentation lists HashiCorp Vault, Google Cloud Secret Manager, Azure Key Vault and AWS Secrets Manager (all of which can be authenticated via ID tokens). Unlike CI/CD variables, which are available to every job, each job would need to explicitly request each external secret.

How Do I Pass GitLab Variables to My Tests on HyperExecute?

The Nightwatch on HyperExecute guide has you export LT_USERNAME and LT_ACCESS_KEY and then run ./hyperexecute --config ... with no --user/--key flags. GitLab then exports all of the CI/CD variables to the job shell. So the setup is two masked/protected project variables and a short job.

Step 1. In Settings > CI/CD > Variables, add LT_USERNAME and LT_ACCESS_KEY (from your TestMu AI profile). Mark both as Masked and Protected and protect the branches that run this job.

Step 2. Add the job:

hyperexecute-e2e:
  stage: test
  image: ubuntu:24.04
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
  before_script:
    - 'test -n "$LT_USERNAME" || { echo "LT_USERNAME is not set or not available on this branch"; exit 1; }'
    - 'test -n "$LT_ACCESS_KEY" || { echo "LT_ACCESS_KEY is not set or not available on this branch"; exit 1; }'
    - apt-get update && apt-get install -y wget
    - wget -q https://downloads.lambdatest.com/hyperexecute/linux/hyperexecute
    - chmod u+x hyperexecute
  script:
    - ./hyperexecute --config hyperexecute.yaml --vars "build=$CI_COMMIT_SHORT_SHA" --vars "branch=$CI_COMMIT_REF_SLUG"

The HyperExecute CLI reference docs --vars as a repeatable flag. The example in there passes four values as --vars "org=…" --vars "product=…" --vars "email=…" --vars "email1=…". The same reference docs list the Linux binary download URL that's used in the job above.

The two test -n lines make the job fail with a clear message when a protected variable is missing, instead of failing later with an authentication error. Credentials never appear in the YAML, in a URL or on the command line.

Step 3. Reference the passed values in hyperexecute.yaml. HyperExecute's YAML deep dive docs will show you the vars you can use anywhere in the file as ${name}, and env which will set environment variables on the test machines:

# hyperexecute.yaml (excerpt: keep your existing runson, discovery and runner settings)
strict: true
env:
  TEST_ENV: staging
  BUILD_SHA: ${build}
  BRANCH: ${branch}

Your tests then just show BUILD_SHA and BRANCH as any other environment variable. strict: true is intentional. Without it, an undefined ${name} will simply generate a warning and the tests will carry on with an empty BUILD_SHA.

With it, any variable used in the YAML must be defined either in vars or in the environment; otherwise the job will error. Values you pass in via --vars do meet the strict mode requirements (the docs don't make this clear): with both flags set, BUILD_SHA and BRANCH arrive on the test machine, and a misspelled name (biuld=) stops the CLI before upload with exit code 1.

Step 4. Prove the job can fail. The HyperExecute CLI docs don't actually specify the exit code when a test fails, but the CLI exits with code 1 (Failed tasks found.) when one does. Before you go ahead and make that a required check, push a branch with a test that you know will fail and confirm that the GitLab job does in fact turn red.

HyperExecute CLI runs: strict mode rejects a misspelled --vars name, both values reach the test machine, and a failed test exits with code 1

For context on what parallel runs achieve: Boomi reported their full test base going from 9.5 hours down to under 4 hours on their first HyperExecute runs (customer reported, from the HyperExecute page).

Why Is My GitLab CI Variable Coming Back as Empty?

An empty variable almost always comes from one of six causes:

SymptomLikely causeFix
Empty only on feature branchesVariable is Protected; branch isn'tProtect the branch, or unprotect a non-secret variable
Empty in merge request pipelinesUsing CI_COMMIT_BRANCH (not set in MR pipelines)Use CI_MERGE_REQUEST_SOURCE_BRANCH_NAME or CI_COMMIT_REF_SLUG
Empty in after_scriptExported in before_script/scriptafter_script is a separate shell; write to a file or set it in variables:
Wrong value, not emptyA higher-precedence project or pipeline variable with the same nameCheck Settings > CI/CD > Variables and pipeline variables
Empty in one environment onlyEnvironment scope doesn't match the job's environment:Widen the scope or set environment:name
Leading zeros lost or number changedUnquoted YAML valueQuote it: "012345"

Don't go around "fixing" this by just printing out all the variables with env in a job log as the masked values will be hidden but the unmasked secrets will still be there.

The GitLab Variable Hygiene Checklist

Eight checks before a pipeline handles real credentials:

  • There's absolutely no secret in the .gitlab-ci.yml. Any keys and tokens are stored in Settings > CI/CD > Variables.
  • Every secret is masked and, wherever possible, hidden. Remember masking requires 8+ characters, one line and no spaces.
  • Production secrets are protected. Only protected branches and tags will receive them.
  • Environment scope is set so that staging jobs can't read the production values (project variables on any tier; group-level scope requires Premium or Ultimate).
  • Quoted YAML values. No octal or boolean surprises.
  • Missing-variable guards (test -n "$VAR" || exit 1) at the top of jobs that need secrets.
  • No secrets in dotenv artifacts. Pass versions and IDs, not keys.
  • A forced-failure run of each test job before it becomes a required check.

Conclusion

Start by moving every key out of .gitlab-ci.yml into masked, protected GitLab environment variables, then add a test -n guard to each job that reads them. Before the job becomes a required check, push one deliberately failing test and confirm the pipeline turns red.

Your variables now determine which environment and suite get run. Run that suite in parallel on HyperExecute from the same GitLab job and get AI root cause analysis on any failures.

To run your first test, start free, or
for a full walkthrough of the product.

Was this helpful?

Authors

Anmol Gupta

Anmol Gupta

Author · 17 posts

Anmol Gupta is Vice President of Product Management at TestMu AI, driving HyperExecute, the test orchestration cloud that runs and accelerates automated test execution. He led the development of the Unified Test Execution Cloud Platform and now leads a 30-member cross-functional product organization across product lines contributing $7M+ in revenue. He brings over nine years of experience and previously co-founded the SaaS company Timble as CTO, where he grew the team from 5 to 40 and launched an AI KYC platform that processed 600K+ applications in five months while cutting verification time from 12 minutes to under 30 seconds. Anmol holds an MTech and BTech from IIT Delhi.

Mayank Bhola

Mayank Bhola

Reviewer

Mayank Bhola is Co-Founder and Head of Products at TestMu AI, where he leads the entire product portfolio across KaneAI, Kane CLI, HyperExecute, SmartUI, the Real Device Cloud, Accessibility, and other software testing product lines. As an early Lead Architect he designed and built the company's flagship Tunnel technology from scratch, created the React-based automation platform, and architected the data-intensive pipelines and FAAS services that scale it. He brings more than 10 years of experience in software development and product engineering, with earlier roles as Head of Technology at Juggernaut Books and Senior Software Engineer at PressPlay TV and Zomato. Mayank holds a B.Tech in Computer Engineering from JIIT Noida.

GitLab Environment Variables FAQs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests