Ansible: What to do when you must use ‘su’

Generally if a task in your playbook needed to perform privilege escalation your remote user would just use sudo to become a privileged user. But what if you needed to transact against a machine that does not have a remote user configured with sudo permissions? Use become_method: su instead.

Consider this example:

---
- name: This play escalates with su instead of sudo
  hosts: my_remote_host
  gather_facts: True
  become_user: root
  become_method: su
  tasks:
  - name: The name of my remote_user is returned
    ansible.builtin.debug:
      msg: "Hello {{ ansible_facts['user_id']}}"

  - name: Listing the contents of roots homedir is something only root can do
    become: True
    ansible.builtin.command: ls /root


To run this playbook from ansible-navigator I’m going to need to prompt for both the unprivileged remote user’s username (which is unpriv in this example) and for the become password. I’ll do this with the arguments --ask-pass whose shorthand is -k and --ask-become-pass whose shorthand is -K.

ansible-navigator run -u unpriv -kK

When the playbook runs, I’m prompted first for the user unpriv‘s ssh password, and then root‘s password to perform the privilege escalation using su.

Doing things this way isn’t exactly ideal, but it is one way to make configuration changes on a remote host when you don’t already have a remote user provisioned with sudo permissions.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.