Skip to content

Instantly share code, notes, and snippets.

@martinrusev
Forked from smiller171/shutdown.py
Last active September 29, 2019 06:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save martinrusev/aec95b02756d70216f9d48919820af19 to your computer and use it in GitHub Desktop.
Save martinrusev/aec95b02756d70216f9d48919820af19 to your computer and use it in GitHub Desktop.
Nightly EC2 shutdown
import boto3
import logging
#setup simple logging for INFO
logger = logging.getLogger()
logger.setLevel(logging.INFO)
#define the connection
ec2 = boto3.resource('ec2')
def lambda_handler(event, context):
# Use the filter() method of the instances collection to retrieve
# all running EC2 instances.
filters = [{
'Name': 'tag:PowerSave',
'Values': ['nightly','Nightly','true','True']
},
{
'Name': 'instance-state-name',
'Values': ['running']
}
]
#filter the instances
instances = ec2.instances.filter(Filters=filters)
#locate all running instances
RunningInstances = [instance.id for instance in instances]
#make sure there are actually instances to shut down.
if len(RunningInstances) > 0:
#perform the shutdown
shuttingDown = ec2.instances.filter(InstanceIds=RunningInstances).stop()
print(shuttingDown)
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1444812758000",
"Effect": "Allow",
"Action": [
"ec2:DescribeInstanceStatus",
"ec2:DescribeInstances",
"ec2:StartInstances",
"ec2:StopInstances"
],
"Resource": [
"*"
]
},
{
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Effect": "Allow",
"Resource": "arn:aws:logs:*:*:*"
}
]
}
import boto3
import logging
#setup simple logging for INFO
logger = logging.getLogger()
logger.setLevel(logging.INFO)
#define the connection
ec2 = boto3.resource('ec2')
def lambda_handler(event, context):
# Use the filter() method of the instances collection to retrieve
# all running EC2 instances.
filters = [{
'Name': 'tag:PowerSave',
'Values': ['nightly','Nightly','true','True']
},
{
'Name': 'instance-state-name',
'Values': ['stopped']
}
]
#filter the instances
instances = ec2.instances.filter(Filters=filters)
#locate all stopped instances
StoppedInstances = [instance.id for instance in instances]
#make sure there are actually instances to shut down.
if len(StoppedInstances) > 0:
startingUp = ec2.instances.filter(InstanceIds=StoppedInstances).start()
print(startingUp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment