Unable to filter the instance by tags and get the list of instances.Please help how can i proceed further.
import boto3
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':'OS_Name', 'Values':['Rstudio']}]
#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")
you need to specify the type of filter so in this case it would be tag.
filters = [{'Name':'tag:OS_Name', 'Values':['Rstudio']}]
from boto3 docs
tag : - The key/value combination of a tag assigned to the resource. Use the tag key in the filter name and the tag value as the filter value. For example, to find all resources that have a tag with the key Owner and the value TeamA , specify tag:Owner for the filter name and TeamA for the filter value.