【问题标题】:Conditionally concat jinja2 lists有条件地连接 jinja2 列表
【发布时间】:2020-05-22 19:18:29
【问题描述】:

一些用于 ansible 角色的数据:

list1:
  - foo
  - bar
list2:             # sometimes this is empty

这个ansible任务失败了:

- name: hello
  somemodule:
    dosomething: "{{ list1 + list2 }}"

错误:

致命:[本地主机]:失败! => {"msg": "({{list1 + list2}}) 发生意外的模板类型错误:只能将列表(不是 \"NoneType\")连接到列表"}

有没有办法仅在list2 不为空时进行条件连接?

【问题讨论】:

    标签: ansible jinja2


    【解决方案1】:

    您可以将none bulitin 测试与inline if expression 结合使用:

    - debug:
        msg: "{{ list1 + (list2 if list2 is not none else []) }}" 
    

    鉴于剧本

    - hosts: local
      gather_facts: no
      vars:
        list1:
          - foo
          - bar
        list2:
    
      tasks:
        - debug:
            msg: "{{ list1 + (list2 if list2 is not none else [])  }}"
    

    一出戏将导致此重述:

    PLAY [local] **************************************************************************************
    
    TASK [debug] **************************************************************************************
    ok: [local] => {
        "msg": [
            "foo",
            "bar"
        ]
    }
    
    PLAY RECAP ****************************************************************************************
    local                      : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 
    

    【讨论】:

    • 除非list2 完全未定义,否则这将不起作用。对于当前 OP 的示例,它仍然会引发错误。您需要完全删除声明,或者将其设为空列表(即list2: []
    • 是的,我的错我虽然 undefined 会抓住它。我有一个编辑来了
    • 发生在最好的情况下;)
    • 好吧,尽管您的编辑在技术上是绝对正确的,但我仍然强烈鼓励 OP 在不声明列表的情况下使用 default,并将空列表详细声明为....空列表而不是作为无/空字符串。
    • @Zeitounator 你的list2: [] 方法的好处是上述条件检查变得不必要了。
    猜你喜欢
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 2022-10-14
    • 2015-03-29
    • 1970-01-01
    • 2021-04-14
    相关资源
    最近更新 更多