Skip to main content

How do I use the when: ref_name section in a pipeline as code?

To use the when: ref_name section in a GitLab pipeline as code, you can specify a job or a step to run only when the pipeline is triggered by a specific branch or tag. This allows you to control the execution of jobs based on the branch or tag name.

Here's an example of how you can use the when: ref_name section:

deploy_staging:
stage: deploy
script:
- echo "Deploying to staging environment..."
only:
refs:
- staging/*
when: ref_name

In the above example:

The deploy_staging job is defined in the deploy stage of the pipeline.

The script section includes the commands for deploying to the staging environment.

The only section specifies the reference names to match against. In this case, it is set to staging/* to trigger the job only when the pipeline is triggered by a branch that starts with staging/.

The when: ref_name section indicates that the job should run only when the pipeline is triggered by the specified reference name.

When this pipeline is executed, the deploy_staging job will run only if the pipeline is triggered by a branch with a name that starts with staging/. If the pipeline is triggered by a different branch or a tag, the job will be skipped.

Using the when: ref_name section allows you to control the deployment of jobs based on the branch or tag name, ensuring that specific actions are performed only on the desired references.