Introduction
Elevate your development workflow by automating code testing and deployment with GitLab CI/CD. In this comprehensive guide, we’ll walk you through creating a GitLab CI/CD configuration file (gitlab-ci.yml
). This configuration file executes different jobs based on whether the code is pushed to the main branch or a feature branch.
YAML Configuration File
Dive into a complete example of a GitLab CI/CD configuration file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | stages: - build variables: MY_VARIABLE: "Hello, World!" before_script: - echo "Setting up the environment..." job_main_branch: stage: build script: - echo "Running this job on the main branch" - echo "Accessing the variable MY_VARIABLE: $MY_VARIABLE" rules: - if: '$CI_COMMIT_BRANCH == "main"' when: always job_feature_branch: stage: build script: - echo "Running this job on a feature branch" - echo "Accessing the variable MY_VARIABLE: $MY_VARIABLE" rules: - if: '$CI_COMMIT_BRANCH != "main"' when: always |
Explanation:
stages
: Defines different stages in the pipeline. In this example, we’ve focused on a single stage named “build.”variables
: Establishes global variables accessible by all jobs. Here,MY_VARIABLE
carries the value “Hello, World!”before_script
: Incorporates commands executed before each job. Here, we emphasize the importance of setting up the environment.job_main_branch
: Specifies a job that runs exclusively on the main branch. Therules
section guarantees the job runs only if the commit branch is “main.”job_feature_branch
: Outlines a job that operates on feature branches. Therules
section ensures the job runs if the commit branch is not “main.”script
: Contains the commands executed by the job. In this instance, it delivers messages indicating the branch being processed and accesses the global variable.
Using Variables
Leverage variables in GitLab CI/CD to define values reused across jobs. Here, the variable MY_VARIABLE
serves as an example. To access this variable within a job, utilize the syntax $VARIABLE_NAME
.
Secrets
GitLab CI/CD enables the secure storage of sensitive information using secrets. To access secrets within a job, utilize the syntax $CI_JOB_TOKEN
for predefined variables or $CI_JOB_TOKEN
for custom variables.
Explore an example of using a secret in your job:
1 2 3 4 5 6 7 | job_using_secret: stage: build script: - echo "Using secret API_KEY: $CI_JOB_TOKEN" rules: - if: '$CI_COMMIT_BRANCH == "main"' when: always |
In this example, $CI_JOB_TOKEN
is used to access a secret named API_KEY
. Ensure the definition of secrets in the GitLab project settings.