出于测试目的,我有3个实例,其中2个具有key:Backup Value:Testing标记,而1个没有此标记,我想获取没有此特定标记的实例名称。我正在尝试获取所有实例名称的逻辑,然后查找具有此备份标签的实例,然后从第一个列表中删除第二个列表。我可以同时获得两个列表,但不能从第一个列表中筛选出第二个列表。
代码:
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)
输出:
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
答案 0 :(得分:1)
这是一个AWS Lambda函数,它将查找没有给定标签的任何实例:
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)
答案 1 :(得分:0)
代码:
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)
输出:
功能日志: START RequestId:73fcb1b0-5421-47dc-88f6-b82f581aa461版本:$ LATEST
['i-05a448daa5823d6af','i-0f79ec69714932e8e','i-058bfa970112e8565']
['i-05a448daa5823d6af','i-058bfa970112e8565']
['i-0f79ec69714932e8e']
第三个输出是没有备份标记的实例