Ansible become root and run other commands

Hi guys, I have a problem with running commands on the remote host with the root account. The manual procedure involves logging in to the server with the user ‘user1’ after which I have to run the command ‘sudo su -’ (without password and without other parameters) to become ‘root’ and execute other commands (e.g. chown userx:userx /path/file). Is there any ‘good soul’ who can share a playbook to achieve this result? Thank you for your support

“Become” is the magic keyword here, here are the docs:
https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_privilege_escalation.html

Within playbooks, you can set become: true on play or task level and such tasks will run with sudo by default.

For example, there’s file module that allows to modify file permissions.

- hosts: targethost
  become: true
  tasks:
    - name: Change file ownership, group and permissions
      ansible.builtin.file:
        path: /etc/foo.conf
        owner: foo
        group: foo
        mode: '0644'

If theres no suitable module for your needs, you can use command or shell module to execute arbitrary commands on the target.

2 Likes

couldnt have answered it better myself. you can specify a become user too if you need to

1 Like