Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 997
Spaniard89 Avatar asked Feb 26 '17 14:02

Spaniard89


People also ask

How do you set an environment variable in Ansible?

You can use the environment keyword at the play, block, or task level to set an environment variable for an action on a remote host. With this keyword, you can enable using a proxy for a task that does http requests, set the required environment variables for language-specific version managers, and more.

How can you set environment variables from the command line?

To set an environment variable, use the command " export varname=value ", which sets the variable and exports it to the global environment (available to other processes). Enclosed the value with double quotes if it contains spaces. To set a local variable, use the command " varname =value " (or " set varname =value ").

How do you store output of a command in a variable in Ansible?

Create the playbook to execute the “df” command to check the /boot usage. Use “register” to store the output to a variable.


1 Answers

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.

like image 92
techraf Avatar answered Nov 03 '22 00:11

techraf