Depending on your system's config, when Ansible escalates its privileges via sudo, the environment will be 'sanitised' giving you a minimal set of env variables. Your /etc/sudoers
file likely has the setting env_reset
.
You have a few options.
In the sudoers files you could remove env_reset
or you could add env_keep MY_VAR
entries for each of the variables you wish to preserve.
Within Ansible you could explicitly set the environment variables you require. Doing that on a specific task looks like this:
- hosts: all
tasks:
- cmd: echo $MY_ENV
become: true
environment:
MY_ENV: "foo"
You can read more about setting the environment for Ansible in the Setting the Environment section of their docs.
Without knowing anything else of your needs, I would strongly recommend setting the variable within your Ansible code and leaving the sudoers file alone unless you genuinely need those values being kept in the env outside of Ansible's context. This helps avoid an inconsistent sudo environment for users.