Skip to content

Instantly share code, notes, and snippets.

@kellyselden
Last active November 29, 2017 11:41
Show Gist options
  • Save kellyselden/240898e2fb70168feaf0 to your computer and use it in GitHub Desktop.
Save kellyselden/240898e2fb70168feaf0 to your computer and use it in GitHub Desktop.
Only run EC2 instances during work hours
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt123456789",
"Effect": "Allow",
"Action": [
"ec2:StartInstances",
"ec2:StopInstances",
"ec2:DescribeInstances"
],
"Resource": [
"*"
]
}
]
}
#!/bin/bash
cd /home/ec2-user
{
echo "export AWS_ACCESS_KEY=--access-key--";
echo "export AWS_SECRET_KEY=--secret-key--";
} >> .bashrc
{
echo "source ~/.bashrc";
echo "tag=\$1";
echo "shift";
echo "for region in \$@";
echo "do";
echo " instances=\$instances\$(ec2-describe-instances --region \$region --filter \"tag:SaveMoney=\$tag\" | grep -oP '^INSTANCE\t\i-\w+\t' | grep -oP 'i-\w+' | awk -vORS=\" \" '{print \$0}')";
echo "done";
echo "echo \$instances | sed 's/\s\$//' | tr -d '\n'";
} > get-instances.sh
{
echo "source ~/.bashrc";
echo "instances=\$(~/get-instances.sh \$@)";
echo "ec2-start-instances \$instances";
} > start-instances.sh
{
echo "source ~/.bashrc";
echo "instances=\$(~/get-instances.sh \$@)";
echo "ec2-stop-instances \$instances";
} > stop-instances.sh
chmod +x *.sh
{
echo "0 11 * * 1-5 ~/start-instances.sh YesPlease us-east-1";
echo "0 23 * * 1-5 ~/stop-instances.sh YesPlease us-east-1";
echo "0 23 * * 1-5 ~/stop-instances.sh MorePlease us-east-1";
echo "0 14 * * 1-5 ~/start-instances.sh YesPlease us-west-1 us-west-2";
echo "0 2 * * 1-5 ~/stop-instances.sh YesPlease us-west-1 us-west-2";
echo "0 2 * * 1-5 ~/stop-instances.sh MorePlease us-west-1 us-west-2";
} | crontab -u ec2-user -
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment