Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible doesn't load ~/.profile

Tags:

ansible

I'm asking myself why Ansible doesn't source ~/.profile file before execute template module on one host ?

Distant host ~/.profile:

export ENV_VAR=/usr/users/toto

A single Ansible task:

- template: src=file1.template dest={{ ansible_env.ENV_VAR }}/file1

Ansible fail with:

fatal: [distant-host] => One or more undefined variables: 'dict object' has no attribute 'ENV_VAR'
like image 675
pierrefevrier Avatar asked Mar 14 '16 13:03

pierrefevrier


People also ask

How do I check if Ansible is installed or not?

To check whether it is installed, run ansible-galaxy collection list. To install it, use: ansible-galaxy collection install ansible.posix. To use it in a playbook, specify: ansible.posix.profile_tasks. Ansible callback plugin for timing individual tasks and overall execution time.

How do I enable callbacks in Ansible?

Most callbacks shipped with Ansible are disabled by default and need to be enabled in your ansible.cfg file in order to function. For example: You can only have one plugin be the main manager of your console output.

Where is the Ansible playbook config file?

ansible 2.3.1.0 config file = /etc/ansible/ansible.cfg configured module search path = Default w/o overrides python version = 2.7.5 (default, Aug 2 2016, 04:20:16) [GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] When running ansible playbook for all servers (1964 servers) it hangs somewhere in middle of execution.

Why does Ansible hang on target host?

it doesn't matter if hang on target host is caused by fuse, nfs or anything, it's still Ansible bug in the way that 1 target host should not be able to lock up whole play for all other hosts.


1 Answers

Ansible is not running remote tasks (command, shell, ...) in an interactive nor login shell. It's same like when you execute command remotely via 'ssh user@host "which python"' To source ~/.bashrc won't work often because ansible shell is not interactive and ~/.bashrc implementation by default ignores non interactive shell (check its beginning).

The best solution for executing commands as user after its ssh interactive login I found is:

- hosts: all
  tasks:
    - name: source user profile file
      #become: yes
      #become_user: my_user  # in case you want to become different user (make sure acl package is installed)
      shell: bash -ilc 'which python' # example command which prints
      register: which_python
    - debug:
      var: which_python

bash: '-i' means interactive shell, so .bashrc won't be ignored '-l' means login shell which sources full user profile (/etc/profile and ~/.bash_profile, or ~/.profile - see bash manual page for more details)

Explanation of my example: my ~/.bashrc sets specific python from anaconda installed under that user.

like image 177
Juraj Michalak Avatar answered Sep 29 '22 05:09

Juraj Michalak