2017-02-26 206 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