Can't extract a nested variable in ansible of a dict based on another variable

Viewed 33

I have a variables file like so

apps:
  appOne:
    slug: none
    ports:
      - "8999:8999"
  kong:
    slug: somerepo/ansible.kong.git
    ports:
      - "8000:8000"
      - "8001:8001"
      - "8443:8443"
      - "8445:8445"

in my vars/apps_config file

I'm trying to figure out the ports based on the {{ app_name }} but can't seem to find a way to drill into the apps object.

So in my yml file I'm executing I have

vars_files:
   - "vars/app_config"
  vars:
      app_name: kong
      container_ports: "{{ apps [{{ app_name }}]['ports'] }}"

but ansible doesn't like the nested variable {{ app_name }}. I saw someone mention using vars['somestring'] before but the following doesn't seem to work

vars['apps.{{ app_name }}']

any ideas?

1 Answers

the right syntax is:

container_ports: "{{ apps[app_name]['ports'] }}"

*inside {{}} app_name is seen like a variable


test:

- name: test
  hosts: localhost
  vars_files:
   - "vars/app_config"
  vars:
      app_name: kong
      container_ports: "{{ apps[app_name]['ports'] }}"   
  tasks:
    - debug:
        var: container_ports

result:

ok: [localhost] => 
  container_ports:
  - 8000:8000
  - 8001:8001
  - 8443:8443
  - 8445:8445
Related