可访问的本地环境变量

我想知道 Ansible 是否有办法访问本地环境变量。

文档引用目标机器上的访问变量:

{{ lookup('env', 'SOMEVAR') }}

是否有方法访问源计算机上的环境变量?

93619 次浏览

Those variables are in the management machine I suppose source machine in your case.

Check this: https://docs.ansible.com/ansible/devel/collections/ansible/builtin/env_lookup.html

Basically, if you just need to access existing variables, use the ‘env’ lookup plugin. For example, to access the value of the HOME environment variable on management machine:`

Now, if you need to access it in the remote machine you can just run your ansible script locally in the remote machine. Or you could just the ansible facts variables. If it's not in the ansible facts you can just run a shell command to get it.

I have a Linux vm running on osx, and for me:

lookup('env', 'HOME') returns "/Users/Gonzalo" (the HOME variable from osx), while ansible_env.HOME returns "/root" (the HOME variable from the vm).

Worth to mention, that ansible_env.VAR fails if the variable does not exists, while lookup('env', 'VAR') does not fail.

Use ansible lookup:

- set_fact: env_var="\{\{ lookup('env','ENV_VAR') }}"

Use delegate_to to run it on any machine you want:

- name: get running ansible user
ansible.builtin.set_fact:
local_ansible_user: "\{\{ lookup('env', 'USER') }}"
delegate_to: localhost