Dynamically expand dictionary variables

14 views
Skip to first unread message

Kees de Jong

unread,
May 3, 2018, 5:26:40 AM5/3/18
to Ansible Project
I'm trying to unify the way I install packages, I have the following vars/main.yml:
---
packages
:
  system
:
    common
:
     
- crudini
     
- dump
     
- duplicity
     
- git
     
- mdadm
     
- irssi
     
- lynx
     
- postfix
     
- powerline
     
- rsync
     
- tmux
     
- vim
   
Debian:
     
- ntp
   
Fedora:
     
- langpacks-en
     
- langpacks-nl
     
- livecd-tools
     
- rktime
     
- tmux-powerline
     
- tuned
     
- vim-powerline

And the following task:
- block:
  - name: install ansible dependencies
    package: name={{ item }} state=present
    with_flattened:
      - "{{ packages.system.common }}"
      - "{{ packages.system.Fedora }}"
      - "{{ vars['packages.system.' + ansible_distribution] }}"
  when: ansible_distribution == "Fedora"
  tags:
    install_custom2

Which results in the following error:
TASK [common : install ansible dependencies] *******************************************************************************************
fatal
: [host]: FAILED! => {"msg": "'dict object' has no attribute u'packages.system.Fedora'"}

Please note that the "{{ packages.system.Fedora }}"  works fine but the "{{ vars['packages.system.' + ansible_distribution] }}" fails (which expands to packages.system.Fedora as well). It looks like a type error. When I organize the package names in vars/main.yml as separate lists, it does work. But I would like to create this dictionary structure since it organizes the variables nicely. Is there a way to expand dictionary variables dynamically just like list variables?

Kees de Jong

unread,
May 3, 2018, 6:29:55 AM5/3/18
to Ansible Project
Got it, it works with: "{{ packages.system[ansible_distribution] }}"
Reply all
Reply to author
Forward
0 new messages