Ansible动态主机变量

时间:2019-09-20 03:08:48

标签: 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']['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

这可能吗?

感觉应该更简单。有没有更简单的方法?

2 个答案:

答案 0 :(得分:0)

像下面那样定义变量是否适合您的情况?

existing_item:
  this: “1234”
  that: “2345”

然后循环遍历现存项目。

答案 1 :(得分:0)

下面的任务

- 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:这感觉应该更容易。有没有更简单的方法?

A:可以将Lookupvars插件一起使用。下面的任务

- debug:
    msg: "{{ lookup('vars', 'existing_item_' ~ item) }}"
  loop:
    - 'this'
    - 'that'

给出相同的结果。

相关问题