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

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

To do this, I did the following:

- 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 an inconspicuous run, when I run the following command:

echo ${TEMP_CONFIG}

in my terminal it gives an empty result.

Any help would be appreciated.

+4
source share
1 answer

There are at least two problems:

  • You must pass copy_config.stdoutas a variable

    - name: set config
      shell: "echo $TEMP_CONFIG"
      environment:
        TEMP_CONFIG: "{{copy_config.stdout}}"
      tags: something
    
  • You need to register the results of the above task, and then print again 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
    
  • . , rc (, ~/.bash_profile, , Bash), TEMP_CONFIG. .

+6

Source: https://habr.com/ru/post/1670873/


All Articles