YAML:我如何覆盖变量

时间:2017-08-14 11:00:04

标签: yaml

我有以下YAML:

defaults: &defaults
  username: admin
  password: admin
  agents:
    blueprint: &agent_blueprint
      version: '1'
      auth:
        username: agent
        password: secret
      supported_features:
      - state
      - lifecycle
      - credentials
      - backup
      - restore
  services:
  - &blueprint_service
    id: '24731fb8-7b84-4f57-914f-c3d55d793dd4'
    name: 'blueprint'
    plans:
    - id: 'bc158c9a-7934-401e-94ab-057082a5073f'
      name: 'v1.0-dedicated-xsmall'
      free: false
      manager:
        name: 'director'
        settings:
          prefix: 'blueprint'
          agent: *agent_blueprint
          context:
            agent: *agent_blueprint

现在我想添加另一个节点来覆盖服务数组中的supported_features个节点。所以,我添加了这样的东西。

development:
  <<: *defaults
  agents:
    blueprint:
      <<: *agent_blueprint
      supported_features:
      - state
      - lifecycle
      - credentials
  services:
  - *blueprint_service

但是,它不会更新supported_features下的services节点。我该怎么做?

1 个答案:

答案 0 :(得分:0)

在YAML中没有变数,我认为你对YAML的merge key feature实际上做了什么有误解。

在你的第二个YAML区块中,你可以这样做:

development:
  <<: *defaults

完全没效果,因为您立即覆盖两个键值对(使用键agentsblueprints),并且:

agents:
    <<: *agents

无效,因为您覆盖了单个键blueprint

之后你会这样做:

blueprint: &agent_blueprint
  <<: *agent_blueprint
  supported_features:

从您刚刚开始定义的blueprint的值中合并键,即supported_features(第三行中的那个)及其值。这是因为别名总是从其前面的锚点获取定义(如果有多个具有相同名称的锚点,则来自最新定义的锚点)。

所以你的第二个例子写得更简单:

development:
  agents:
    blueprint: 
      supported_features:
      - state
      - lifecycle
      - credentials
  services:
  - *blueprint_service

其中*blueprint_service扩展为:

id: 24731fb8-7b84-4f57-914f-c3d55d793dd4
name: blueprint
plans:
- free: false
  id: bc158c9a-7934-401e-94ab-057082a5073f
  manager:
    name: director
    settings:
      agent: *agent_blueprint
      context:
        agent: *agent_blueprint
      prefix: blueprint
  name: v1.0-dedicated-xsmall

因为在第一个YAML块中定义了锚点时锚点生效。并*agent_blueprint在那里:

  auth: {password: secret, username: agent}
  supported_features: [state, lifecycle, credentials, backup, restore]
  version: '1'

没有“更新”。当别名被解析时,别名从定义为锚的内容中获取其值。