ansible - 使用多个嵌套主机变量时匹配单个自定义主机库存变量
问题描述
我正在尝试遍历清单文件中的匹配主机,其中每个主机都有某些变量,但是,每个主机可能有多个与之关联的嵌套变量,如下所示:
库存文件:
[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]
我不确定如何从主机清单中读取单个嵌套变量。
谢谢!!!
解决方案
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']"
推荐阅读
- google-sheets - 需要 AppSheet 指导
- javascript - 在 chrome 中打开包含特定内容的新标签页
- regex - 如何将网站从 www 重定向到非 www
- html - HTMLInputElement event.target.value 输出字符串事件,尽管它是范围元素(打字稿)
- llvm - 如何使用 llvm::cl::ParseCommandLineOptions> - 链接错误
- python - 如何在 SqlAlchemy 上订购嵌套的 SQL SELECT
- python - csv表堆栈到一列
- javafx - 如何在 FXML (JavaFX) 中制作响应式 ImageView
- json - 来自 GraphQL api 调用的未定义对象结果 - Web 控制台显示收到的 JSON 响应
- javascript - 尝试多次附加一个 html 表,但是当我重新单击它时,我的 'th' 总是出现在顶部而不是在 'tr' 之后