我正在尝试创建一个包含多个重复部分的ansible角色任务文件,并且我想利用YAML的锚点功能,该功能允许在文件之间共享数据。在我的实际文件中,我有3个或4个属性在文件中的多个任务中需要完全相同,因此锚点似乎是完美的解决方案。这是我的设置:
localhost connection=local
---
- name: test
hosts: localhost
roles:
- test
---
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
是否可以在角色角色任务文件中使用YAML锚?还是有更好的方法来做到这一点?
答案 0 :(得分:1)
是否可以在角色角色任务文件中使用YAML锚?还是有更好的方法来做到这一点?
当然可以,但这是因为您创建的YAML文档不是合法的;您不能只使用任意的顶级密钥并期待良好的结果-它与YAML锚点无关
您想要的是:
- set_fact:
foo: &foo
msg: this is a test
- name: Test message
debug:
<<: *foo
您不必使用set_fact
,任何“非可执行”任务都可以,并且您也可以使用when:
来阻止它甚至运行,因为仅YAML结构很重要。您也可以在其他任务的vars:
块中创建该结构,即使该任务不使用var