Being Flexible in Travis Stages with References
Deployment or asset publication happens on select configurations (e.g., after non-debug aka non-verbose builds), it only takes even me, just missing one member of any stage to subtly break the pipeline and introduces visual clutter that YAML has a hard time parsing. Anchors have been in the YAML spec for quite some time, but not all CI providers have support for Anchors, here at Travis we embrace a modern implementation of YAML. Let’s get our Anchors going and parse something similar in this blog post.
Anchors and Extensions
When building in YAML, these are normally negative qualities in a configuration that I will show you below, now our present situation is one where where we’re going to use two of YAML’s unusual and lesser-known features, and rarely you’ll see this utilized in a
.travis.yml, these features are called Anchors and Extensions.
To get started, let me give you a couple of YAML examples. You use
aliases like so:
_template: &_template key: value other_key: other_value real_config: - <<: *_template other_key: overridden_value new_key: new_value - <<: *_template different_key: different_value - *_template
Which equates to:
real_config: - key: value other_key: overridden_value new_key: new_value - key: value other_key: other_value different_key: different_value - key: value other_key: other_value
You’ll see in the above example I wrote out I used key-value pairs. as an example. Fundamentally, a file written in YAML consists of a set of key-value pairs. Each pair is written as
key: value, where whitespace after the
: is optional, and in Travis you can obviously give conditionals.
Anchors are really similar to the programming language C, here’s a quick sample for reference:
foo: &bar travis bar: *bar
This is read through the interpeter as:
foo: travis bar: travis
Let’s inject an anchor blob in our
blob: &blob bar: travis foo: <<: *blob
This is the same as:
blob: bar: travis foo: bar: travis
Synchornizing Anchors, Extensions and Blobs, we can use references and anchors to beautifully and almost artistically set our
.travis.yml file. This is not only cleaner for YAML, but for also the end user reading the YAML file, here’s the example YAML file using Anchors, and Extensions I’ve created:
--- language: cpp os: linux dist: xenial linux-ppc64le: &linux-ppc64le os: linux-ppc64le linux-s390x: &linux-s390x os: linux arch: s390x dist: bionic jobs: include: - <<: *linux-ppc64le compiler: gcc - <<: *linux-ppc64le compiler: clang - <<: *linux-s390x compiler: gcc - <<: *linux-s390x script: true
We can also add addons on certain hooks, here’s an example:
--- _build: stage: montana language: cpp addons: apt: packages: - gcc - chromaprint - netif
As you can see this is a more formattable way to write your
.travis.yml, and it’s using little lesser known functions of YAML.
If you have any questions please email me at firstname.lastname@example.org and I’ll answer any and all questions!