Làm cách nào để gán giá trị trống cho một biến trong Ansible?


12

Nếu firewall_allowed_portstrong:

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

không xác định, sau đó lỗi này xảy ra:

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

Cố gắng giải quyết vấn đề

"{{ firewall_allowed_ports | }}"

kết quả trong:

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

Câu trả lời:


14

Sử dụng default([])để tạo một danh sách trống nếu firewall_allowed_portskhông xác định. Các with_itemssẽ bỏ qua nó khi có sản phẩm nào.

- name: port {{ item }} allowed in firewall
  ufw:
    rule: allow
    port: "{{ item }}"
    proto: tcp
  with_items: 
    - 22
    - "{{ firewall_allowed_ports | default([]) }}"
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookie và Chính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.