首页 > 解决方案 > bitbucket 管道中的 YAML 锚点

问题描述

我正在尝试编写 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

...

当然这不起作用(请参阅自定义部署步骤)。不能定义另一个脚本项并期望它将其合并到锚脚本。有没有办法做到这一点?

标签: yamlbitbucket-pipelines

解决方案


很长一段时间后,我对这个问题有了回应,但它并不像人们想要的那样好。

我所期望的是,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 锚中将常用命令转换为大字符串,那么我们就可以在我们想要的任何步骤中重复使用它,并且减少输入和重复,并且内容变得更具可读性。


推荐阅读