gitlab-ci

Convert "only/except" clauses to "rules" clause in Gitlab CI


Problem Summary:

My goal is to add a rules clause to configure a Gitlab CI job to run if an environment variable is set, or if manual action is performed. Unfortunately, the step currently makes use of only and except clauses so I'll have to also convert them into rules syntax, which I've not fully grasped yet.

Current Job Definition:

deploy:
  only:
    - branches
  except:
    refs:
      - /flux-.*$/  
      - master
  stage: deploy
  when: manual

Required Changes:

I'll be replacing

when: manual

with

rules:
  - if: '$CI_ENVIRONMENT_NAME'
  - when: manual

Now I'd like to learn how to translate the only/except clauses. I think it'll be completely based on predefined environment variable tests, though I'm unsure which variables are of interest for this translation.

Many thanks for any suggestions or pointers.


Solution

  • As you pointed out using predefined environment variables is the way to go with rules. Many of them can be used to achieve the same thing, it really depends on your needs (For example: $CI_COMMIT_REF_NAME vs $CI_COMMIT_REF_SLUG vs $CI_COMMIT_BRANCH).

    My goal is to add a rules clause to configure a Gitlab CI job to run if an environment variable is set, or if manual action is performed.

    Just to be sure to understand what you mean by that:

    Is that correct?

    If yes, one implementation would look like this below. (You can also use || operators to merge the 2 first rules if you want)

    deploy:
      stage: deploy
      rules:
        - if: '$CI_COMMIT_REF_NAME == "master"'
          when: never
        - if: '$CI_COMMIT_REF_NAME =~ /flux-.*$/'
          when: never
        - if: '$CI_ENVIRONMENT_NAME'
        - when: manual
    

    Keep in mind that rules are evaluated in order. Hope that helps.