accessing nested variables in dictionary that contains ansible-variable as key

10 views
Skip to first unread message

Philip Svensson

unread,
Jan 26, 2021, 6:34:09 PM1/26/21
to Ansible Project
Hey I'm wondering how I should point to variables nested like shown below.
if it helps, the playbook I'm writing doesn't need to work with multiple hosts at once

The variable cannot be re-structured since it's being used by another ansible-module I do not maintain

---

  vm_specs:
    "{{ hostname }}":
      dns1: 1.1.1.1
      dns2: 2.2.2.2

I've tried a bunch of things (that I assume are all jibberish) for this but I can't seem to wrap my head around the mixture of yaml/python/jinja2

Thanks in advance

//Philip

Vladimir Botka

unread,
Jan 26, 2021, 10:44:05 PM1/26/21
to Philip Svensson, ansible...@googlegroups.com
On Tue, 26 Jan 2021 15:34:09 -0800 (PST)
Philip Svensson <philip....@jeppesen.com> wrote:

> how I should point to variables nested like shown below.
>
> vm_specs:
> "{{ hostname }}":
> dns1: 1.1.1.1
> dns2: 2.2.2.2

For example,

shell> cat playbook.yml
- hosts: localhost
vars:
vm_specs:
"{{ hostname }}":
dns1: 1.1.1.1
dns2: 2.2.2.2
tasks:
- set_fact:
my_hostname: "{{ vm_specs.keys()|first }}"
my_dns: "{{ vm_specs.values()|first }}"
- debug:
var: my_hostname
- debug:
var: my_dns

gives

shell> ansible-playbook playbook.yml -e hostname=test

TASK [debug]
*****************************************************
ok: [localhost] =>
my_hostname: test

TASK [debug]
*****************************************************
ok: [localhost] =>
my_dns:
dns1: 1.1.1.1
dns2: 2.2.2.2

--
Vladimir Botka
Reply all
Reply to author
Forward
0 new messages