Question

Conditionally display the drop-down list of values of a variable based the branch name GitLab pipeline

The globalvariables: section of my .gitlab-ci.yml file has been constructed like below:

variables:
  HOST_NAME:
    description: Select a host name to deploy
    value: web-server-dev-01
    options:
      - web-server-dev-01
      - web-server-dev-02
      - web-server-dev-03
      - web-server-prod-01
      - web-server-prod-02
      - web-server-prod-03

Now, when I run the pipeline, the HOST_NAME variable shows the default value web-server-dev-01 and other 6 server names become available in the drop-down list of this variable, whichever branch I run from.

I'd like to make the values available like below:

  • When running from dev branch, the default value of the HOST_NAME should show web-server-dev-01 and drop-down should show the first 3 server names (ending with dev-xx).
  • When running from master branch, the default value of the HOST_NAME should show web-server-prod-01 and drop-down should show the last server names (ending with prod-xx).

Is it possible? If so, would you please show how?

 4  82  4
1 Jan 1970

Solution

 2

You can configure a variable dependent on the branch like using rules:variables during the job run.

variables:
  SERVER_NO:
    description: Select a host name to deploy
    value: 01
    options:
      - 01
      - 02
      - 03

deploy:
  stage: deploy
  script:
    - echo "Deploying to $HOSTNAME"
  rules:
    - if: $CI_COMMIT_REF_NAME =~ /^dev$/
      variables:
        HOSTNAME: web-server-dev-$SERVER_NO
    - if: $CI_COMMIT_REF_NAME =~ /^main$/
      variables:
        HOSTNAME: web-server-prod-$SERVER_NO
2024-07-17
Oluwafemi Sule