在 Ansible 角色任务文件中使用 YAML 锚点

2023-12-29

我正在尝试创建一个 ansible 角色任务文件,其中包含多个重复部分,并且我想利用 YAML 的锚点功能,该功能允许跨文件共享数据。在我的实际文件中,我有 3 或 4 个属性需要在文件中的十几个任务中完全相同,因此锚点似乎是完美的解决方案。这是我的设置:

主机配置文件

localhost connection=local

test.yml

---
- name: test
  hosts: localhost
  roles:
    - test

角色/测试/任务/main.yml

---
foo: &foo
  msg: 'this is a test'

- name: Test message
  debug:
    <<: *foo

我期望的属性foo字典应该传播到debug字典,结果是这样的结构

{
  "name": "Test message",
  "debug": {
    "msg": "this is a test"
  }
}

但是,当我尝试运行剧本时却收到此错误消息:

λ ansible-playbook -i hosts.ini test.yml
ERROR! Syntax Error while loading YAML.
  did not find expected key

The error appears to have been in '~/ansible-test/roles/test/tasks/main.yml': line 5, column 1, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:


- name: Test message
^ here

是否可以在 ansible 角色任务文件中使用 YAML 锚点?或者有更好的方法来实现这一点吗?


是否可以在 ansible 角色任务文件中使用 YAML 锚点?或者有更好的方法来实现这一点吗?

当然可以,但实际情况是您创建的 YAML 文档不合法;你不能只使用任意的顶级密钥并期望好的结果——它与 YAML 锚点无关

你想要的是:

- set_fact:
    foo: &foo
      msg: this is a test

- name: Test message
  debug:
    <<: *foo

你不必使用set_fact,任何“不可执行”的任务都可以,你也可以使用when:阻止它运行,因为 YAML 结构很重要。您还可以在中创建该结构vars:某些其他任务的块,即使该任务不使用 var

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Ansible 角色任务文件中使用 YAML 锚点 的相关文章

随机推荐