How can I filter AWS instances using Tag and Value using boto3
?
import boto3
ec2 = boto3.resource('ec2')
client = boto3.client('ec2')
response = client.describe_tags(
Filters=[{'Key': 'Owner', 'Value': '[email protected]'}])
print(response)
You are using a wrong API. Use describe_instances
import boto3
client = boto3.client('ec2')
custom_filter = [{
'Name':'tag:Owner',
'Values': ['[email protected]']}]
response = client.describe_instances(Filters=custom_filter)
Instance with tags and instances without tags can be retrieved as below Can get all tags as below
import boto3
ec2 = boto3.resource('ec2',"us-west-1")
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
for instance in instances:
if instance.tags != None:
for tags in instance.tags:
if tags["Key"] == 'Name' or tags["Key"] == 'Owner':
if tags["Key"] == 'Name':
instancename = tags["Value"]
if tags["Key"] == 'Owner':
owner = tags["Value"]
else:
instancename='-'
print("Inastance Name - %s, Instance Id - %s, Owner - %s " %(instancename,instance.id,owner))
Stop instances that are running and have no tags
import boto3
ec2 = boto3.resource('ec2',"ap-south-1")
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
for instance in instances:
#print(instance.tags)
if instance.tags == None:
print(instance.id)
instance.stop()
else:
pass
stop all running instances with a specific tag like tag key ='env'
import boto3
ec2 = boto3.resource('ec2',"ap-south-1")
# filter all running instances
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
# Decleared list to store running instances
all_running_instances = []
specific_tag = 'env'
for instance in instances:
# store all running instances
all_running_instances.append(instance)
# Instances with specific tags
if instance.tags != None:
for tags in instance.tags:
# Instances with tag 'env'
if tags["Key"] == specific_tag:
# Remove instances with specefic tags from all running instances
all_running_instances.remove(instance)
#print(all_running_instances)
for specific in all_running_instances:
print(specific)
specific.stop()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With