YAML 合并级别

Bla*_*axy 2 yaml

我们有一个包含重复部分的 gitlab-ci yaml 文件。

test:client:
  before_script:
    - node -v
    - yarn install
  cache:
    untracked: true
    key: client
    paths:
      - node_modules/
  script:
    - npm test

build:client:
  before_script:
    - node -v
    - yarn install
  cache:
    untracked: true
    key: client
    paths:
      - node_modules/
    policy: pull
  script:
    - npm build
Run Code Online (Sandbox Code Playgroud)

我想知道,使用合并语法,是否可以提取公共部分以在这两个部分的上下文中有效地重用它。

.node_install_common: &node_install_common
  before_script:
    - node -v
    - yarn install
  cache:
    untracked: true
    key: client
    paths:
      - node_modules/
Run Code Online (Sandbox Code Playgroud)

但真正的问题是:我必须在哪个缩进级别合并块以确保 policy: pull 应用于缓存部分。我试图这样做:

test:client:
  <<: *node_install_common
  script:
    - npm test

test:build:
  <<: *node_install_common
    policy: pull
  script:
    - npm build
Run Code Online (Sandbox Code Playgroud)

但是我收到一个无效的 yaml 错误。如何缩进以获得正确的合并行为?

fly*_*lyx 5

请注意,合并键不是 YAML 规范的一部分,因此不能保证有效。它们还针对过时的 YAML 1.1 版本指定,并且尚未针对当前的 YAML 1.2 版本进行更新。我们打算在即将推出的 YAML 1.3 中明确删除合并键(并可能提供更好的替代方案)。

话虽如此:没有合并语法。合并键<<必须像映射中的普通键一样放置。这意味着该键必须与其他键具有相同的缩进。所以这将是有效的:

test:client:
  <<: *node_install_common
  script:
    - npm test
Run Code Online (Sandbox Code Playgroud)

虽然这不是:

test:build:
  <<: *node_install_common
    policy: pull
  script:
    - npm build
Run Code Online (Sandbox Code Playgroud)

请注意,与您的代码相比,我添加:test:clienttest:build行。

现在指定合并以将引用映射的所有键值对放置到当前映射中,如果它们不存在于当前映射。这意味着您不能如您所愿地替换子树中更深的值——merge 不支持部分替换子树。但是,您可以多次使用合并:

.node_install_common: &node_install_common
  before_script:
    - node -v
    - yarn install
  cache: &cache_common
    untracked: true
    key: client
    paths:
      - node_modules/

test:client:
  <<: *node_install_common
  script:
    - npm test

test:build:
  <<: *node_install_common
  cache: # define an own cache mapping instead of letting merge place
         # its version here (which could not be modified)
    <<: *cache_common  # load the common cache content
    policy: pull       # ... and place your additional key-value pair
  script:
    - npm build
Run Code Online (Sandbox Code Playgroud)