Reducing repeated configuration code with anchors and extensions
All GitLab CI pipeline files must be valid YAML. This also means they support various templates and repeatable code patterns that the YAML language supports. Writing multiple CI job definitions for each CI job in a pipeline can be time-consuming and lead to serious maintainability concerns. If you leverage the same variable in multiple places in a pipeline, it’s better to have it defined once, and then referenced multiple times. This way, when you need to change the variable, you do it in one place as opposed to many. Not only is this easier to do, but it’s also safer as with large pipelines, multiple variable replacements can lead to errors.
The three methods GitLab and YAML offer for creating reusable CI pipelines are anchors, the extends (extends:
) keyword, and a reference (!reference
) tag. In the following sections, we’re going to explain the benefits and usage of each of these three methods...