Accessing environment variables created inside shell task

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:

A few misconceptions here:

#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:

  - hosts: all
    environment:
         ANIMAL: dropbear
    tasks:
         - shell: env |grep ANIMAL
             register: output
         - debug: var=output

Brian,

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’.

ie.

use shell to get the var, register the output, use that output to set
environment: directive for the rest of the play.

To add to that, I understand I can use something similar to the following to access a single value:

Custom module for gathering facts for the rescue!
http://docs.ansible.com/ansible/developing_modules.html#module-provided-facts
http://blog.toast38coza.me/custom-ansible-module-hello-world/
http://mcsrainbow.github.io/articles/create-an-ansible-module-and-then-use-module-provided-facts.html

  1. január 29., péntek 18:30:13 UTC+1 időpontban PixelDrift.NET Sam a következőt írta: