我正在尝试编写 bitbucket 管道并使用 YAML 锚点来减少重复。
这就是我想做的例子:
---
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
...
当然这不起作用(请参阅自定义部署步骤)。人们不能定义另一个脚本项并期望它将其合并到锚脚本。有办法做到这一点吗?
过了相当长的一段时间,我对这个问题有了回应,但它并不像人们想象的那么好。
我期望的是,YAML 解析器能够以某种方式合并节列表项的元素并使之成为一个。这不起作用,也不受 YAML 标准支持。
我们可以做的是:
---
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
基本上每次我们设置一个步骤来合并锚点时,锚点元素覆盖锚点本身中的相同项目后指定的任何项目。因此,如果我们将常用命令转换为 YAML 锚点内的大字符串,那么我们就可以在我们想要的任何步骤中重复使用它,并且减少键入和重复,并且内容变得更具可读性。
您也许可以将
Some other command to execute
脚本放入 after-script 中。像这样的东西:
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
after-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
遵循基于已接受答案的想法,此修改似乎有效并允许多行脚本,例如:
definitions:
caches:
big-stuff-cache:
key:
files:
- "src/big-stuff-manifest.json"
path: "src/big_stuff"
common-items:
install-aws: &install-aws |
# install aws cli for steps that need to run from a non-aws-cli container and need aws cli
curl "https://awscli.amazonaws.com/awscli-exe-linux-aarch64.zip" -o "awscliv2.zip"
unzip -q awscliv2.zip
./aws/install
echo aws version $(aws --version)
steps:
- step: &build-and-upload-img
name: 'ECR img deploy'
caches:
- node
services:
- docker
script:
- *install-aws
- aws ecr dostuff
- step: &deploy-lambda-layer
name: 'layer deploy'
caches:
- big-stuff-cache
script:
- *install-aws
- chmod +x ./pipelineScripts/deployLambdaLayer.sh
- ./pipelineScripts/deployLambdaLayer.sh