I am trying to write bitbucket pipeline and use YAML anchors to reduce repetition.
So this is the example of what I would like to do:
---
definitions:
steps:
- step: &build-test-alpine
image: php:7.4-alpine
caches:
- composer
script:
- apk add unzip curl
- curl -sS https://getcomposer.org/installer | php -- --install-dir='/usr/local/bin' --filename='composer'
- composer --no-ansi -n install
- composer --no-ansi -n test
pipelines:
custom:
deploy:
- step:
name: Build and deploy application
<<: *build-test-alpine
script:
- Some other command to execute
default:
- step:
<<: *build-test-alpine
name: PHP 7.4
- step:
<<: *build-test-alpine
image: php:7.3-alpine
name: PHP 7.3
...
Of course this does not work (see custom deploy step). One can not define another script item and expect it to merge it to the anchor script. Is there a way to do this?
After quite some time I have a response to this question but it is not as nice as one might desire.
What I expected is that somehow YAML parser would be able to merge elements of section list items and make it one. This does not work nor is supported by YAML standard.
What we can do instead is this:
---
definitions:
commonItems: &common
apk add unzip curl &&
curl -sS https://getcomposer.org/installer | php -- --install-dir='/usr/local/bin' --filename='composer' &&
composer --no-ansi -n install &&
composer --no-ansi -n test
steps:
- step: &build-test-alpine
image: php:7.4-alpine
caches:
- composer
script:
- *common
pipelines:
custom:
deploy:
- step:
name: Build and deploy application
<<: *build-test-alpine
script:
- *common
- some other command to execute
default:
- step:
<<: *build-test-alpine
name: PHP 7.4
- step:
<<: *build-test-alpine
image: php:7.3-alpine
name: PHP 7.3
Essentially every time we set a step to merge anchor any item specified after anchor element overrides the same item in the anchor itself. So if we transform the common commands in a big string within an YAML anchor than we can use it repeatedly in whatever step we want and typing and repetition is reduced and stuff becomes more readable.