在ansible剧本中使用主机变量
我试图在剧本中结合“with_items”引用主机变量 我的库存在ansible剧本中使用主机变量,ansible,ansible-inventory,Ansible,Ansible Inventory,我试图在剧本中结合“with_items”引用主机变量 我的库存 [container] testcontainer-01.example.org template_name="syslog" ipv4="192.168.1.101" testcontainer-02.example.org template_name="syslog" ipv4="192.168.1.102" 剧本: tasks: - debug: var: "{{ item.ipv4 }}"
[container]
testcontainer-01.example.org template_name="syslog" ipv4="192.168.1.101"
testcontainer-02.example.org template_name="syslog" ipv4="192.168.1.102"
剧本:
tasks:
- debug:
var: "{{ item.ipv4 }}"
with_items:
- "{{ groups['container'] }}"
每当我运行播放时,都会出现以下错误:
The task includes an option with an undefined variable. The error was: 'ansible.utils.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'ipv4'
当我要求debug只使用{{item}}
时,如果没有ipv4属性,它只会说变量没有定义
"testcontainer-01.example.org ": "VARIABLE IS NOT DEFINED!: Unable to look up a name or access an attribute in template string ({{testcontainer-01.example.org}}).\nMake sure your variable name does not contain invalid characters like '-': unsupported operand type(s) for -: 'StrictUndefined' and 'StrictUndefined'"
如果需要运行播放的主机的ipv4,请使用
- debug:
var: ipv4
如果要列出容器中使用的所有ipv4
(未测试)如Vladimer Botka所述,以下作品
- debug:
var: "{{ hostvars[item].ipv4 }}"
with_inventory_hostnames:
- container
出于某种原因,Ansible仍然对我咆哮,说我的变量没有定义。尽管如此,它还是产生了我所需要的结果。ipv4变量的值正在正确的位置使用
ok: [containerhost.example.org] => (item=testcontainer-02.example.org) => {
"192.168.1.102": "VARIABLE IS NOT DEFINED!",
"item": "testcontainer-02.example.org"
}
ok: [containerhost.example.org] => (item=testcontainer-01.example.org) => {
"192.168.1.101": "VARIABLE IS NOT DEFINED!",
"item": "testcontainer-01.example.org"
}
@弗雷科:我发布了msg:“{{hostvars[item].ipv4}}”
。语法错误var:“{{hostvars[item].ipv4}}}”
,因为“{{hostvars[item].ipv4}}}”不是变量。这是一根绳子。这也是为什么Ansible仍然对我咆哮说我的变量没有定义的原因。
ok: [containerhost.example.org] => (item=testcontainer-02.example.org) => {
"192.168.1.102": "VARIABLE IS NOT DEFINED!",
"item": "testcontainer-02.example.org"
}
ok: [containerhost.example.org] => (item=testcontainer-01.example.org) => {
"192.168.1.101": "VARIABLE IS NOT DEFINED!",
"item": "testcontainer-01.example.org"
}