How to assign an empty value to a variable in Ansible?
If firewall_allowed_ports
in:
- name: port {{ item }} allowed in firewall
ufw:
rule: allow
port: "{{ item }}"
proto: tcp
with_items:
- 22
- "{{ firewall_allowed_ports }}"
is undefined, then this error occurs:
fatal: [host.example.com]: FAILED! => {"failed": true, "msg": "the field 'args'
has an invalid value, which appears to include a variable that is undefined.
Attempt to solve the issue
"{{ firewall_allowed_ports | }}"
results in:
fatal: [host.example.com]: FAILED! => {"failed": true, "msg": "template error
while templating string: expected token 'name', got 'end of print statement'.
String: {{ firewall_allowed_ports | }}"}
Use default([])
to create an empty list if firewall_allowed_ports
is undefined. The with_items
will skip it when empty.
- name: port {{ item }} allowed in firewall
ufw:
rule: allow
port: "{{ item }}"
proto: tcp
with_items:
- 22
- "{{ firewall_allowed_ports | default([]) }}"