-2

I have dict defined with a lot of sub elements:

kernel:
  vm:
    swappiness: 0
    dirty_background_ratio: 123
    dirty_ratio: 123
    dirty_expire_centisecs: 123
  sys:
    fs:
      file_max: 123456
  net:
    ipv4:
      tcp_max_syn_backlog: 123456
      tcp_slow_start_after_idle: 0
      tcp_abort_on_overflow: 1
    core:
      somaxconn: 123456
      netdev_max_backlog: 123456
      rmem_max: 123456
      wmem_max: 123456
      rmem_default: 123456
      rmem_max: 123456

And I have a task (not working) below as an example of what I'm trying to do to set the kernel parameters.

- name: "Tune kernel parameters"
  sysctl:
    name: "{{ item.key }}"
    value: "{{ item.value[item.key] }}"
    state: present
    sysctl_set: yes
  with_subelements:
    - kernel

How can each item the dict be set without having to name each key name?

user3358549
  • 79
  • 1
  • 6
  • What exactly do you mean by *"without having to name each key name"*? – NPE Jul 13 '17 at 08:51
  • @NPE Thanks for the quick reply. The docs ( http://docs.ansible.com/ansible/playbooks_loops.html#looping-over-subelements ) shows that the key's name needs to be named. For example: "name" in `{{ item.0.name }}`, which is "alice". I would have to name each keys. For example, I think that I would have to do `{{ item.0.net.core.somaxconn }}`. Since more sub-dicts maybe added/removed, I rather get the key, say `{{ item.key }}`, and the key's value, say `{{ item.value[item.key} }}`. I don't know what the correct syntax do that or if it's even possible. I just need the name of the key and its value – user3358549 Jul 13 '17 at 09:05
  • here's another example https://stackoverflow.com/questions/41908715/ansible-with-subelements where the keys' names have to be listed (surname, name and age). I don't want to have to update the task with a new sub element's key name every time there's a new dict+value added. – user3358549 Jul 13 '17 at 09:09
  • I bet this is possible only with custom filter plugin for Ansible, as I see no other way to flatten nested dictionary into a list of dot-separated strings. – Konstantin Suvorov Jul 13 '17 at 13:14

1 Answers1

2

Iterating over dictionaries

d = {'x': 1, 'y': 2, 'z': 3} 

for key, value in d.iteritems():

      print key,value
Kallz
  • 3,244
  • 1
  • 20
  • 38
  • I need to do this in Ansible without adding python code. I removed the python tags. How do I do this in Ansible? (version 2.3.1 at the moment). – user3358549 Jul 13 '17 at 09:14