从 bash 命令的命令输出在 Ansible 中设置环境变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42469836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:49:23  来源:igfitidea点击:

Setting an environment variable in Ansible from a command output of bash command

bashenvironment-variablesansible

提问by Spaniard89

I would like to set output of a shell command as an environment variable in Ansible.

我想在 Ansible 中将 shell 命令的输出设置为环境变量。

I did the following to achieve it:

我做了以下事情来实现它:

- name: Copy content of config.json into variable
  shell:  /bin/bash -l -c "cat /storage/config.json"
  register: copy_config
  tags: something

- name: set config
  shell: "echo $TEMP_CONFIG"
  environment:
    TEMP_CONFIG: "{{copy_config}}"
  tags: something

But somehow after the ansible run, when I do run the following command:

但不知何故在 ansible 运行之后,当我运行以下命令时:

echo ${TEMP_CONFIG}

in my terminal it gives an empty result.

在我的终端中,它给出了一个空结果。

Any help would be appreciated.

任何帮助,将不胜感激。

回答by techraf

There are at least two problems:

至少有两个问题:

  1. You should pass copy_config.stdoutas a variable

    - name: set config
      shell: "echo $TEMP_CONFIG"
      environment:
        TEMP_CONFIG: "{{copy_config.stdout}}"
      tags: something
    
  2. You need to register the results of the above task and then again print the stdout, so:

    - name: set config
      shell: "echo $TEMP_CONFIG"
      environment:
        TEMP_CONFIG: "{{copy_config.stdout}}"
      tags: something
      register: shell_echo
    
    - debug:
        var: shell_echo.stdout
    
  3. You never will be able to pass the variable to a non-related process this way. So unless you registered the results in an rc-file (like ~/.bash_profilewhich is sourced on interactive login if you use Bash) no other shell process would be able to see the value of TEMP_CONFIG. This is how system works.

  1. 你应该copy_config.stdout作为一个变量传递

    - name: set config
      shell: "echo $TEMP_CONFIG"
      environment:
        TEMP_CONFIG: "{{copy_config.stdout}}"
      tags: something
    
  2. 您需要注册上述任务的结果,然后再次打印stdout,因此:

    - name: set config
      shell: "echo $TEMP_CONFIG"
      environment:
        TEMP_CONFIG: "{{copy_config.stdout}}"
      tags: something
      register: shell_echo
    
    - debug:
        var: shell_echo.stdout
    
  3. 您永远无法以这种方式将变量传递给不相关的进程。因此,除非您在 rc 文件中注册结果(~/.bash_profile如果您使用 Bash,则该文件来源于交互式登录),否则其他 shell 进程将无法看到TEMP_CONFIG. 这就是系统的工作原理。