Aws Ec2 run script program at startup

A script can be passed in the User Data property.

If you are using the Amazon Linux AMI, and the first line of the script begins with #!, then the script will be executed the first time that the instance is started.

For details, see: Running Commands on Your Linux Instance at Launch


Adding a script under User Data in CloudFormation only runs once, right when the instance is launched but not when the instance is restarted which is what I needed for my use case. I use the rc.local approach as commented above and here. The following in effect appends my script to the rc.local file and performs as expected:

Resources:
  VM:
    Type: 'AWS::EC2::Instance'
    Properties:
      [...]
      UserData:
        'Fn::Base64': !Sub |
          #!/bin/bash -x
          echo 'INSTANCEID="$(curl -s http://169.254.169.254/latest/meta-data/instance-id)"' >> /etc/rc.local
          #echo 'INSTANCEID=$(ls /var/lib/cloud/instances)' >> /etc/rc.local
          echo 'echo "aws ec2 stop-instances --instance-ids $INSTANCEID --region ${AWS::Region}" | at now + ${Lifetime} minutes' >> /etc/rc.local

Additional tip: You can inspect the user data (the current script) and modify it using the AWS console by following these instructions: View and update the instance user data.