YAML anchors

If you have repeated sections in your bitbucket-pipelines.yml file, you might like to use YAML anchors. They can reduce effort and make updating in bulk, easier.

Anchors and aliases

There are 2 parts to this:

  • The anchor '&' which defines a chunk of configuration

  • The alias '*' used to refer to that chunk elsewhere

So in the example below we use &build-test to define a step entity, which has several lines for reuse, and the alias *build-test to reuse it.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 definitions: steps: - step: &build-test name: Build and test script: - mvn package artifacts: - target/** pipelines: branches: develop: - step: *build-test main: - step: *build-test

YAML anchors and aliases cannot contain the ' [ ', ' ] ', ' { ', ' } ', and ' , ' characters.

Override values

But what if you want essentially the same block of code with one small change?

You can use overrides with the characters '<<:' to add more values, or override existing ones.

Building on the example above we could override the name value for a step:

1 2 3 4 5 6 7 8 pipelines: branches: develop: - step: *build-test main: - step: <<: *build-test name: Testing on Main

In the pipelines result page, we'd see the name of the step as Build and test for pipelines that ran on the develop branch, and Testing on Main for pipelines that ran on the main branch.

Put it all together

Using the techniques above, you can reduce the amount of effort needed to create your configuration, and maintain it when changes occur.

As with all YAML it's vital to make sure your indentation is correct, which is tricky when using anchors, so take care!

Here's a slightly longer example showing how you might use overrides and multiple anchors together:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 definitions: steps: - step: &build-test name: Build and test script: - mvn package artifacts: - target/** - step: &deploy name: Deploy deployment: test script: - ./deploy.sh target/my-app.jar pipelines: branches: develop: - step: *build-test - step: *deploy main: - step: *build-test - step: <<: *deploy deployment: production trigger: manual

 

Additional Help