通过 extra-vars 或 inventory 变量将 Ansible 变量设置为未定义
Set Ansible variable to undefined through extra-vars or inventory variable
所以我有一个 Ansible 剧本,看起来像
---
- hosts: mygroup
tasks:
- debug:
msg: "{{ foo | default(inventory_hostname) }}"
我的库存文件看起来像
[mygroup]
127.0.0.1
由于 foo
未在任何地方定义,因此调试会按预期打印 127.0.0.1
。
但是假设我的库存文件看起来像
[mygroup]
127.0.0.1 foo=null
当我运行 剧本时,它打印出字符串null
。我还尝试使用 foo=None
并打印一个空字符串。如何通过 inventory 或 extra-vars 将变量设置为 null?
当我想取消设置已在剧本中定义的变量时,这可能很有用。
我正在使用 Ansible 版本 2.1.1.0。
Python(因此 Ansible)区分未定义的变量和具有 none 值的变量。
变量一旦定义就无法"undefine"。
结果即使您将值设置为none
,您指定的条件也永远不会将变量视为未定义。
您在输出日志中得到一个 ""
,因为这是 debug
模块显示 none 值的方式,而不是因为它是一个空字符串。
解决方案 1
使用带条件的三元运算符来检查 foo
变量的实际值:
- debug:
msg: "{{ ((foo is defined) and (foo != None)) | ternary(foo, inventory_hostname) }}"
解决方案 2
使用 "wrapper" 词典:
为 "wrapper" 字典中的变量定义默认值:
foodict:
foo: bar
在剧中引用变量为foodict.foo
:
---
- hosts: mygroup
tasks:
- debug:
msg: "{{ foodict.foo | default(inventory_hostname) }}"
通过使 "wrapper" 字典无效来覆盖清单文件中的值:
[mygroup]
127.0.0.1 foodict=None
所以我有一个 Ansible 剧本,看起来像
---
- hosts: mygroup
tasks:
- debug:
msg: "{{ foo | default(inventory_hostname) }}"
我的库存文件看起来像
[mygroup]
127.0.0.1
由于 foo
未在任何地方定义,因此调试会按预期打印 127.0.0.1
。
但是假设我的库存文件看起来像
[mygroup]
127.0.0.1 foo=null
当我运行 剧本时,它打印出字符串null
。我还尝试使用 foo=None
并打印一个空字符串。如何通过 inventory 或 extra-vars 将变量设置为 null?
当我想取消设置已在剧本中定义的变量时,这可能很有用。
我正在使用 Ansible 版本 2.1.1.0。
Python(因此 Ansible)区分未定义的变量和具有 none 值的变量。
变量一旦定义就无法"undefine"。
结果即使您将值设置为none
,您指定的条件也永远不会将变量视为未定义。
您在输出日志中得到一个 ""
,因为这是 debug
模块显示 none 值的方式,而不是因为它是一个空字符串。
解决方案 1
使用带条件的三元运算符来检查 foo
变量的实际值:
- debug:
msg: "{{ ((foo is defined) and (foo != None)) | ternary(foo, inventory_hostname) }}"
解决方案 2
使用 "wrapper" 词典:
为 "wrapper" 字典中的变量定义默认值:
foodict: foo: bar
在剧中引用变量为
foodict.foo
:--- - hosts: mygroup tasks: - debug: msg: "{{ foodict.foo | default(inventory_hostname) }}"
通过使 "wrapper" 字典无效来覆盖清单文件中的值:
[mygroup] 127.0.0.1 foodict=None