Skip to content

Instantly share code, notes, and snippets.

@rubot
Forked from fia5000/remote-user-info.yml
Created January 10, 2020 14:43
Show Gist options
  • Save rubot/27633689d852d933ed89cebd138373f8 to your computer and use it in GitHub Desktop.
Save rubot/27633689d852d933ed89cebd138373f8 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