How to create default empty dict to combine filter in Ansible?

Viewed 3365

I write a role. In defaults/main.yml I have:

sysctl:
  net.inet.ip.forwarding: 1
  vm.swappiness: 10

tasks/main.yml:

- name: Setup sysctl.conf
  sysctl: name="{{ item.0 }}" value="{{ item.1 }}" state=present
  become: yes
  loop: "{{ sysctl_default | combine(sysctl) | dictsort }} "

If user doesn't define sysctl in vars ansible will raise an error. Default parameters must be set if user skip this settings. How to create empty dictionary if user ommit sysctl settings in his playbook? Such expression {{ sysctl_default | combine(sysctl | default({})) | dictsort }} doesn't working:

fatal: [192.168.140.96]: FAILED! => {"msg": "|combine expects dictionaries, got AnsibleUndefined"}
1 Answers

Q: "{{ sysctl_default | combine(sysctl | default({}) | dictsort }} doesn't working"

A: ... because of the missing closing parenthesis ")". Correct syntax is

{{ sysctl_default | combine(sysctl|default({})) | dictsort }}

Q: "Again this not working: fatal: [192.168.140.96]: FAILED! => {"msg": "|combine expects dictionaries, got AnsibleUndefined"}"

A: The next problem is the undefined variable sysctl_default. For example the play

  vars:
    sysctl_default:
      net.inet.ip.forwarding: 1
      vm.swappiness: 10
  tasks:
    - debug:
        msg: "name={{ item.0 }} value={{ item.1 }} state=present"
      loop: "{{ sysctl_default | combine(sysctl|default({})) | dictsort }}"

gives

"msg": "name=net.inet.ip.forwarding value=1 state=present"
"msg": "name=vm.swappiness value=10 state=present"
Related