我正在尝试在清单文件中循环访问匹配的主机,其中每个主机都有特定的变量,但是,每个主机可能有多个与之关联的嵌套变量,如下所示:
库存文件:
[support]
myhost1 application_role="['role1', 'role2']" team="['ops', 'dev']"
myhost2 application_role="['role1']" team="['ops', 'sales']"
我的目标是尝试将文件仅交付给与客户变量键"team"等于值"sales"匹配的主机。
我正在使用此测试任务进行测试只是为了获得一些响应,但正如您从输出中看到的那样,它跳过了所有这些,因为它没有捕获嵌套变量,它似乎将变量读取为一个完整的字符串而不是拆分?
测试任务:
- name: Loop through example servers and show the hostname, team attribute
debug:
msg: "team attribute of {{ item }} is {{ hostvars[item]['team'] }}"
when: hostvars[item]['team'] == "sales"
loop: "{{ groups['support'] }}"
输出:
PLAY [support] ************************************************************************
TASK [ssh_key_push : Loop through example servers and show the hostname, team attribute msg=team attribute of {{ item }} is {{ hostvars[item]['team'] }}] ***
skipping: [myhost1] => (item=myhost1)
skipping: [myhost1] => (item=myhost2)
skipping: [myhost1]
skipping: [myhost2] => (item=myhost1)
skipping: [myhost2] => (item=myhost2)
skipping: [myhost2]
我不确定如何让 ansible 从主机清单中读取单个嵌套变量。
谢谢!!!
when: hostvars[item]['team'] == "sales"
此表达式正在比较列表,例如
team:
- ops
- sales
到单个字符串值sales
.这将始终返回 false。
您要做的是检查列表是否包含该值。如此链接所述,Jinja2 提供了一个in
测试,但 ansbile 提供了在某些情况下可以简化写作的contains
。两个版本都是等效的:
when: hostvars[item]['team'] is contains 'sales'
# or
when: "'sales' in hostvars[item]['team']"