title: How to run script on AWS Cloud Formation startup as a different user?
body: <p>I am having a lot of trouble launching an AWS Ubuntu instance (from a Cloud Formation template) and successfully running a script on startup. This script does run, but I do not want it running as root. I want the script to either be invoked as a different user or when the script runs for the script to change user. </p>
  
  <p>Since we are attempting to use Cloud Formation, I need to put the script or a reference to the script in my Template file.  The relevant part of my template file is below. The script 'myScript.sh' does run, but always as root. </p>
  
  <pre><code>"MyImage" : {
          "Type" : "AWS::EC2::Instance",
          "Properties" : {
             "ImageId" : "xxxxxx",
             "KeyName" : "xxxxxx",
             "SecurityGroups" : [ "xxxxxx" ],
             "UserData" : {"Fn::Base64" : {"Fn::Join" : ["", [
              "#include\n",
              "https://s3-eu-west-1.amazonaws.com/aFolder/myScript.sh \n"
              ] ] } }
          }
        }
      },
  </code></pre>
  
  <p>From the URL: <a href="http://alestic.com/2009/06/ec2-user-data-scripts" rel="noreferrer">http://alestic.com/2009/06/ec2-user-data-scripts</a> it states that these scripts always run as root. So instead I decided to modify the script to change the user. Below is an example script that does not do what I want. I've commented it inline to explain what each stage does:</p>
  
  <pre><code>#!/bin/bash
  
  whoami &gt; /home/ubuntu/who1.txt    # Always returns 'root'
  su ubuntu                         # Appears to have no effect. Ubuntu user does exist
  whoami &gt; /home/ubuntu/who2.txt    # Always returns 'root'
  
  su ubuntu echo fish &gt; /home/ubuntu/aFile.txt  # File is not created
  
  sudo -u ubuntu bash               # Appears to have no effect
  whoami &gt; /home/ubuntu/who3.txt    # Always returns 'root'
  </code></pre>
  
  <p>I'm guessing that there's something fundamentally wrong with my script, but I just can't see it! has anyone got any experience with AWS and Cloud Formation and have you succeeded in running a script not as root? I really don't want the script running as root since the activities that are going to be started should not be owned at the root level.</p>
  
  <p>Thanks,
  Phil</p>