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.
To tell
sudoto keep the environment, you can use--preserve-envto keep all the variables or--preserve-env=ENV_VAR1to keep only the required ones.P.S. There is much more on privilege escalation that just
become: trueso you might find a way to use it. Also, you're usingshellinstead ofcommandwhich could also affect the behavior of your script. This answer has more details on that with links to the documentation.