10 GitLab CI/CD Secrets Used by DevOps Experts
10 advanced GitLab CI/CD techniques with YAML: workflow rules, needs, !reference, CI/CD components, OIDC id_tokens, hidden variables and resource_group.
The GitLab techniques experienced DevOps engineers rely on are mostly pipeline-design features hiding in the CI/CD YAML reference: workflow:rules to stop duplicate pipelines, needs for DAG ordering, !reference and CI/CD components for reuse, OIDC ID tokens instead of stored cloud keys, masked and hidden variables, resource_group for safe deploys, and auto-cancel for wasted runs.
This guide explains ten of them with working .gitlab-ci.yml snippets checked against the GitLab documentation in November 2026. It assumes you already know stages, jobs and runners. If you are new to GitLab CI, start with our beginner-friendly GitLab CI tips for freshers, then come back. Runner tuning is covered separately in 15 GitLab runner optimization tips.
Key takeaways
- Add a
workflow:rulesblock to every project so branch and merge request pipelines do not both run for the same push. needslets a job start as soon as its real dependencies finish, instead of waiting for the whole previous stage.- Share pipeline logic with CI/CD components (
include:component) pinned to a version, plusextendsand!referenceinside a project. - Use
id_tokensto authenticate to AWS, Azure, GCP or Vault through OIDC, so no long-lived cloud keys sit in CI/CD variables. - Since GitLab 18.3 new variables default to masked. "Masked and hidden" values cannot be revealed in the UI after saving.
resource_groupstops two deploy jobs from hitting the same environment at once;interruptibleplusworkflow:auto_cancelstops paying for outdated runs.
The ten techniques at a glance
| # | Technique | Keyword | What you gain |
|---|---|---|---|
| 1 | One pipeline per change | workflow:rules | No duplicate branch and MR pipelines |
| 2 | DAG job ordering | needs | Shorter pipelines |
| 3 | Path-based job rules | rules:changes | Skip jobs unrelated to the change |
| 4 | Reuse inside a project | extends, !reference | Less copy-paste YAML |
| 5 | Reuse across projects | include:component | Versioned, shared pipeline building blocks |
| 6 | Keyless cloud access | id_tokens | No stored cloud credentials |
| 7 | Safer variables | Masked, hidden, protected, file type | Less secret leakage |
| 8 | Deployment concurrency control | resource_group | One deploy per environment at a time |
| 9 | Cancel redundant runs | interruptible, workflow:auto_cancel | Lower runner cost |
| 10 | Parent-child and matrix pipelines | trigger:include, parallel:matrix | Manageable monorepo and multi-target builds |
1. Stop duplicate pipelines with workflow:rules
Without a workflow block, pushing to a branch that has an open merge request can start two pipelines: a branch pipeline and a merge request pipeline. That doubles runner time and confuses people about which result counts. This pattern, based on GitLab's documented examples, runs MR pipelines when an MR exists 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
- if: $CI_COMMIT_TAG
Rules are evaluated top to bottom and the first match wins. The second rule drops the branch pipeline when an MR is already open for that branch. See GitLab workflow examples for variants.
2. Use needs to build a DAG
By default a job waits until every job in the previous stage finishes. With needs, a job starts as soon as the specific jobs it depends on succeed. In a pipeline that builds a frontend and a backend, the frontend tests no longer wait for a slow backend build.
stages: [build, test, deploy]
build-frontend:
stage: build
script: npm ci && npm run build
build-backend:
stage: build
script: ./gradlew assemble
test-frontend:
stage: test
needs: [build-frontend]
script: npm test
test-backend:
stage: test
needs: [build-backend]
script: ./gradlew test
deploy:
stage: deploy
needs:
- job: test-frontend
- job: test-backend
- job: security-scan
optional: true
script: ./deploy.sh
optional: true lets the deploy job run even when security-scan was skipped by its own rules. Without it, a missing job makes the pipeline invalid. A job with needs: [] starts immediately when the pipeline is created.
3. Run jobs only when relevant files change
rules:changes skips jobs whose files did not change. In merge request pipelines GitLab compares against the target branch. For branch pipelines you can set the comparison point explicitly with compare_to:
docker-build:
script: docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA .
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
changes:
paths:
- Dockerfile
- src/**/*
compare_to: refs/heads/main
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
Keep the second rule so the default branch always builds. A path filter that is too narrow is a common reason a broken image reaches main without anyone noticing.
4. Reuse YAML with extends and !reference
Hidden jobs (names starting with a dot) act as templates. extends merges a template into a job. The !reference tag goes further: it pulls in one section, such as a list of script lines or rules, from another job.
.aws-login:
before_script:
- aws sts get-caller-identity
.deploy-rules:
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
deploy-api:
extends: .deploy-rules
before_script:
- !reference [.aws-login, before_script]
- echo "extra setup for the API"
script: ./deploy-api.sh
extends merges hashes but replaces arrays, so a job that sets its own before_script loses the template's lines. !reference solves that by inserting the template lines where you want them. Both are documented on the YAML optimization page.
5. Share pipelines across projects with CI/CD components
CI/CD components are reusable pipeline units with typed inputs, published to the CI/CD Catalog. They replace the older habit of including raw template files from a shared repository.
# templates/secret-detection.yml in the component project
spec:
inputs:
stage:
default: test
---
secret-detection:
stage: $[[ inputs.stage ]]
script: ./scan-secrets.sh
# .gitlab-ci.yml in a consuming project
include:
- component: $CI_SERVER_FQDN/my-org/security-components/[email protected]
inputs:
stage: build
Inputs are validated, so a missing required input fails the pipeline with a clear error instead of running with an empty variable. Pin to a release tag or commit SHA for production. Partial versions like @1.1 and @~latest work only for Catalog components, and GitLab advises against ~latest because it can pull in breaking changes. Publishing to the Catalog needs semantic version tags created by a release job. Details are in the CI/CD components documentation.
6. Authenticate to clouds with ID tokens (OIDC)
Storing an AWS access key or a cloud service account key in CI/CD variables means a long-lived secret that anyone with Maintainer access or a leaky job log could expose. GitLab can instead issue a short-lived, signed JWT per job, which the cloud provider exchanges for temporary credentials.
deploy-aws:
image:
name: amazon/aws-cli:latest
entrypoint: [""]
id_tokens:
AWS_ID_TOKEN:
aud: https://gitlab.example.com
script:
- >
export $(printf "AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s AWS_SESSION_TOKEN=%s"
$(aws sts assume-role-with-web-identity
--role-arn "$ROLE_ARN"
--role-session-name "gitlab-$CI_JOB_ID"
--web-identity-token "$AWS_ID_TOKEN"
--duration-seconds 3600
--query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]'
--output text))
- aws s3 ls
The token's claims include the project path, branch and whether the ref is protected. Write the cloud-side trust policy to accept only those you expect, for example only the main branch of one project. Without that condition, any project on the same GitLab instance could assume the role. See OpenID Connect ID token authentication and GitLab's cloud-specific guides. The same mechanism works with HashiCorp Vault through the secrets keyword.
7. Use the right variable type for secrets
GitLab CI/CD variables have several protection settings, and each one does something different:
| Setting | What it does | Limits |
|---|---|---|
| Masked | Replaces the value with [MASKED] in job logs. Default for new variables since GitLab 18.3. | Single line, no spaces, at least 8 characters |
| Masked and hidden | Also stops the value from being shown in the CI/CD settings UI after saving | Only set at creation; generally available for projects and groups since 17.6 |
| Protected | Available only to pipelines on protected branches or tags | MR pipelines can optionally be allowed access |
| File type | Writes the value to a temp file; the variable holds the path | Cannot be defined in .gitlab-ci.yml |
Masking is not encryption. A script that base64-encodes a value or prints it in pieces will get around it. GitLab's own CI/CD variables documentation recommends an external secrets manager or file-type variables for sensitive data. Mark production credentials as protected so a pipeline on a random feature branch cannot read them. For keeping secrets out of the repository itself, see our guide on storing secrets safely in Git.
8. Serialise deployments with resource_group
If two pipelines finish close together, two deploy jobs can run against production at the same time and leave it in a mixed state. resource_group makes jobs with the same group name run one at a time, across all pipelines in the project.
deploy-production:
stage: deploy
script: ./deploy.sh production
resource_group: production
environment:
name: production
url: https://app.example.com
The default process mode is unordered. You can switch a group to oldest_first or newest_first through the API if order matters. Pair this with GitLab's "prevent outdated deployment jobs" project setting so an older pipeline cannot roll production back after a newer one has deployed.
9. Cancel redundant pipelines automatically
When a developer pushes three commits in two minutes, the first two pipelines are already out of date. Mark safe jobs as interruptible and tell the workflow to cancel them on new commits:
workflow:
auto_cancel:
on_new_commit: interruptible
default:
interruptible: true
deploy-production:
interruptible: false
script: ./deploy.sh
on_new_commit accepts conservative (the default), interruptible or none. Always set deploy and migration jobs to interruptible: false; cancelling a database migration halfway is worse than paying for the runner minutes.
A related setting for review apps: environment:auto_stop_in: 1 day stops temporary environments that nobody cleaned up.
10. Parent-child pipelines and parallel:matrix
A single .gitlab-ci.yml for a monorepo becomes unreadable fast. Parent-child pipelines let the parent trigger a separate pipeline file per service, only when that service changes:
payments:
trigger:
include: services/payments/.gitlab-ci.yml
strategy: depend
rules:
- changes:
- services/payments/**/*
strategy: depend makes the parent job wait for and reflect the child pipeline's result. For running the same job across several targets, parallel:matrix creates one job per combination (up to 200):
test:
script: ./run-tests.sh
parallel:
matrix:
- PYTHON: ["3.11", "3.12", "3.13"]
DB: [postgres, mysql]
That produces six jobs. You can generate child pipeline YAML dynamically in an earlier job and pass it as an artifact, which some teams use to build only the services a change touches. Our post on 15 GitLab CI/CD pipeline examples shows complete pipelines using several of these patterns together.
Putting several techniques together
The snippet below combines techniques 1, 2, 4, 8 and 9 into a small but realistic pipeline for a containerised service. Use it as a starting skeleton and add components and ID tokens as your project needs them.
workflow:
auto_cancel:
on_new_commit: interruptible
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
when: never
- if: $CI_COMMIT_BRANCH
default:
interruptible: true
stages: [build, test, deploy]
.main-only:
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
build-image:
stage: build
image: docker:27
services: [docker:27-dind]
script:
- docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" "$CI_REGISTRY"
- docker build -t "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" .
- docker push "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA"
unit-tests:
stage: test
needs: []
script: make test
deploy-production:
stage: deploy
extends: .main-only
needs: [build-image, unit-tests]
interruptible: false
resource_group: production
environment:
name: production
script: ./deploy.sh "$CI_COMMIT_SHORT_SHA"
A few details are worth noticing. unit-tests uses needs: [], so it starts at pipeline creation instead of waiting for the image build. The deploy job is the only one that is not interruptible, and it shares the production resource group so overlapping merges queue up instead of racing. $CI_REGISTRY_USER and $CI_REGISTRY_PASSWORD are predefined variables that GitLab injects per job, so no registry password is stored anywhere. The Docker image tags are examples; pin to the versions your runners support.
How to adopt these without breaking pipelines
- Use the pipeline editor's validation (or the CI Lint tool) on every change to
.gitlab-ci.ymlbefore merging it. - Add
workflow:rulesfirst; it is the cheapest win and affects only when pipelines start. - Introduce
needsone stage at a time and watch the pipeline graph to confirm the order you expect. - Move one shared job into a component, publish a
1.0.0tag, and migrate projects gradually. - Replace stored cloud keys with ID tokens environment by environment, starting with non-production, then delete the old variables.
Mistakes these techniques prevent
- Two pipelines per push, which halves effective runner capacity.
- Copying the same 40-line deploy job into twenty projects, then fixing a bug in only three of them.
- AWS keys stored as plain CI/CD variables that any Maintainer can reveal.
- Overlapping production deploys after two quick merges.
- Paying for full pipelines on commits that were replaced a minute later.
For a tour of GitLab features beyond CI (merge request approvals, security dashboards, value stream analytics), read top 10 GitLab features you should explore. If you are preparing for interviews, the GitLab CI/CD interview questions test most of the keywords above.
Our GitLab training covers pipeline design, components, runners and OIDC deployments with hands-on labs, in the Kharadi, Pune classroom or live online.
Frequently asked questions
How do I stop GitLab from running duplicate pipelines?
Add a workflow:rules block that runs merge request pipelines when an MR exists and drops branch pipelines for branches with an open MR, using $CI_OPEN_MERGE_REQUESTS. GitLab documents this pattern in its workflow examples.
What is the difference between extends and !reference in GitLab CI?
extends merges a whole template job into another job, but arrays such as script are replaced, not combined. !reference pulls one specific section from another job, so you can combine template lines with your own.
What are GitLab CI/CD components?
They are reusable, versioned pipeline units with validated inputs, included with include:component and published to the CI/CD Catalog. Pin them to a release tag or commit SHA in production pipelines.
How can GitLab CI access AWS without storing access keys?
Use id_tokens to get a short-lived OIDC token in the job, then exchange it with aws sts assume-role-with-web-identity. Restrict the IAM role's trust policy to your project and branch claims.
Are masked variables in GitLab secure?
Masking only hides exact values in job logs. A script can still expose a value by encoding or splitting it. Use protected variables for production, "masked and hidden" for values nobody should read back, and an external secrets manager for sensitive data.
What does resource_group do in GitLab?
It makes jobs that share the same group name run one at a time across all pipelines in a project. It is mainly used to stop two deployments hitting the same environment simultaneously.
How does needs make GitLab pipelines faster?
It lets a job start as soon as the jobs it lists finish, rather than waiting for every job in the previous stage. This turns the pipeline into a directed acyclic graph and removes idle waiting.
When should I use parent-child pipelines?
Use them in monorepos or large projects where one pipeline file has become hard to read. The parent triggers a separate pipeline per component, often only when that component's files change.
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0