Ansible 在键中获取带点的变量

abs*_*urd 2 ansible

我想让 Ansible 读出内核中的用户命名空间是否被激活 (CentOS)。当我运行时,相应的值是可见的

- debug:
    msg: "{{ ansible_cmdline }}"
Run Code Online (Sandbox Code Playgroud)

这给了我输出:

 "msg": {
    "BOOT_IMAGE": "/vmlinuz-...",
    "LANG": "...",
    "crashkernel": "...",
    "namespace.unpriv_enable": "...",
    "quiet": ...,
    "rd.lvm.lv": "...",
    "rhgb": ...,
    "ro": ...,
    "root": "...",
    "user_namespace.enable": "1"
}
Run Code Online (Sandbox Code Playgroud)

但是,我没有成功直接查询子项:

- debug:
    msg: "{{ ansible_cmdline.user_namespace.enable }}"
Run Code Online (Sandbox Code Playgroud)

Ansible 将 解释.enable为进一步的子项: The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'user_namespace'

如何访问密钥"user_namespace.enable"

abs*_*urd 8

自己解决了:

要使用点表示键,请使用带单引号的数组表示法而不是点表示法,即:

- debug:
    msg: "{{ ansible_cmdline['user_namespace.enable'] }}"
Run Code Online (Sandbox Code Playgroud)

这将返回值。

参见:Ansible 常见问题解答