Search code examples
gitlabcicd

Including common section in Gitlab CI/CD


I'm trying to create a common section to all stages in my CI/CD pipeline. This is my .gitlab-ci.yml:

image: debian:bullseye

default:
  tags:
    - qa

stages:
  - build_vm

.common:
    script:
    - echo "######################## Installing stuff ########################"
    - export DEBIAN_FRONTEND=noninteractive
    - apt-get update
    - |
      apt-get install -qy \
        ca-certificates \
        git \
        jq \
        make \
        nmap \
        openssh-client \
        python3 \
    - make VERBOSE=true "$MAKEFILE_TARGET"


build_vm:
  before_script:
    - export PYTHONPATH="$CI_PROJECT_DIR":$PYTHONPATH
  variables:
    MAKEFILE_TARGET: build_vm
  stage: build_vm
  extends: .common
  script:
    - echo "build_vm $GITLAB_USER_LOGIN!"
    - make VERBOSE=true "$MAKEFILE_TARGET"

However, the .common section is not included during job runs.

To test if it's running I included using make (with my Makefile being present in the project of course) in build_vm and the pipeline job complains:

/bin/bash: line 170: make: command not found

So clearly the .common stage hasn't run (because it didn't install make as it would have).

Why is this section not included? It should be easy enough, no?


Solution

  • The way you have extended will cause the build_vm script section override the .common script section.

    Here is the right way to do this using !reference

    image: debian:bullseye
    
    default:
      tags:
        - qa
    
    stages:
      - build_vm
    
    .common:
        script:
        - echo "######################## Installing stuff ########################"
        - export DEBIAN_FRONTEND=noninteractive
        - apt-get update
        - |
          apt-get install -qy \
            ca-certificates \
            git \
            jq \
            make \
            nmap \
            openssh-client \
            python3 \
        - make VERBOSE=true "$MAKEFILE_TARGET"
    
    
    build_vm:
      before_script:
        - export PYTHONPATH="$CI_PROJECT_DIR":$PYTHONPATH
      variables:
        MAKEFILE_TARGET: build_vm
      stage: build_vm
      script:
        - !reference [.common, script]
        - echo "build_vm $GITLAB_USER_LOGIN!"
        - make VERBOSE=true "$MAKEFILE_TARGET"