ansible 查找不适用于环境变量

ansible lookup not working for enviroment variables

A​​nsible 查找不适用于环境变量。

这个有效:

- name: WIN_SHELL | Get ComputerName
  win_shell: $Env:ComputerName
  register: computerName

- debug:
    var: computerName.stdout_lines.0

None 其中:

- debug:
    msg: '{{lookup("env", "ComputerName")}}'

- debug:
    msg: '{{ lookup("env", "COMPUTERNAME") }}'

- debug:
    msg: '{{ lookup("env", "computername") }}'

- debug:
    msg: '{{ lookup("env", "computerName") }}'

关于 ansible 查找,我有什么不明白的地方吗?还是有一些情有可原的情况阻止了它的工作?我宁愿使用 ansible 查找而不是 win_shell 来保持幂等性。

env 与所有其他 lookups is executed on the controller machine. In this case, this is very well recalled in the synopsis on the documentation page for the env lookup

Allows you to query the environment variables available on the controller when you invoked Ansible.

所以您示例中的 win_shell 任务 - 在远程机器上执行 - 绝对不等同于您的查找测试 - 在控制器上执行。

如果您没有在您的主机上禁用事实收集(即通过在您的剧本中设置 gather_facts: false),所有环境变量都应该可以在 ansible_env 字典中访问。以下任务应该使您能够阅读所有这些内容并确保您的设置正确(以及获得正确的名称以使用它)。

- name: Debug all env vars
  debug:
    var: ansible_env