Ansible with_dict 需要一个字典 - 空白 Null 字典变量

Ansible with_dict expects a dict - blank Null dictionary variable

Ansible 1.9.4

在我的 group_vars/slave/slave 文件中,我将以下变量设置为 NULL 值(none/not defined/empty 字符串更准确):

# NFS mount settings
slave_nfsmount:

剧本调用 task/action:

  - name: Ensure nfs mount directory exists
    file: path={{item.key}} state=directory
    with_dict: "{{slave_nfsmount | default({})}}"
    ignore_errors: yes

收到错误消息:

TASK: [Ensure nfs mount directory exists] ************************************** 
fatal: [12.19.22.33] => with_dict expects a dict

FATAL: all hosts have already failed -- aborting

不想在global_vars/slave/slave文件中设置slave_nfsmount变量的值(因为用户可以在命令行或它可以通过其他方式提供,具体取决于用户是否希望在运行时传递什么)。因为,目前它对 slave_nfsmount 变量使用 NULL blank/none 值,所以我在 with_dict: 语句中使用 "{{ slave_nfsmount | default({})}}"

当值为 blank/null/not defined/empty 时,我如何才能使此工作 以使我的剧本不会失败?

我试过给:and slave_nfsmount is not defined

ignore_errors: yes (True),但是没有用,剧本仍然失败,出现如上所示的致命错误。

I have the following variable set to NULL value (none/not defined)

不,你没有。你有一个定义的变量。

例如使用三元过滤器。

with_dict: "{{slave_nfsmount | ternary(slave_nfsmount, {})}}"

default() 过滤器 returns 仅当 var 为 undefined.

时的默认值

http://jinja.pocoo.org/docs/2.9/templates/#default

If the value is undefined it will return the passed default value, otherwise the value of the variable:

在您的例子中,slave_nfsmount 已定义且为 NULL。

如果你想让这个变量被额外的变量覆盖(即 -e 参数),在你初始化它的时候给它一个默认值:

slave_nfsmount: {}