Search code examples
ansiblesu

How to become a specific user in ansible


I am trying to run a command on a system with ansible as a specific user.

Its important that I run as that specific user because the config file the command needs to work is only available to that user. Any other user won't be able to read the config file and thus won't work.

I'm trying to use ansible's become_user, become and become_method to run the command but ansible seems to be ignoring it. Here's an example:

- shell: whoami
  register: c
- shell: whoami
  become: yes
  register: d
- shell: whoami
  become: yes
  become_user: myuser
  become_method: su
  register: e
- debug: var=c.stdout
- debug: var=d.stdout
- debug: var=e.stdout

And when I run the ansible script I get the following:

TASK [myscript : debug] *************************************************************************************************************************************************
ok: [10.33.56.93] => {
    "c.stdout": "root"
}

TASK [myscript : debug] *************************************************************************************************************************************************
ok: [10.33.56.93] => {
    "d.stdout": "root"
}

TASK [myscript : debug] *************************************************************************************************************************************************
ok: [10.33.56.93] => {
    "e.stdout": "root"
}

Am I misunderstanding how become_user works? Is there some other way for me to get my command to run as a specific user?

I am using ansible 2.9.18 if that should matter.

Thanks


Solution

  • become_user is the main piece that you need here.

    You are seeing root appear in the first task because you are running the playbook as root which is fine.

    The other two tasks are root because you are giving privilege escalation to each task which will override the become_user that you are setting. You can simply remove become: yes and switching the user should work.

    ---
    - hosts: localhost
      become: yes
      tasks:
    
        - shell: whoami
          register: c
    
        - shell: whoami
          become_user: myuser
          register: d
    
        - debug: var=c.stdout
    
        - debug: var=d.stdout