Have building block style run conditions in .gitlab-ci.yml

,

Hi!

I’m currently setting up a security scanning pipeline for the teams and therefore looking at a lot of adjustments to already existing .gitlab-ci.yml files of different teams.
What I would like to do is to use cross-project includes referencing the security teams yaml files to include. There’s one issue though: unfortunately, each team has a more or less custom .gitlab-ci.yml file, which requires allowing local overrides. I want to make this overriding process as convenient as possible, by defining run condition rules in the security includes and just reference them during overrides. I do not know how that can be done though.

I’m thinking something like:

rules:
  - &not_scheduled
    if: '$CI_PIPELINE_SOURCE == "schedule"'
    when: never
  - &manual_on_push
    if: '$CI_PIPELINE_SOURCE == "push" || $CI_PIPELINE_SOURCE == "merge_request_event"'
    when: manual
    allow_failure: true # TODO Disallow failure once the security scanning should act as a quality gate
  - &always_on_push
    if: '$CI_PIPELINE_SOURCE == "push" || $CI_PIPELINE_SOURCE == "merge_request_event"'
    when: always
    allow_failure: true # TODO Disallow failure once the security scanning should act as a quality gate
    [...]

[...]

# This step tests the code for vulnerabilities with Snyk and creates a report. In case of an issue, the pipeline can be configured to fail hard to ensure vulnerable or non-compliant builds are not pushed to production
security:test:
  extends: .security:template
  rules:
    - *not_scheduled
    - *manual_on_push
    - *always_on_push
  script:
    [...]

This obviously does not work, but what could be done to have it? such that in case I need to override the job definition for a team, I do not have to rewrite the full set of rules, but instead can piece together a set of sensible rules as shown in the job definition? How do I need to define the rules, to be able to reference them later - even if one of the defined jobs is being overridden?

You are nearly there! This is a working config:

stages:
    - security

.not_scheduled: &if_scheduled
    if: '$CI_PIPELINE_SOURCE == "schedule"'
    when: never

.always_on_push: &always_on_push
    if: '$CI_PIPELINE_SOURCE == "push" || $CI_PIPELINE_SOURCE == "merge_request_event"'
    when: always
    allow_failure: true

.high_assurance: &high_assurance
    rules:
        - <<: *if_scheduled
        - <<: *always_on_push

security:
    stage: security
    <<: *high_assurance
    script:
        - echo hello

You need two things: anchors, then include.

The additional includes examples explain how to deal with overriding templates.

You may also find extends and reference useful.

1 Like