2
votes

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
i think it makes more sense to add a when clause in your task, to check if the sysctl variable is defined and has items. by adding a default filter, what are you planning to achieve? run the sysctl task without a valid change to do?ilias-sp
I plan to add net.inet.ip.forwarding: 1 by default, because this role is for router. So, even if user skip this setting it will be ok, the role take care of it explicitly :)dynax60

1 Answers

2
votes

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"