How to set environmental variables using Ansible


I need to set the variables like JAVA_HOME and update PATH. There are a number of ways of doing this. One way is to update the /etc/environment variable and include a line for JAVA_HOME using the lineinfile module and then run the command source /etc/environment directly on the guest OS (CentOS in my case).

Another way is to execute the export command e.g.

Is there a cleaner way to do this as all these require manipulating files and running commands directly on the OS to update the environment variables?


Yes, there is a cleaner way. You can set environment variables per task:


If you set the environment variable like above in a task, it is only available for this specific task. In subsequent tasks it does not exist unless you define it again.

Though you can define env vars per play as well:

Now it’s gonna be available for all tasks of this play.

See Setting the Environment and FAQ: How can I set the PATH or any other environment variable for a task or entire playbook? in the docs.

Another example with a script task:

Where the script simply has this content:

Leave a Reply