2017-02-26 205 views
3

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

我做了以下实现它:

- 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 

但ansible运行后不知何故,当我运行以下命令:在我的终端

echo ${TEMP_CONFIG} 

它提供了一个空的结果。

任何帮助,将不胜感激。

回答

5

至少有两个问题:

  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. Yo你永远不能通过这种方式将变量传递给非相关进程。因此,除非您将结果注册到rc文件(如使用Bash的~/.bash_profile采用交互式登录方式进行采购),否则其他shell进程将无法看到TEMP_CONFIG的值。这是系统的工作原理。

+0

非常感谢提示答案,我对第2和第3点有疑问,为什么我需要注册它并回显std.out?它的目的是什么?我以为在做'environment: TEMP_CONFIG:“{{copy_config.stdout}}”'会将这个添加到.bash_profile文件中,为什么我需要明确地添加它? – Spaniard89

+0

您需要引用'stdout'子项,因为这是Ansible存储命令的标准输出的地方。不,它不会向'.bash_profile'添加任何内容,它只是为模块中指定的命令设置环境。 – techraf