Reputation: 445
I have the below lambda function which stops all the Ec-2 instances with the AutoOff_uat tag. If I want to run this lambda across two regions us-east-1 and us-east-2. what modifications do i need to make
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:AutoOff_uat',
'Values': ['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]
#print the instances for logging purposes
#print RunningInstances
#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
else:
print "Nothing to see here"
Upvotes: 0
Views: 1115
Reputation: 3773
You can pass the region to the resource when you create it
ec2 = boto3.resource('ec2', region_name='us-east-2')
I would recommend wrapping all of your code in a function which takes the region as an argument and then iterate over a list of regions you want to operate on.
import boto3
import logging
#setup simple logging for INFO
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def shutdown_instances(region):
#define the connection
ec2 = boto3.resource('ec2', region=region)
# Use the filter() method of the instances collection to retrieve
# all running EC2 instances.
filters = [{
'Name': 'tag:AutoOff_uat',
'Values': ['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]
#print the instances for logging purposes
#print RunningInstances
#make sure there are actually instances to shut down.
def lambda_handler(event, context):
for region in ['us-east-1', 'us-east-2']:
shutdown_instances(region)
Upvotes: 1