如何在Ansible中为变量分配空值?


12

如果firewall_allowed_ports在:

- name: port {{ item }} allowed in firewall
  ufw:
    rule: allow
    port: "{{ item }}"
    proto: tcp
  with_items: 
    - 22
    - "{{ firewall_allowed_ports }}"

未定义,则发生此错误:

fatal: [host.example.com]: FAILED! => {"failed": true, "msg": "the field 'args' 
has an invalid value, which appears to include a variable that is undefined.

尝试解决问题

"{{ firewall_allowed_ports | }}"

结果是:

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 | }}"}

Answers:


14

使用default([])如果创建一个空列表firewall_allowed_ports是不明确的。with_items当为空时,它将跳过它。

- name: port {{ item }} allowed in firewall
  ufw:
    rule: allow
    port: "{{ item }}"
    proto: tcp
  with_items: 
    - 22
    - "{{ firewall_allowed_ports | default([]) }}"
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.