创建事实Ansible和Jinja2的VAR



来自Ansible Facts

的板条

更新:我有四个系统,在我需要提取事实的那些系统中,然后将它们用作jinja 2模板上的变量。真实的主机名称中有一个带有虚线的前缀,这使得很难将整个主机名用作变量。系统的设置为:

office1
    debn-web01
    ubun-web02
office2
    linx-web01
    linx-web02

在我有:

的Ansible Play中
vars:
    office1:
       web01:
          myip: 10.10.10.10
          peer: 10.10.10.20
       web02:
          myip: 10.10.10.20
          peer: 10.10.10.10
    office2:
       web01:
          myip: 10.20.20.30
          peer: 10.20.20.40
       web02:
          myip: 10.20.20.40
          peer: 10.20.20.30

我想在主机名上的dash之后提取主机名,即" debn -web01" ->" web01"以将其用作先前创建的Ansible变量。

所以在jinja2模板上我有:

# This should create the var: web01
{% set trimd_hostname = ansible_hostname.split("-")[1] %}
# Start of Ansible Config File:
host_name: {{ ansible_hostname }}
web01 host_ip: {{ ansible_eth0.ipv4.address }}
host_peer: {{ office1[ trimd_hostname ]peer }}

装饰选项正在工作,因为我可以在模板上单独打印输出。但是,我会出现错误,即peer不是office1.trimd_hostname的变量对象。

回答这个问题有些棘手,因为您没有发布完整的复制器。这意味着这个问题可能有些偏离,因为我不得不对您正在做的事情做出一些假设。

如果我尝试通过以下示例剧本来重现您的问题,则它可以无错误:

---
- hosts: localhost
  gather_facts: false
  vars:
    office1:
      web01:
        myip: 10.10.10.10
        peer: 10.10.10.20
      web02:
        myip: 10.10.10.20
        peer: 10.10.10.10
    office2:
      web01:
        myip: 10.20.20.30
        peer: 10.20.20.40
      web02:
        myip: 10.20.20.40
        peer: 10.20.20.30
    trimd_hostname: web01
    ansible_hostname: debn-web01
    ansible_eth0:
      ipv4:
        address: 1.2.3.4
  tasks:
    - copy:
        dest: ./output.txt
        content: |
          {% set trimd_hostname = ansible_hostname.split("-")[1] %}
          host_name: {{ ansible_hostname }}
          web01 host_ip: {{ ansible_eth0.ipv4.address }}
          host_peer: {{ office1[trimd_hostname].peer }}

output.txt中产生以下内容:

host_name: debn-web01
web01 host_ip: 1.2.3.4
host_peer: 10.10.10.20

我已经指出了您的问题中的错别字,但是很难判断这是实际错误,还是在编写问题时只是复制/粘贴错误。

我想提出另一种组织数据的方式。摆脱office1office2变量,而是使用Ansible host_vars存储信息。

也就是说,创建具有以下内容的host_vars/dbn-web01.yml

myip: 10.10.10.10
peer: 10.10.10.20

,对于其他主机类似。然后您的模板简单:

host_name: {{ ansible_hostname }}
web01 host_ip: {{ ansible_eth0.ipv4.address }}
host_peer: {{ peer }}

peer变量的值将适用于任务运行的特定主机。

最新更新