Reputation: 13
For test purpose i am having 3 instances , 2 have tag in them key:Backup Value:Testing and 1 is without this i want to get the instance name which is not having this particular tag. I am trying this logic that i am getting all the instance name and then finding which instances having this backup tag and then removing the 2nd list from 1st. i am able to get both the list but not able to filter out the 2nd list from the first.
Code:
import boto3
ec2 = boto3.client('ec2')
def lambda_handler(event, context):
response = ec2.describe_instances()
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
print(instance["InstanceId"])
tags_NV = ec2.describe_tags(
Filters = [
{
'Name':'resource-type',
'Values':['instance']
},
{
'Name':'key',
'Values':['Backup']
}
]
)
ami_backuppolicy = {i['ResourceId'] for i in tags_NV['Tags']}
print(ami_backuppolicy)
OUTPUT:
Function Logs:
START RequestId: c271c3b3-9c64-4d7b-829f-d34ffcb5e944 Version: $LATEST
i-05a448daa5823d6af
i-0f79ec69714932e8e
i-058bfa970112e8565
{'i-058bfa970112e8565', 'i-05a448daa5823d6af'}
END RequestId: c271c3b3-9c64-4d7b-829f-d34ffcb5e944
REPORT RequestId: c271c3b3-9c64-4d7b-829f-d34ffcb5e944 Duration: 480.40 ms Billed Duration: 500 ms Memory Size: 128 MB Max Memory Used: 73 MB Init Duration: 276.17 ms
Upvotes: 0
Views: 1692
Reputation: 270184
Here is an AWS Lambda function that will find any instances that do not have the given tag:
import boto3
def lambda_handler(event, context):
ec2_resource = boto3.resource('ec2')
not_backed_up = []
for instance in ec2_resource.instances.all():
if not [tag for tag in instance.tags if tag['Key'] == 'Backup' and tag['Value'] == 'Testing']:
not_backed_up.append(instance.id)
print(not_backed_up)
Upvotes: 1
Reputation: 13
CODE :
import boto3
def lambda_handler(event, context):
list=[]
ec2 = boto3.client('ec2')
ec2_resource = boto3.resource('ec2')
response = ec2.describe_instances()
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
list.append(instance["InstanceId"])
not_backed_up = []
list_difference = []
for instance in ec2_resource.instances.all():
if [tag for tag in instance.tags if tag['Key'] == 'Backup' and tag['Value'] == 'Testing']:
not_backed_up.append(instance.id)
print(list)
print(not_backed_up)
for item in list:
if item not in not_backed_up:
list_difference.append(item)
print(list_difference)
OUTPUT :
Function Logs: START RequestId: 73fcb1b0-5421-47dc-88f6-b82f581aa461 Version: $LATEST
['i-05a448daa5823d6af', 'i-0f79ec69714932e8e', 'i-058bfa970112e8565']
['i-05a448daa5823d6af', 'i-058bfa970112e8565']
['i-0f79ec69714932e8e']
The 3rd output is the instance not having the backup tag
Upvotes: 0