Switch SSH username in Ansible playbook

Posted on

I have an Ansible playbook where I start out using the root user but, after the initial tasks are done, I want to switch to an admin user, which will continue with the rest of the tasks.

I tried to use set_fact to change the remote_user variable but didn't get that to work, I think it's because the variable is immutable? There's also an update_fact module which might work, but I haven't tried it (since I found it while writing this post).

The solution I found looks like this:

---
- name: My playbook
  hosts: all
  gather_facts: false
  become: true

  tasks:
    - name: Stage 1
      block:
        - name: Do a thing
          ...

        - name: Do another thing
          ...

        - name: Generate password for user 'admin'
          ansible.builtin.set_fact:
            admin_password: "{{
                lookup(
                    'ansible.builtin.password',
                    'creds_admin.txt',
                    chars=['ascii_letters', 'digits'],
                    length=16
                )
                }}"

        - name: Create user 'admin'
          ansible.builtin.user:
            name: admin
            state: present
            password: "{{ admin_password | trim | password_hash('sha512') }}"
      become_method: su
      remote_user: root

    - name: Stage 2
      block:
        - name: Set the `sudo` password
          ansible.builtin.set_fact:
            ansible_become_password: "{{ admin_password }}"

        - name: Reboot the server
          ansible.builtin.reboot:
            msg: "Reboot after initial config"

        - name: Do more things
          ...
      become_method: sudo
      remote_user: admin

It sets two blocks, and each block has different settings for how to handle privileged actions.