Passing before_script back to job deifned in an include

I’m writing a set of templates providing two jobs (one for linux, one for windows) and they both extend a common template

common template:

.sca-common:
  stage: scans
  rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event'
  variables:
    COMMON_VAR: blah

linux template:

include: '/common.yml'

scans:sca:
  extends: .sca-common
  image: ${sca_job_image}
  variables:
    sca_job_image: alpine:latest
  before_script:
    - # something goes here to conditionally include provided
  script:
    - echo "Running the scan"

The windows version is like Linux but with Powershell commands in the script block instead of bash/shell. I want for the teams including one of the two OS templates to be able to supply custom before_script for the scans:sca job.

caller in another project:

stages:
  - build
  - test
  - scans

# Some magic goes here to pass before_script

include:
  - project: 'templates/pipelines'
    ref: main
    file: 'linux-scan.yml'

My first instinct was around anchors or !reference, but I think anchors don’t work across files, and both would need some kind of condition syntax. The main purpose would be to do things like install packages needed for their project. My recommendation to people is going to be that they build their own image, but if they have simple requirement like just ‘apk add maven’ I think that’s reasonable to not have to build a whole custom image.

!reference might work, haven’t tried to use it like that.
Alternative, if the before_script should be pre-defined in your templates you can hide it behind variable.

scans:sca:
  extends: .sca-common
  image: ${sca_job_image}
  variables:
    sca_job_image: alpine:latest
  before_script:
    - if [ "${RUN_BEFORE_SCRIPT}" = "yes" ]; then step1;step2; fi
  script:
    - echo "Running the scan"
include:
  - project: 'templates/pipelines'
    ref: main
    file: 'linux-scan.yml'

variables:
  RUN_BEFORE_SCRIPT: "yes" #or any other value to not run it

stages:
  - build
  - test
  - scans

If the before_script is something they define in their project level, they can just do this:

include:
  - project: 'templates/pipelines'
    ref: main
    file: 'linux-scan.yml'

stages:
  - build
  - test
  - scans

scans:sca:
  before_script:
    - echo hello
1 Like

That’s … so simple. Thanks! I’ll try it out.

edit: it worked!