Ansible动态主机变量
是否可以替换循环中的Ansible动态主机变量,ansible,jinja2,ansible-facts,Ansible,Jinja2,Ansible Facts,是否可以替换循环中的{{item.name}},然后使用它来查找hostvar 注意:{item.name}}是动态的,预先未知 主机变量的创建方式如下: existing_item_this: "1234" existing_item_that: "2345" 假设我们在一个列表中循环,其中item.name是“this”然后是“that”。 我希望ansible首先将{{item.name}替换为“this”,然后查找hostVar hostvars['127.0.0.1']['exist
{{item.name}}
,然后使用它来查找hostvar
注意:{item.name}}是动态的,预先未知
主机变量的创建方式如下:
existing_item_this: "1234"
existing_item_that: "2345"
假设我们在一个列表中循环,其中item.name
是“this”
然后是“that”
。
我希望ansible首先将{{item.name}
替换为“this”
,然后查找hostVar
hostvars['127.0.0.1']['existing_item_{{ item.name }}']
becomes
hostvars['127.0.0.1']['existing_item_this']
becomes
"1234"
上述任务将运行两次并调用:
https://example.com/1234
and
https://example.com/2345
这可能吗
这感觉应该更容易。有更简单的方法吗?下面这样定义变量是否适用于您的场景
existing_item:
this: “1234”
that: “2345”
然后在现有的_项上循环。下面的任务
- debug:
msg: "{{ hostvars[inventory_hostname]['existing_item_' ~ item] }}"
loop:
- 'this'
- 'that'
- debug:
msg: "{{ lookup('vars', 'existing_item_' ~ item) }}"
loop:
- 'this'
- 'that'
给予
问:这感觉应该更容易。有没有更简单的方法
答:可以与插件一起使用。下面的任务
- debug:
msg: "{{ hostvars[inventory_hostname]['existing_item_' ~ item] }}"
loop:
- 'this'
- 'that'
- debug:
msg: "{{ lookup('vars', 'existing_item_' ~ item) }}"
loop:
- 'this'
- 'that'
给出了相同的结果