'Common script for all jobs inheriting a hidden one in Gitlab CI

We have a common included CI config file (.services.yml) for a set of projects looking like this:

stages:
 - ...
 - build
 - ...

.build:
  stage: build
  script:
    - build_script
    - ...
  ...

The .build job is used in each project a few times in order to build different binaries for a set of stage platforms:

include:
  - project: "project/path"
    ref: master
    file: /.services.yml

build-stage1:
  extends: .build
  ...

build-stage2:
  extends: .build
  ...

However some projects using the .services.yml don't inherit the .build job as it's unnecessary.

We have decided to make an 'extra build' job recently in order to optimize the pipeline. A goal of the job is to set some common environment for each instance of the .build one:

stages:
 - ...
 - prebuild
 - build
 - ...

.prebuild:
  stage: prebuild
  script:
    - prebuild_script
    - ...
  ...

.build:
  stage: build
  script:
    - build_script
    - ...
  ...

So if a project runs the build stage, it must explicitly implement the prebuild one too (but only once as it's the common preparation stage for the following build stages):

prebuild:
  extends: .prebuild
  ...

build-stage1:
  extends: .build
  ...

build-stage2:
  extends: .build
  ...

The question is whether it's possible to attach the prebuild_script to the build_script so it is proceeded only once no matter how many times the .build job is inherited. Or is there a workaround?

I've tried to search some solution in the job rules but there is no option that fits.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source