根据事实创建变量 [英] Create Variable From Ansible Facts

查看:53
本文介绍了根据事实创建变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有四个系统,在这些系统中,我需要提取事实,然后将它们用作jinja 2模板上的变量.

I have four systems, in those I need to extract facts then use them as variables on a jinja 2 template.

在Ansible中,我有:

In Ansible i have:

vars:
    office1:
       web01:
          myip: 10.10.10.10 // or fact
          peer: 10.10.10.20
       web02
          myip: 10.10.10.20 // or fact
          peer: 10.10.10.10

    office2:
       web01:
          myip: 10.20.20.30 // or fact
          peer: 10.20.20.40
       web02
          myip: 10.20.20.40 // or fact
          peer: 10.20.20.30 

在Jinja 2模板上,我有:

On the jinja 2 template I have:

# Config File:
host_name: {{ ansible_hostname }}  // web01
host_ip: {{ ansible_eth0.ipv4.address }}
host_peer: {{ office1."{{ ansible_hostname }}".peer }}

但是我得到一个错误,提示未定义Ansible变量:office1.ansible_hostname.peer.

I however get error that Ansible variable: office1.ansible_hostname.peer is not defined.

任何帮助,将不胜感激.

Any help with this would be greatly appreciated.

推荐答案

Ansible中的扩展不是递归的.尝试下面的扩展

Expansion in Ansible is not recursive. Try the expansion below

host_peer: {{ office1[ansible_hostname].peer }}

例如下面的播放

- hosts: test_01
  gather_facts: yes
  vars:
    office1:
      test_01:
        myip: 10.20.20.30
        peer: 10.20.20.40
  tasks:
    - template:
        src: template.j2
        dest: /scratch/test_01.cfg

带有template.j2

with template.j2

# Config File:
host_name: {{ ansible_hostname }}
host_peer: {{ office1[ansible_hostname].peer }}

给予:

# cat /scratch/test_01.cfg 
# Config File:
host_name: test_01
host_peer: 10.20.20.40

回答问题

根据实际情况创建变量

Create Variable From Ansible Facts

一种选择是使用 lookup vars .例如下面的播放

an option would be to use lookup vars. For example the play below

vars:
  var1: var1
  var2: var2
  var3: var3
tasks:
  - debug:
      msg: "{{ lookup('vars', 'var' + item) }}"
    with_sequence: start=1 end=3

给予(节略):

"msg": "var1"
"msg": "var2"
"msg": "var3"

这篇关于根据事实创建变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆