Skip to content

Instantly share code, notes, and snippets.

@squamous
Last active April 17, 2017 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save squamous/99c0c5a1d85cf1522293974f0a40c446 to your computer and use it in GitHub Desktop.
Save squamous/99c0c5a1d85cf1522293974f0a40c446 to your computer and use it in GitHub Desktop.
Trick for getting remote user info in Ansible
---
# Ansible doesn't expose the shell environment of the remotely logged in user
# so we need to use a few tricks to get some of these values.
#
# This playbook demonstrates how to get a couple of useful environment variables.
#
# NOTE: these values are different to ansible_env.ansible_user_dir and
# ansible_env.ansible_user_shell which represent the user running ansible.
- hosts: all
vars:
app_user: foobar
tasks:
- name: Get the user's home directory
shell: >
egrep "^{{ app_user }}:" /etc/passwd | awk -F: '{ print $6 }'
changed_when: false
register: user_home
- name: Get the user's shell
shell: >
egrep "^{{ app_user }}:" /etc/passwd | awk -F: '{ print $7 }' | awk -F/ '{print $3}'
changed_when: false
register: user_shell
- debug: msg="info for user {{ app_user }} - HOME={{ user_home.stdout }}, SHELL={{ user_shell.stdout }}"
# To access the user's environment variables we invoke their shell in interactive mode which presumably
# will run load .profile and/or .login
- name: Get the user's language
command: "{{ user_shell.stdout }} -ic 'echo $LANG'"
changed_when: false
register: user_lang
- debug: msg="language for user {{ app_user }} is {{ user_lang.stdout }}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment