I am currently working through replacing a legacy orchestration tool with Ansible while maintaining the existing orchestration scripts in place. I have hit an interesting problem with environment variables that I haven’t yet been able to solve. Essentially, I want to be able to access environment variables that are created as part of a shell/comand task. Ideally I would like to extract these variables from the shell task and populate facts with the values and/or pass the values to subsequent tasks. The issue is that I can only access the environment variables in that task (ie. subsequent tasks can’t ‘see’ them) so I need some way of exporting/importing them for other tasks.
The problem is displayed in the following playbook:
#1 what you set in the shell: task is not available to other tasks as
they each reconnect to the server and open a new ssh session, they
don't all execute in the same shell process.
#2 ansible_env is not reset every time you run a task, it reflects the
environment from when facts where gathered, it can even reflect a
differnt user when remote_user/become_user are set in different
places.
#3 to set the environment for task execution we have the 'environment'
directive, which can be set at play, block and task levels:
Thanks for the response, I acknowledge all of these points and accept that this is the situation.
In the example at point 3. the environment variable is provided to multiple shell tasks, but in this scenario the value of the environment variable being passed is known prior to execution.
Perhaps I should have better described my constraints, as the example of setting the environment variable in the shell using ‘export’ was only to to show I couldn’t access the value outside the shell.
In my example replace the ‘export ANIMAL=droppear’ to a binary called ‘blackbox’, this ‘blackbox’ binary generates results in the form of setting environment variables that I need to access, one of them named ‘ANIMAL’.