Templates


Make jobs reusable

Templates contain required keywords

Templates must not be well-formed jobs

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


Templates 1/

Keywords from job_name are applied after keywords from .template

The following pipeline… results in the following job:

.template:
  image: alpine
  script: pwd

job_name:
  extends: .template
job_name:
  image: alpine
  script: pwd

Templates 2/

Keywords from job_name are applied after keywords from .template

The following pipeline… result in the following job:

.template:
  image: alpine
  script: pwd

job_name:
  extends: .template
  script: ls -l
job_name:
  image: alpine
  script: ls -l

Templates 3/3

Variables are merged!

The following pipeline… result in the following job:

.template:
  image: alpine
  variables:
    foo: bar
    my_var: my_val
  script: pwd

job_name:
  extends: .template
  variables:
    bar: baz
    my_var: also_my_val
job_name:
  image: alpine
  variables:
    foo: bar
    bar: baz
    my_var: also_my_val
  script: pwd

Hands-On

See chapter Templates


Pro tip 1: 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]

Pro tip 3: Organizing templates in repositories

Once you are hooked on templates, you want to organize them in a repository

Versioning

Use tags and releases to mark versions

Single repository

Easy to find/browse, hard to version

Apply separate versioning: docker/v1.0.0, helm/v1.0.2, k8s/v1.2.0

Repository per topic

Separation of concerns

Harder to find/browse, easier to version

Create versions separately


Pro tip 4: Public Template Library

Project to help building professional pipelines

Pipeline generator

Documentation

Source code