Basically you need to run tasks for postgres
user in root block. Example as below:
pb.yml
- hosts: testingserver
gather_facts: false
tasks:
- name: this is me without become
command: whoami
- name: this is my sudo `root` block
become: true
block:
- name: checking who I am
command: whoami
- name: this is me becoming `postgres`
become_user: postgres
command: whoami
output:
$ ANSIBLE_CONFIG=ansible.cfg ansible-playbook -i inven pb.yml -K -v
BECOME password:
PLAY [testingserver] ***********************************************************************************************************************************************************************************************
TASK [this is me without become] ***********************************************************************************************************************************************************************************
changed: [testingserver] => {"ansible_facts": {"discovered_interpreter_python": "/usr/libexec/platform-python"}, "changed": true, "cmd": ["whoami"], "delta": "0:00:00.006233", "end": "2023-07-05 11:01:57.229844", "msg": "", "rc": 0, "start": "2023-07-05 11:01:57.223611", "stderr": "", "stderr_lines": [], "stdout": "testinguser", "stdout_lines": ["testinguser"]}
TASK [checking who I am] *******************************************************************************************************************************************************************************************
changed: [testingserver] => {"changed": true, "cmd": ["whoami"], "delta": "0:00:00.006191", "end": "2023-07-05 11:01:57.964360", "msg": "", "rc": 0, "start": "2023-07-05 11:01:57.958169", "stderr": "", "stderr_lines": [], "stdout": "root", "stdout_lines": ["root"]}
TASK [this is me becoming `postgres`] *************************************************************************************************************************************************************************
changed: [testingserver] => {"changed": true, "cmd": ["whoami"], "delta": "0:00:00.003580", "end": "2023-07-05 11:01:58.768622", "msg": "", "rc": 0, "start": "2023-07-05 11:01:58.765042", "stderr": "", "stderr_lines": [], "stdout": "postgres", "stdout_lines": ["postgres"]}
PLAY RECAP *********************************************************************************************************************************************************************************************************
testingserver : ok=3 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
This is my linux box environment as per your case:
- normal user is testinguser
- normal user su to postgres require password
- normal user sudo to root
- root su to postgres
$ ssh testingserver
[testinguser@testingserver ~]$ su - postgres
Password:
[testinguser@testingserver ~]$ sudo -i
[sudo] password for testinguser:
[root@testingserver ~]# su - postgres
[postgres@testingserver ~]$ whoami
postgres