Ansible如何根据inventory的app_type变量查询对应主机IP地址
解决方法
最终可用playbook
--- - hosts: localhost name: 获取app_type为bob的主机IP gather_facts: no tasks: - name: 匹配规则筛选IP并赋值 set_fact: ambariIP: "{{ groups.all | map('extract', hostvars) | selectattr('app_type', 'equalto', 'bob') | map(attribute='inventory_hostname') | first }}" - name: 输出验证结果 debug: var: ambariIP
实现逻辑说明
groups.all直接拉取inventory中所有主机,完全不受组名变动影响map('extract', hostvars)批量提取每个主机对应的所有变量信息selectattr('app_type', 'equalto', 'bob')从所有主机变量里筛选出app_type等于bob的条目map(attribute='inventory_hostname')提取匹配到的主机的地址(你inventory中直接把IP填为主机名,所以这个值就是目标IP)- 末尾的
first表示取第一个匹配到的IP,如果你的环境存在多个app_type=bob的主机,去掉first就能得到IP列表
原有代码错误点
- lookup用法错误:
lookup('hosts', children)参数不符合语法,children是inventory的层级属性,不能直接作为参数传给hosts查找插件 - 条件判断逻辑错误:
hostvars[app_type]是错误的变量访问方式,app_type是单个主机的属性,不是hostvars的顶级键,需要先定位到主机才能读取对应的变量 - 缺少遍历筛选逻辑:没有遍历所有主机做匹配,单条when条件无法定位到目标主机
内容的提问来源于stack exchange,提问作者Eva
相关产品推荐
相关产品推荐

