首页 > 解决方案 > 使用多个嵌套主机变量时匹配单个自定义主机库存变量

问题描述

我正在尝试遍历清单文件中的匹配主机,其中每个主机都有某些变量,但是,每个主机可能有多个与之关联的嵌套变量,如下所示:

库存文件:

[support]
myhost1 application_role="['role1', 'role2']" team="['ops', 'dev']"
myhost2 application_role="['role1']" team="['ops', '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']"

推荐阅读