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

Nat*_*ara 2 ansible

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

主机配置文件

localhost connection=local
Run Code Online (Sandbox Code Playgroud)

测试文件

---
- name: test
  hosts: localhost
  roles:
    - test
Run Code Online (Sandbox Code Playgroud)

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

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

- name: Test message
  debug:
    <<: *foo
Run Code Online (Sandbox Code Playgroud)

我希望foo字典的属性应该扩展到debug字典中,从而产生类似的结构

{
  "name": "Test message",
  "debug": {
    "msg": "this is a test"
  }
}
Run Code Online (Sandbox Code Playgroud)

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

? 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
Run Code Online (Sandbox Code Playgroud)

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

mda*_*iel 6

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

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

你想要的是:

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

- name: Test message
  debug:
    <<: *foo
Run Code Online (Sandbox Code Playgroud)

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