Issue
I am facing issues in exporting environment variables as part of the following Ansible task -
- name: Run custom shell script
shell: "sudo bash custom_script.sh"
register: output
environment:
ENV_VAR1: "secret-key"
During execution, the process is not able to find the ENV_VAR1
.
Another way is to explicitly export the variable in the shell command, something like -
- name: Run custom shell script
shell: "sudo su -c 'export ENV_VAR1=\"secret-key\"; bash custom_script.sh'"
register: output
But, I not comfortable with this approach, and would like to make use of the environment
functionality provided by Ansible.
Note: Please note, I will not be able to use become: true
as well, and have to run the shell command through sudo
.
Any help is appreciated. Thanks in advance.
Solution
To tell sudo
to keep the environment, you can use --preserve-env
to keep all the variables or --preserve-env=ENV_VAR1
to keep only the required ones.
P.S. There is much more on privilege escalation that just become: true
so you might find a way to use it. Also, you're using shell
instead of command
which could also affect the behavior of your script. This answer has more details on that with links to the documentation.
Answered By - Alexander Pletnev Answer Checked By - David Marino (WPSolving Volunteer)