Skip to content

Instantly share code, notes, and snippets.

@kixorz
Created March 20, 2013 22:41
Show Gist options
  • Star 42 You must be signed in to star a gist
  • Fork 18 You must be signed in to fork a gist
  • Save kixorz/5209217 to your computer and use it in GitHub Desktop.
Save kixorz/5209217 to your computer and use it in GitHub Desktop.
Running cron jobs in AWS Auto Scaling group is tricky. When you deploy the same code and configuration to all instances in the group, cron job would run on all of them. You may not want that. This script detects the first instance in the group and allows only this instance to run the job. IAM user used by this script needs to have permissions to…
#!/usr/bin/env ruby
require 'syslog'
require 'net/http'
require 'aws-sdk'
Syslog.open
AWS.config({
:access_key_id => '<iam user key>',
:secret_access_key => '<iam user secret>'
})
metadata_endpoint = 'http://169.254.169.254/latest/meta-data/'
instance_id = Net::HTTP.get( URI.parse( metadata_endpoint + 'instance-id' ) )
auto_scaling = AWS::AutoScaling.new
auto_scaling.groups.each { |group|
instance = group.ec2_instances.filter('instance-state-name', 'running').first
if( instance.instance_id == instance_id )
command = ARGV * ' '
Syslog.alert( 'running cron on ' + instance_id + ': ' + command )
`#{command}`
end
}
#!/bin/bash
source "/usr/local/rvm/scripts/rvm"
cd "$(dirname "$0")"
./aws_autoscaling_cron.rb "$@"
{
"Statement": [
{
"Action": [
"autoscaling:DescribeAutoScalingGroups",
"autoscaling:DescribeAutoScalingInstances",
"ec2:DescribeInstanceAttribute",
"ec2:DescribeInstanceStatus",
"ec2:DescribeInstances"
],
"Effect": "Allow",
"Resource": [
"*"
]
}
]
}
#run a command every day at midnight
0 0 * * * ubuntu /aws_autoscaling_cron.sh <command> <parameters> > /dev/null 2> /dev/null
@timbuckingham
Copy link

Thanks @leytonreed -- for anyone else who ran into an issue with the bash script, your auto scaling group name may have spaces in it. You'll want to wrap $MY_ASG in quotes:

FIRST_ID=$(aws autoscaling describe-auto-scaling-groups --region $MY_REGION --auto-scaling-group-name "${MY_ASG}" --query "AutoScalingGroups[].Instances[0].InstanceId" --output text)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment