Ansible 动态主机变量
Ansible Dynamic Host Vars
是否可以在循环中替换 {{ item.name }}
然后使用它来查找主机变量?
注意:{{ 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"
tasks:
- name: Do Loop
uri:
url: "https://example.com/{{hostvars['127.0.0.1']['existing_item_{{ item.name }}'] }}"
loop: # Loop where item.name is "this" then "that"
以上任务将 运行 两次并调用:
https://example.com/1234
and
https://example.com/2345
这可能吗?
这感觉应该更容易。有没有更简单的方法?
像下面这样定义变量是否适用于您的场景?
existing_item:
this: “1234”
that: “2345”
然后循环 existing_item.
下面的任务
- debug:
msg: "{{ hostvars[inventory_hostname]['existing_item_' ~ item] }}"
loop:
- 'this'
- 'that'
给予
ok: [127.0.0.1] => (item=this) => {
"msg": "1234"
}
ok: [127.0.0.1] => (item=that) => {
"msg": "2345"
}
Q: This feels like it should be easier. Is there a simpler way?
答:可以使用Lookup with the vars插件。下面的任务
- debug:
msg: "{{ lookup('vars', 'existing_item_' ~ item) }}"
loop:
- 'this'
- 'that'
给出相同的结果。
是否可以在循环中替换 {{ item.name }}
然后使用它来查找主机变量?
注意:{{ 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"
tasks:
- name: Do Loop
uri:
url: "https://example.com/{{hostvars['127.0.0.1']['existing_item_{{ item.name }}'] }}"
loop: # Loop where item.name is "this" then "that"
以上任务将 运行 两次并调用:
https://example.com/1234
and
https://example.com/2345
这可能吗?
这感觉应该更容易。有没有更简单的方法?
像下面这样定义变量是否适用于您的场景?
existing_item:
this: “1234”
that: “2345”
然后循环 existing_item.
下面的任务
- debug:
msg: "{{ hostvars[inventory_hostname]['existing_item_' ~ item] }}"
loop:
- 'this'
- 'that'
给予
ok: [127.0.0.1] => (item=this) => {
"msg": "1234"
}
ok: [127.0.0.1] => (item=that) => {
"msg": "2345"
}
Q: This feels like it should be easier. Is there a simpler way?
答:可以使用Lookup with the vars插件。下面的任务
- debug:
msg: "{{ lookup('vars', 'existing_item_' ~ item) }}"
loop:
- 'this'
- 'that'
给出相同的结果。