Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aws Ec2 run script program at startup

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.

like image 867
andrea cenciarelli Avatar asked Apr 01 '18 03:04

andrea cenciarelli


2 Answers

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.

like image 56
K F Avatar answered Oct 20 '22 00:10

K F


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

like image 8
John Rotenstein Avatar answered Oct 20 '22 02:10

John Rotenstein