Templates


Make jobs reusable

Job templates begin with a dot to prevent execution

Templates can be located in the same .gitlab-ci.yml (inline)

Templates can be imported using include from…

See also the official development guide for templates


Hands-On: Template and include

  1. Create inline tmplate:

     .build-go:
       script:
       - |
         go build \
             -ldflags "-X main.Version=${CI_COMMIT_REF_NAME} -X 'main.Author=${AUTHOR}'" \
             -o hello \
             .
    

  2. Use in build job

     build:
       extends: .build-go
       #...
    

See new .gitlab-ci.yml:

git checkout 160_gitlab_ci/120_templates/inline -- '*'

Hands-On: Local

  1. Add go.yaml to root of project
  2. Include go.yaml:

     include:
     - local: go.yaml
    
     build:
       extends: .build-go
       #...
    
  3. Check pipeline

See new .gitlab-ci.yml:

git checkout 160_gitlab_ci/120_templates/local -- '*'

Hands-On: File

  1. Create a new project, e.g. template-go
  2. Move (!) go.yaml to the root of the new project
  3. In original project, include go.yaml:

     include:
     - project: <GROUP>/template-go
       ref: main
       file: go.yaml
    
  4. Check pipeline

Pro tip: Multiple inheritence

Jobs can inherit from multiple templates

job_name:
  extends:
  - .template1
  - .template2

With conflicting templates…

.template1:
  script: pwd
.template2:
  script: whoami

…last writer wins!

job_name:
  script: whoami

But variables are merged!


Pro tip 2: Solve multiple inheritence

Conflicting templates…

.template1:
  script: pwd
.template2:
  script: whoami

…can be resolved by using reference tags

job_name:
  script:
  - !reference[.template1, script]
  - !reference[.template2, script]