Ansible: How to inherit between commands in a with_items loop

I am creating a playbook that requires sending multiple commands. It looks like one reasonable way to do this is to use a with_items loop. Is this correct? If so, the commands are all needed by the final command, but the commands do not seem to inherit what is set before them, such as exports or changing directories. For example, I want to run the following:

Two things. Ansible has a dedicated way of setting up the environment: http://docs.ansible.com/ansible/latest/playbooks_environment.html. Use that instead of manually sourcing vars and exporting them.
If you need them to come from that testvars.sh file then you should add a separate step to parse that and make it available to the shell task in your playbook (using set_fact).
That has the advantage of being able to run the commands both manually on the host and with ansible and still have a single place to store the vars. I guess this can be handy when the file originates from some vendor package and can slightly vary with different version (I’m thinking about java apps for instance).

Other thing is the cd step and subsequently doing ./test1. You should use ‘chdir’ as an argument to the shell module and just run ‘test1’. See http://docs.ansible.com/ansible/latest/shell_module.html#examples.

To summarize you do not need with_items.
Just one shell task, with the properly populated environment, and the ‘chdir’ argument.
And optionally add a prior step to establish the list of env vars.

Dick

Thanks for the detailed explanation and the links, they were helpful!

You are right that the source file I need to call will change with different versions and its pretty involved with a lot of parsing and environment checks that determine what variables to set depending on the platform the script is run from. It would require more than just parsing the file and I would end up having to duplicating the scripting in the file which seems like overkill. Given that, I think i can use a compromise based on some of the links you sent. Here is what I ended up with, that seems to be working for me.