【问题标题】:Ansible Dynamic Host VarsAnsible 动态主机变量
【发布时间】:2019-09-20 03:08:48
【问题描述】:

是否可以在循环中替换 {{ 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

这可能吗?

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

【问题讨论】:

    标签: ansible jinja2 ansible-facts


    【解决方案1】:

    下面的任务

    - 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"
    }
    

    问:这感觉应该更容易。有没有更简单的方法?

    答:Lookup 可以与vars 插件一起使用。下面的任务

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

    给出相同的结果。

    【讨论】:

      【解决方案2】:

      像下面这样定义变量是否适用于您的场景?

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

      然后遍历existing_item。

      【讨论】:

        猜你喜欢
        • 2020-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-17
        • 1970-01-01
        • 2017-03-22
        • 1970-01-01
        • 2016-03-19
        相关资源
        最近更新 更多