1
votes

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

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 

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

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

Any help with this would be greatly appreciated.

1

1 Answers

1
votes

Expansion in Ansible is not recursive. Try the expansion below

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

For example the play below

    - 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

with template.j2

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

gives

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

To answer the question

Q: "Create Variable From Ansible Facts"

A: 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

gives (abridged)

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