在Ansible任务中加载全局环境变量 [英] Loading global environment variables in an Ansible task
问题描述
我在目标计算机的/etc/environment
中设置了几个全局环境变量,在运行某些Ansible任务时需要提供这些全局变量.例如
I have several global environment variables set in /etc/environment
on my target machine that I need to present when running some Ansible tasks. E.g.
MY_VAR=Some global variable
Ansible并不知道这些全局变量的值,所以我不能使用environment
功能.
The value of these global variables are not known to Ansible so I can't use the environment
functionality.
示例任务:
- shell: echo MY_VAR is $MY_VAR
register: my_var
- debug: msg={{ my_var.stdout }}
我得到的输出是MY_VAR is
,我希望它是MY_VAR is Some global variable
.我知道发生这种情况是因为非交互式Bash shell(Ansible使用)不从/etc/environment
加载环境,但是有没有办法在该环境的上下文中执行命令?
The output I get is MY_VAR is
where I would like it to be MY_VAR is Some global variable
. I understand that this is happening because non-interactive Bash shells (which Ansible uses) don't load the environment from /etc/environment
, but is there a way to execute my command in the context of that environment?
注意:我实际上并不想检索环境变量的值(如上所示),我只是希望它出现在执行shell
任务的上下文中内.
Note: I don't actually want to retrieve the value of the environment variable (as shown above), I just want it to be present in the context that I execute the shell
task in.
推荐答案
使用ansible_env
变量可通过事实获得远程环境变量.
Remote environment variables are available via facts using the the ansible_env
variable.
这将使用以下命令打印出用户Ansible登录到远程主机的所有变量:
This prints out all variables of the user Ansible logs into a remote host with:
- debug: var=ansible_env
如果Ansible用户无法使用全局环境变量,则可以在运行命令之前将其源于任务:
If global environment variables not available to the Ansible user, they can be sourced in a task before running your command:
- shell: . /etc/environment && commandhere
这篇关于在Ansible任务中加载全局环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!