We will be using User Data script to define our autorun script, which we intend to execute on every reboot or launch of our EC2 instance. I will be using this script to mount my elastic file system drive (EFS) and start to do application server configuration every time my server is rebooted and auto-scale using my autoscaling configuration.
Example of User Data script:
Content-Type: multipart/mixed; boundary="//"MIME-Version: 1.0--//Content-Type: text/cloud-config; charset="us-ascii"MIME-Version: 1.0Content-Transfer-Encoding: 7bitContent-Disposition: attachment; filename="cloud-config.txt"#cloud-configcloud_final_modules:- [scripts-user, always]--//Content-Type: text/x-shellscript; charset="us-ascii"MIME-Version: 1.0Content-Transfer-Encoding: 7bitContent-Disposition: attachment; filename="userdata.txt"!/bin/bash/bin/echo "Hello World" >> /home/ec2-user/logscript.txtyum update -y/bin/echo "Hello World -2" >> /home/ec2-user/logscript.txtmkdir /home/ec2-user/efs/bin/mount -t nfs4 -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport 172.31.XX.XXX:/ /home/ec2-user/efs/bin/echo "file server mounting completed, ready to start the server..." >> /home/ec2-user/logscript.txt/home/ec2-user/efs/Tomcat/bin/startup.sh/bin/echo "tomcat server started" >> /home/ec2-user/logscript.txt--//
** important notes:- here I have created a file called 'logscript.txt' on my ec2 instance, to log all output of the script. As you can see, I am defining my bash script in this user data script (in Red). You can replace the Red text with your custom script.
Defining User Data on EC2:
- Go to your EC2 panel
- Select the instance, Go to Action --> Instance Settings --> View/Change User Data
- You can modify User data only when your instance is in the "Stop" state. Before stopping make use follow the process as stop may change your public IP address.
- Put the following script, click Save
- Go to Instance State and 'Start'
You can verify the logscript.txt to check if your script executed or not.
Happy deploying!
Deepesh Rajpal | c: 98282.38079 | rajpal.deepesh@gmail.com


Comments