Loops 如何跳过ansible循环中的空值

Loops 如何跳过ansible循环中的空值,loops,ansible,Loops,Ansible,我需要在ansible循环中跳过列表中的值null。当我使用when条件时,仍然会打印空值。 下面是我的剧本: - hosts: localhost vars: show: - read - write - null - test val: [] tasks: - name: Fact set_fact: val: "{{val+[item]}}" loop: &quo

我需要在ansible循环中跳过列表中的值null。当我使用when条件时,仍然会打印空值。 下面是我的剧本:

 - hosts: localhost
   vars:
    show:
     - read
     - write
     - null
     - test
    val: []
   tasks:
   - name: Fact
     set_fact:
      val: "{{val+[item]}}"
     loop: "{{show}}"
     when: item != "null"

   - name: Print
     debug:
      msg: "{{val}}"
输出:

TASK [Print] ***
ok: [localhost] => {
    "msg": [
        "read",
        "write",
        null,
        "test"
    ]
}

请告知。

我不知道是否要检查变量是否为文本形式的“null”,或者该变量是否没有值且已为null,因此我将编写两个示例:),将null值设为字符串并作为字符串进行比较:

- hosts: localhost
  vars:
    show:
      - read
      - write
      - "null"
      - test
    val: []
  tasks:
    - name: Fact
      set_fact:
        val: "{{val+[item]}}"
      loop: "{{show}}"
      when: "'{{item}}' != 'null'"

    - name: Print
      debug:
        msg: "{{val}}"
测试该值是否为null,并且它确实没有我们将使用的任何值,对于该示例为“无”:

- hosts: localhost
  vars:
    show:
      - read
      - write
      - null
      - test
    val: []
  tasks:
    - name: Fact
      set_fact:
        val: "{{val+[item]}}"
      loop: "{{show}}"
      when: item is not none

    - name: Print
      debug:
        msg: "{{val}}"
引用

表示缺少值。这通常绑定到本机类似null的值(例如,Perl中的undef,Python中的None)

有更多关于如何测试null的选项

  • 与Python相比,无
  • when:item!=没有一个
    
  • 使用Jinja测试
  • 何时:项不是无
    
  • 如果出于任何原因必须与字符串进行比较,Jinja筛选器会将null转换为字符串“None”
  • when:item | string!='没有
    
  • 最有效的方法是在迭代之前从列表中删除空值
  • 循环:{{show | reject('none')| list}”