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