Linux has a convenient feature of running cronjob which will get executed at the correct time. In AWS we have a great feature of scaling out multiple instances based on traffic.
There are some requirements where the admin has to write a cron job which will be saved in the AWS AMI and provisioned in Autoscalling. As the multiple instances will be running a cron job, The single cron job will get executed parallelly in all the instances in ASG(Autoscaling group). This will get conflicted if we want to run the cron job only once.
The script which is provided below will handle the situation in Auto scaling and get only one cron job trigger even if multiple instances are running in AWS ASG.
Running crontab on AWS auto scaling group:
Step 1:
Log in to the instance where you are preparing the Golden Image. If you wonder what the golden image is. It simply means the customized AMI for our application.
Step 2:
vi /opt/asg-cron-script.sh
save the bash script in any location or with any file name as per your requirement.
#!/bin/bash
# Collect some information about the instance
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
INSTANCE_REGION=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone | sed 's/.$//')
INSTANCE_ASG=$(aws autoscaling describe-auto-scaling-instances --region $INSTANCE_REGION --instance-ids $INSTANCE_ID --query "AutoScalingInstances[].AutoScalingGroupName" --output text)
# Query the ASG
FIRST_INSTANCE_ID=$(aws autoscaling describe-auto-scaling-groups --region $INSTANCE_REGION --auto-scaling-group-name $INSTANCE_ASG --query "AutoScalingGroups[].Instances[0].InstanceId" --output text)
if [ "$FIRST_INSTANCE_ID" == "$INSTANCE_ID" ]; then
exit 0 #WRITE YOUR SCRIPT HERE BY REPLACING exit 0
else
exit 1
fi
To save the file press Esc + wq!
Step 3:
To call the above script we have to edit the crontab. Enter the below command
crontab -e
Edit the file by adding the below line
* * * * * /bin/bash /opt/asg-cron-script.sh
Step 4:
Go to the AWS console -> IAM services -> Policies -> Create new policy
Add the below json file
{
"Statement": [
{
"Action": [
"autoscaling:DescribeAutoScalingGroups",
"autoscaling:DescribeAutoScalingInstances",
"ec2:DescribeInstanceAttribute",
"ec2:DescribeInstanceStatus",
"ec2:DescribeInstances"
],
"Effect": "Allow",
"Resource": [
"*"
]
}
]
}
Step 5:
Create a role
AWS console -> IAM services -> Roles -> Create new Role
Step 6:
Attach policy to the new role created and attach the role to the ASG instances/Launch configuration (“IAM Instance Profile” within the Launch Configuration)
—-Tada—-
Mission Completed