ansible - 有条件地连接 jinja2 列表

标签 ansible jinja2

ansible角色中使用的一些数据:

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

此 ansible 任务失败:

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

错误:

fatal: [localhost]: FAILED! => {"msg": "Unexpected templating type error occurred on ({{list1 + list2}}): can only concatenate list (not \"NoneType\") to list"}

是否有办法仅在 list2 不为空时有条件连接?

最佳答案

您可以使用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 

关于ansible - 有条件地连接 jinja2 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61962370/

相关文章:

Python 和 Ansible - 编解码器错误 UTF-8 到 ascii 转换

Ansible:如何将文件远程复制到远程

ansible - 如果列表中的任何项目为 True (Ansible),则仅运行一次命令

python - 在 Google App Engine 中调试 Jinja2

docker - 如何安全地将可能包含特殊字符的变量传递给 Ansible 中的 docker-compose 文件

server - 如何在ansible中的 "Do you want to continue"提示符上提供自定义输入?

linux - Ansible 无法创建 dir/$HOME/.ansible/cp

yaml - ansible - "when"条件不适用于逻辑 "AND"运算符

javascript - 单击下拉列表中基于该选项 ID 的选项后,如何在 html 表中显示数据?

python - url 查询中的字符 %7D 是什么意思?