简体   繁体   English

Ansible 从文件中设置环境变量并在 playbook 中访问它

[英]Ansible set environment variable from a file and access it within the playbook

I have the below Ansible script which runs on localhost我有以下在本地主机上运行的 Ansible 脚本

  - name: set env
    shell: ". /tmp/testenv"

  - name: get env
    debug:
      msg: "{{ lookup('env','TEST') }}"

In above script I'm trying to source the file and access the environment variables using the lookup.在上面的脚本中,我尝试使用查找来获取文件并访问环境变量。 But it seems like environment variable is not set.但似乎没有设置环境变量。 Is there anyway I can get this to work?无论如何我可以让它工作吗?

The shell command is one process and the lookup looks in the environment of the Ansible process, which is a different one. shell 命令是一个进程,查找在 Ansible 进程的环境中查找,这是一个不同的进程。 You have to echo the environment variable in your shell command and register the result.您必须在 shell 命令中回显环境变量并注册结果。

- hosts: localhost
  connection: local
  gather_facts: no
  tasks:

    - name: set env
      shell: "echo 'export TEST=test' > /tmp/testenv"

    - name: check env
      shell: ". /tmp/testenv; echo $TEST"
      register: result

    - name: get env
      debug:
        msg: "{{ result.stdout }}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在剧本中设置Ansible标签? - How to set an Ansible tag from within a playbook? 如何在 Ansible playbook 中为每个客户端设置不同的环境变量 - How to set different environment variable for each client in Ansible playbook Ansible - 设置 Playbook 级环境变量,但在定义一些任务之后 - Ansible - Set Playbook level Environment variable, but after defining some tasks 有没有办法在环绕Ansible playbook中的角色时设置环境变量? - Is there a way to set an environment variable while looping over a role in Ansible playbook? 从 ansible 剧本中的 yml 文件访问变量 - Accessing a variable from yml file in ansible playbook 如何从文件中访问数据并以分隔符分隔,然后将数据分配给变量并根据变量循环播放剧本 - How to access data from a file upto delimiter in ansible and assign data to a variable and loop playbook according to the variable 如何在ansible playbook中设置环境变量 - How to set environment variables in ansible playbook Ansible剧本,设置环境变量不起作用 - Ansible playbook, set environment variables not working Ansible playbook 中下次使用的环境集 - Set of environment for next using in Ansible playbook 从 ansible 剧本中的 var 文件中检索变量值 - Retrieve variable values from var file in ansible playbook
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM