8

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.

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks a lot for the prompt answer, I have question with respect to point 2 and 3, why do I need to register it and echo out the std.out? what's the purpose of it? I thought doing environment: TEMP_CONFIG: "{{copy_config.stdout}}" will add this into the .bash_profile file, why do I need to explicitly add it?
You need to reference stdout subkey, because that's where Ansible stores the stdout of the command. No, it won't add anything to .bash_profile, it just sets the environment for the command specified in the module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.