Friday, August 9, 2019

Ansible - accessing .bashrc changes in subsequent task

My project uses ansible for local development setup, and I've found several examples where I needed to make updates to the .bashrc file:  updating the $PATH environment variable and creating a new environment variable for the VM's bridged IP address.  Accessing the changes in ~/.bashrc works fine when you logout and login again (or source it in the current shell) for anything done after the ansible playbook is run.  But, there's been a nuance I've encountered several times the past couple of months that I am sharing here to more easily remember the reasoning the next time it happens!

CentOS Linux release 7.3.1611 (Core)
ansible 2.8.2

After making updates to the ~/.bashrc file with an ansible task, the updates to the ~/.bashrc file is NOT available by default when performing the next ansible task.

For example, I needed to make updates to the ~/.bashrc file to update the $PATH environment variable to include another location where the yarn dependency was installed.  Another, I needed to export a new environment variable to more easily access the VM's bridged IP address.

To allow this to work as the intended user (vs root) I needed to switch user with su, but I also needed to have the command run inside a new login shell with an environment similar to a real login (the -l option for su).  Otherwise it wouldn't re-run the .bashrc file to get access to the just made changes in the ansible task that had just occurred.

NOTE:  {{user}} and {{project_path}} is set up in ansible's group_vars inventory.

- block:
  - name: export bridged ip address in .bashrc
      dest: '/home/{{user}}/.bashrc'
      block: |
       export BRIDGED_IP_ADDRESS=$(hostname -I | awk '{print $1}')
      marker: '# {mark} ANSIBLE MANAGED BLOCK - export BRIDGED_IP_ADDRESS'
      owner: '{{user}}'
      group: 'wheel'
      create: yes
  - name: command that needs access to $BRIDGED_IP_ADDRESS
    command: '<command>'
      chdir: '{{project_path}}'
    # The -l indicates to start shell as login shell with an environment similar to a real login
    become_method: su
    become_user: '{{user}}'
    become_flags: '-l'

This article helped a lot.

No comments:

Post a Comment

I appreciate your time in leaving a comment!