raah
raah

Reputation: 230

How to access a nested variable in a referenced Hash.

I'm writing an Ansible Playbook and am trying to access a nested variable inside a referenced hash.

Here is my vars file:

SourceIPs:
  192.168.33.20:
    DestIP: 192.168.33.30
    Port: 22
  192.168.33.30:
    DestIP: 192.168.33.20
    Port: 22

Here is my task file:

- name: Testing varibale access.
  debug:
    msg: " Source IP: {{ ansible_host }} corresponding Port IP and Port {{ SourceIPs[' {{ansible_host}} '] }}  "

It fails when executing this saying dict_object has no variable called {{ ansible_host }}. So clearly its not converting that to the IP address of the current host.

However if I modify the task file to include a static host ip like so:

- name: Testing varibale access.
  debug:
    msg: " Source IP: {{ ansible_host }} corresponding Port IP and Port {{ SourceIPs['192.168.33.30'] }}  "

It works and get the values back for that particular host.

What I'm trying to achieve is get the values back associated to the host I'm currently executing on.

Upvotes: 1

Views: 1097

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68289

Never do nesting in Jinja2 expressions. You can use variables inside them without any wrappings:

- name: Testing varibale access.
  debug:
    msg: " Source IP: {{ ansible_host }} corresponding Port IP and Port {{ SourceIPs[ansible_host] }} "

Upvotes: 1

Related Questions