travis.yml DRY with anchors
Anchors and aliases are an amazing feature of YAML that allow you to re-use blocks of YAML elsewhere in the same file. Even tho they’re a part of the YAML spec (and have been since the early 2000s) not everyone supports them (I’m looking at you AWS CloudFormation) but fortunately travis-ci has embraced a modern implementation of YAML.
You use anchors and 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 is equivalent 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
As you can see we’ve got a hash anchored at _template
with key
and other_key
and in the first hash in the real_config
array we override other_key
and introduce new_key
. In the second hash we introduce different_key
.
In travis.yml this means you can keep it DRY and template things like deployments and API keys (and what ever else you can think of):
install: pip install -r requirements-tests.txt
script: make tests
before_deploy: mv build build-${TRAVIS_OS_NAME}
matrix:
include:
- language: python
os: linux
python: '3.6'
- language: python
os: linux
python: '3.5'
- os: osx
language: generic_deploy_provider: &_deploy_provider
provider: releases
api_key:
secure: abcde=
file: build-${TRAVIS_OS_NAME}
skip_cleanup: true
on: &_deploy_provider_on
tags: true
deploy:
- <<: *_deploy_provider
on:
<<: *_deploy_provider_on
python: '3.5'
- <<: *_deploy_provider
on:
<<: *_deploy_provider_on
condition: "$TRAVIS_OS_NAME == osx"
This example is based off of a working travis.yml, feel free to adapt it to your needs.
At the time of writing this AWS Cloudformation returns “Template validation error: Template error: YAML aliases are not allowed in CloudFormation templates” if you try to use YAML anchors/aliases.