Array variable inside .gitlab-ci.yml yaml

2 min read 05-10-2024
Array variable inside .gitlab-ci.yml yaml


Managing Dynamic Values in Your .gitlab-ci.yml: Leveraging Arrays

The .gitlab-ci.yml file is the heart of your CI/CD pipeline, dictating the workflow of your project. Sometimes, you might need to define a series of tasks or values in a flexible way. This is where arrays come in handy.

Scenario: Dynamic Testing Stages

Imagine you have a project with several environments: development, staging, and production. You want to run the same tests in each environment, but with different configurations. Using a simple array within your .gitlab-ci.yml provides an elegant solution.

stages:
  - test

variables:
  TEST_ENVS: ["development", "staging", "production"]

test_job:
  stage: test
  script:
    - echo "Running tests for environment: ${CI_ENV}"
    - # Your testing commands here
  variables:
    CI_ENV: ${{ TEST_ENVS[${CI_JOB_INDEX}] }}
  only:
    - branches:
        - main
  except:
    - schedules

Explanation:

  • stages: Defines the stages of your pipeline.
  • variables: The TEST_ENVS variable stores an array of environment names.
  • test_job: This job runs for each environment in the TEST_ENVS array.
  • script: The job's commands, including the CI_ENV variable which is dynamically set.
  • CI_JOB_INDEX: A GitLab CI/CD variable that represents the current job's index within the stage. It starts from 0.
  • only and except: These are used to control when this job should run.

This setup will create three test_job jobs, each running with a different CI_ENV value from the TEST_ENVS array.

Advantages of Using Arrays:

  • Flexibility: Easily add or remove environments without changing the core job definition.
  • Code Reusability: The test_job definition can be reused for different environments, promoting consistency.
  • Improved Readability: Keeps your .gitlab-ci.yml file organized and easier to understand.

Expanding the Concept:

You can extend this concept to manage various lists within your CI/CD pipeline:

  • Multiple Build Targets: Define an array of build targets (e.g., ["linux", "macos", "windows"]) to run your build process on different platforms.
  • Test Suites: Group your test suites into an array, allowing you to select specific suites for certain environments.
  • Configuration Parameters: Store an array of parameters to dynamically modify your build or deployment process.

Conclusion:

Arrays are a powerful tool for managing dynamic elements in your .gitlab-ci.yml file. By leveraging this feature, you can enhance the flexibility, reusability, and organization of your CI/CD pipeline.