You can use any of the two solutions provided below to solve the above issue.
1. Using PAM Authentication Module
PAM (Pluggable authentication modules) are at the core of user authentication on modern Linux operating systems. To allow users in a specific group to switch to another user account without a password, we can modify the default PAM settings for the su command in the /etc/pam.d/su file.
# vim /etc/pam.d/su
OR
$ sudo vim /etc/pam.d/su
Add the following configurations after “auth sufficient pam_rootok.so” as shown in the following screenshot.
auth [success=ignore default=1] pam_succeed_if.so user = postgres
auth sufficient pam_succeed_if.so use_uid user ingroup postgres
In the above configuration, the first line checks if the target user is postgres, if it is, the service checks the current user, otherwise, the default=1 line is skipped and the normal authentication steps are executed.
auth [success=ignore default=1] pam_succeed_if.so user = postgres
The line that follows checks if the current user is in the group postgres, if yes, the authentication process is considered successful and returns sufficient as a result. Otherwise, the normal authentication steps are executed.
auth sufficient pam_succeed_if.so use_uid user ingroup postgres
Save the file and close it.
Next, add the user (for example jarvis) that you want to su to the account postgres without a password to the group postgres using usermod command.
$sudo usermod -aG postgres jarvis
Now try to su to the postgres account as the user jarvis, you should not be prompted for a password as shown in the following screenshot:
$ su - postgres
2. Using Sudoers File
You can also su to another user without requiring a password by making some changes in the sudoers file. In this case, the user (for example jarvis) who will switch to another user account (for example postgres) should be in the sudoers file or in the sudo group to be able to invoke the sudo command.
$ sudo visudo
Then add the following configuration below the line “%sudo ALL=(ALL:ALL) ALL” as shown in the following screenshot.
jarvis ALL=NOPASSWD: /bin/su – postgres
Save and close the file.
Now try to su to the account postgres as the user jarvis, the shell should not prompt you to enter a password:
$ sudo su - postgres