Edit Apparently, the problem was that I should have done
su - postgres -c "commands, commands, commands"
,
that is, passed any commands to su
, rather than attempting to list them below su
, because those commands (below su
) aren't affected by su
. /Edit
Edit 2: See David Braun's answer for an even better solution: https://stackoverflow.com/a/22947716/694469
Can I not switch user (su - postgres
) in a Vagrant bootstrap shell provisioning script? (Why not?)
I'm writing such a script. In that script, I do:
echo '===== Creating PostgreSQL databases and users'
su - postgres
psql -c "
create user SomeUserName password '...';
alter user ...;
"
Here, psql
should attempt to login as user postgres
. What happens, however, is that su - postgres
apparently fails, and the shell attempts to login as user root. (Apparently, root is the user that runs the Vagrant bootstrap shell script.)
So this error appears and the psql commands aren't invoked:
psql: FATAL: role "root" does not exist
Replacing su - postgres
with sudo su - postgres
has no effect (I think the script is already run as root.)
I added id
(which prints the current user ID) before and after su - postgres
, and id
prints uid=0(root) gid=0(root) groups=0(root)
both before and after su
was called. So as far as I can tell, su - postgres
is kind of ignored? And a certain exit
, later on when I attempt to switch back to the root user, exits the bootstrap script completely :-(
However. After doing vagrant ssh
, I'm able to sudo su - postgres
just fine, and then start psql
. But not from within the provisioning script.
(A workaround is to specify -h 127.0.0.1 --username postgres
when I call psql
(instead of switching user to postgres). And also enable PostgreSQL trust based authentication for VM local connections.)