Aws Ec2 run script program at startup

31,185

Solution 1

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

Solution 2

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.

Solution 3

What is the OS of EC2 instance?

  1. You could use userdata script at instance launch time. Remember this is just 1time activity

  2. If your requirement is to start the script everytime you reboot EC2 instance then you could make use of rc.local file on Linux instances which is loaded at OS boot time.

Share:
31,185
andrea cenciarelli
Author by

andrea cenciarelli

Updated on September 06, 2020

Comments

  • andrea cenciarelli
    andrea cenciarelli over 3 years

    There is a method to setup an EC2 machine to execute Kafka starting script on startup? I use also java Aws SDK, so I accept both solution for a program java that run command on EC2 instance and solutions for a bash script mode that run kafka script at startup.

  • andrea cenciarelli
    andrea cenciarelli about 6 years
    I'm using Ubuntu server 16.04. I need to start Zookeeper and Kafka at launch of free tier EC2 istances.
  • user9575749
    user9575749 about 6 years
    Make use of user data script at instance launch time