Spaniard89
Spaniard89

Reputation: 2419

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

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

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:

echo ${TEMP_CONFIG}

in my terminal it gives an empty result.

Any help would be appreciated.

Upvotes: 8

Views: 6968

Answers (1)

techraf
techraf

Reputation: 68609

There are at least two problems:

  1. You should pass copy_config.stdout as 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_profile which 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.

Upvotes: 10

Related Questions