Environment variables seen with gather_facts but not seen in playbooks

Hello,

I have a script file with 40-50 variables (some are something like this: ENV=hostname | awk -F- '{print $1}' | sed 's/ACE//') and I deploy this file to all my machines in /etc/profile.d/some_script.sh

I created a new user with which I only run deployments with ansible and have modified the /etc/sudoers file like this:

Defaults !env_reset #notice the “!” this does not allow sudo to reset the env. This way when I run something with sudo I don’t lose environment variables
ansible ALL=(ALL) NOPASSWD: ALL

Something goes wrong with the command below I can see the env variables
[ansible@ACEPR-ANSIREBOND-01 ansible]$ ansible ACEPP-LM-01 -m setup | grep ENV
“ENV”: “PP”,
“ENV_PROP”: “preprod”,
“ENV_PROP_PREFIX”: “preprod”,

But when I run this playbook:

  • name: prereq
    hosts: ACEPP-LM-01
    remote_user: ansible
    sudo: True
    tasks:
  • shell: echo {{ ansible_env.ENV }}

It gives error: fatal: [ACEPP-LM-01] => One or more undefined variables: ‘dict’ object has no attribute ‘ENV’
Why is ansible seeing the env variables (gathering_facts is ok) but it can’t resolve {{ ansible_env.ENV }}

[ansible@ACEPP-LM-01 ~]$ sudo echo $ENV
PP
[ansible@ACEPP-LM-01 ~]$ env | grep ENV
ENV=PP
ENV_PROP=preprod
ENV_PROP_PREFIX=preprod

With root and no sudo everything is ok. Is it the sudo ?

I have modified ~/.bashrc for root and ansible user to include : alias sudo=“sudo -i” and also modified ansible.cfg : executable = /bin/bash

[ansible@ACEPP-LM-01 ~]$ sudo env | grep ENV
ENV=PP
ENV_PROP=preprod
ENV_PROP_PREFIX=preprod
[ansible@ACEPP-LM-01 ~]$ sudo env | grep SUDO
SUDO_USER=ansible
SUDO_UID=30001
SUDO_COMMAND=/bin/bash -c env
SUDO_GID=30001
[ansible@ACEPP-LM-01 ~]$ env | grep ENV
ENV=PP
ENV_PROP=preprod
ENV_PROP_PREFIX=preprod

and when I run a “shell: echo $ENV && env && whoami && cat ~/.bashrc”
I get this:

stdout:

TERM=xterm
SHELL=/bin/bash
USER=root
SUDO_USER=ansible
SUDO_UID=30001
USERNAME=root
MAIL=/var/mail/ansible
PATH=/usr/bin:/bin
PWD=/users/ansible
LANG=C
HOME=/root
SUDO_COMMAND=/bin/bash -c echo SUDO-SUCCESS-gkqnfqfgysvzciwpzfzhjksuidabfmha; LANG=C LC_CTYPE=C /usr/bin/python /users/ansible/.ansible/tmp/ansible-tmp-1432099297.2-178454781677599/command; rm -rf /users/ansible/.ansible/tmp/ansible-tmp-1432099297.2-178454781677599/ >/dev/null 2>&1
SHLVL=2
LOGNAME=root
LC_CTYPE=C
SUDO_GID=30001
_=/usr/bin/env
root
[output omitted]

alias sudo=“sudo -i”

So sudo uses now /bin/bash but it ignors ~/.bashrc alias. Why ? What am I missing ?

in your ansible.cfg have you set tried setting “sudo_flags=-H -i” ? this would make the sudo invoke a login shell

  • Benno

@benno joy
I didn’t have that set ! It’s working ! Thanks a lot ! Put up a paypal/donate - i’ll send you a beer! :slight_smile: