How to add additional script command in gitlab components?

I have a gitlab components file, and would like to add the possibility that before_script can be enhanced by the projects that use the component.

In the following example, I would want to offer other projects to execute additional before_script commands in between what I defined in the component.

Pseudocode, how could I achieve that?

spec:
  inputs:
    before_script_additional:
      type: array
      default: []
---
docker_compose:deploy:
  stage: deploy
  before_script:
    - echo before
    - $[[ inputs.before_script_additional ]]
    - echo after

Goal

You want to define a GitLab CI/CD component that has a default before_script, but also allows projects that use the component to inject their own extra before_script lines in between your steps.


Solution (Using inputs and extends)

GitLab CI does not support injecting arrays directly like this:

- $[[ inputs.before_script_additional ]]  # ❌ This won't work

But you can achieve your goal using a combination of:

  • inputs (for user-defined commands)
  • script: blocks instead of before_script for full control
  • Template extending, if more flexibility is needed

Component Example (using script)

# .gitlab-ci-component.yml
spec:
  inputs:
    extra_before:
      type: array
      default: []

---

docker_compose:deploy:
  stage: deploy
  script:
    - echo before
    - for cmd in "${{ inputs.extra_before[@] }}"; do eval "$cmd"; done
    - echo after

In this example, you loop over the array of extra commands and run each one between your fixed steps.


Usage in Project

include:
  - component: my.gitlab.com/group/components/build_image.yml

docker_compose:deploy:
  inputs:
    extra_before:
      - echo "Custom step A"
      - echo "Custom step B"

Why Your Original Approach Didn’t Work

  • GitLab does not support injecting an array directly into before_script like this:
before_script:
  - echo before
  - $[[ inputs.before_script_additional ]]  # ❌ invalid
  • The before_script field expects a static YAML array, not dynamic interpolation of another array.

Summary

To let other projects inject steps between fixed steps in a GitLab component:

  • Use an input array (e.g., extra_before)
  • Loop over it inside the script: section
  • Or consider using extends: in more advanced setups

Let me know if you want a version that uses before_script specifically, but it will need a different workaround.