【问题标题】:ansible inventory groups using jinja2使用 jinja2 的 ansible 库存组
【发布时间】:2021-02-23 07:00:06
【问题描述】:
devices:
  children:
    abcgroup:
      children:
        xyzgroup:
          children:
            group1:
              hosts:
                device509:
                  ansible_ssh_host: 1.1.1.1
                device510:
                  ansible_ssh_host: 2.2.2.2
            group2:
              hosts:
                devcice609:
                  ansible_ssh_host: 3.3.3.3
                device610:
                  ansible_ssh_host: 4.4.4.4
        defgroup:
          hosts:
            device0508:
                ansible_ssh_host: 30.30.30.30
            device0608:
                ansible_ssh_host: 31.31.31.31

我的 jinja2 模板

peer-keepalive 目标 {% if 'group1' in group_names %}{{ansible_ssh_host[1]}} source {{ansible_ssh_host}} {% endif %}

peer-keepalive 目标 {% if 'group2' in group_names %}{{ansible_ssh_host[1]}} source {{ansible_ssh_host}} {% endif %}

想要的输出或期望的输出

on device509 i should get below output
peer-keepalive destination 2.2.2.2 source 1.1.1.1

on device510 i should get below output
peer-keepalive destination 1.1.1.1 source 2.2.2.2

on device609 i should get below output
peer-keepalive destination 4.4.4.4 source 3.3.3.3

on device610 i should get below output
peer-keepalive destination 3.3.3.3 source 4.4.4.4

我在每个设备上得到的输出如下,我的 jinja2 模板错误我得到点 (.)

在 device509 上,我得到以下信息 对等保活目的地。来源 1.1.1.1 device510 我在下面 对等保活目的地。来源 2.2.2.2 在 device609 上,我得到以下信息 对等保活目的地。来源 3.3.3.3 device610 我在下面 对等保活目的地。来源 4.4.4.4

如何解决这个问题

【问题讨论】:

  • 如果要其他主机的ip,为什么要当前主机IP的第二个字符?你得到的正是你所要求的 => . 你的要求实际上根本不清楚。对于源来说,这很简单:你想使用当前的主机 IP。但是如何获取目标IP呢?
  • @Zeitounator device509 和 device510 是一对,在 device509 上的目标 ip 应该是 device510 ip,在 device510 上的目标 ip 应该是设备 509 ip。想要的输出与我得到的不同,看起来我的 jinja2 模板是错误的,我不知道如何获得“想要的输出”
  • 在您考虑模板之前,您已经遇到了 IMO 设计问题。你如何决定哪些设备是成对的?因为他们在同一个组?如果组突然包含 3 个主机会发生什么?你知道吗? device509 已经属于您库存中的 5 个组?您将如何区分 group1device?我的 2 美分:如果您正在设计配对,只需为每个设备添加一个 network_peer: deviceXXX 变量。在任何设备上运行时,您可以访问 hostvars[network_peer] 字典中对等方的任何值。
  • @Zeitounator 谢谢你的建议,我已经发布了答案。

标签: ansible jinja2 inventory


【解决方案1】:

这对我有用

peer-keepalive destination {{ hostvars[groups['group1'][1]].ansible_ssh_host }} source {{ hostvars[groups['group1'][0]].ansible_ssh_host }}

peer-keepalive destination {{ hostvars[groups['group1'][0]].ansible_ssh_host }} source {{ hostvars[groups['group1'][1]].ansible_ssh_host }}

group2 也一样

【讨论】:

    猜你喜欢
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多