1

I regularly need to drop a postres database and recreate it. It has to be done as postgres user as following:

$ sudo -u postres dropdb my_database

I thought of adding sudoers rules for not being asked a password. Usually I proceed by creating a file in /etc/sudoers.d/ with a rule like this one:

Cmnd_Alias DROP_DB = /bin/bash -l -c dropdb*, /usr/bin/dropdb*
emilio ALL = NOPASSWD: DROP_DB

But in this use case, I need to run the command as postgres user and it doesn't work.

What is the proper way to run a command as a different user without being asked a password?

EDIT: This might be a duplicate but it brings a different solution using visudo which is interesting.

2
1

Wrap dropdb and createdb in a bash script like /usr/bin/recreatedb.sh:

#!/bin/bash

sudo -u postgres dropdb $2
sudo -u postgres createdb -O $1 $2

Then create a special sudoers rule using visudo:

$ sudo visudo -f /etc/sudoers.d/postgresql

With this rule:

Cmnd_Alias RECREATE_DB = /bin/bash -l -c recreatedb*, /usr/bin/recreatedb*
username ALL = NOPASSWD: RECREATE_DB

Not the answer you're looking for? Browse other questions tagged or ask your own question.