我正在嘗試在 Python 中創建一個字典,其值是一個串列。
對于每個實體,我獲取兩個標簽 (ms_type和name) 并形成一個串列并將該串列值附加到字典中的每個鍵。
我究竟做錯了什么 ?
空字典:
{"i-asdasdbuecebwad51": None,"i-0asdasda41bubwadd": None}
我得到的輸出:
{'i-asdasdbuecebwad51': None, 'i-0asdasda41bubwadd': None, 10: ['App1', 'service']}
期望的輸出:
{'i-asdasdbuecebwad51': ['App1', 'service'], 'i-0asdasda41bubwadd': ['App2', 'scheduler']}
代碼:
import boto3
instance_id = ["i-asdasdbuecebwad51","i-0asdasda41bubwadd"]
def get_inst_name(connection, instance_id):
print("We are in the get inst name function")
try:
empty_instance_dict = {k:None for k in instance_id}
print(f"Dictionary Initiated {empty_instance_dict}")
print("------\n")
for each in instance_id:
empty = []
for_response = (connection.describe_tags(
Filters=[
{
'Name': 'resource-id',
'Values': [each, ],
},
],
)
)
for each in range(0, len(for_response['Tags'])):
if for_response['Tags'][each]['Key'] == "ms_type":
microservice_types = for_response['Tags'][each]['Value']
break
for each in range(0, len(for_response['Tags'])):
if for_response['Tags'][each]['Key'] == "Name":
instance_name = for_response['Tags'][each]['Value']
break
empty.append(instance_name)
empty.append(ms_type)
empty_instance_dict[each] = empty
return empty_instance_dict
except Exception as e:
print(f"The instance {instance_id} doesn't have the tag called name")
return None
def lambda_handler(instance_id):
aws_region = "us-east-1"
print(type(instance_id))
print("Instance found are:")
print(instance_id)
ec2client = boto3.client('ec2', region_name = aws_region)
print("Fetching instance name:")
instance_name = get_inst_name(ec2client,instance_id)
###
print(type(instance_name))
print(instance_name)
lambda_handler(instance_id)
uj5u.com熱心網友回復:
我拿走了您的代碼并對其進行了一些清理:
import boto3
instance_id = ["i-asdasdbuecebwad51","i-0asdasda41bubwadd"]
result = {}
ec2_client = boto3.client('ec2')
response = ec2_client.describe_instances(InstanceIds=instance_list)
for reservation in response['Reservations']:
for instance in reservation['Instances']:
instance_id = instance['InstanceId']
tags = [tag['Value'] for tag in instance['Tags'] if tag['Key'] in ['ms_type', 'Name']]
result[instance_id] = tags
print(result)
uj5u.com熱心網友回復:
我沒有運行它的憑據,所以它未經測驗:
import boto3
client = boto3.client('ec2', region_name='us-east-1')
output = {}
for instance in ['i-asdasdbuecebwad51', 'i-0asdasda41bubwadd']:
filter_ = {'Name': 'resource-id', 'Values': [instance]}
for tag in client.describe_tags(Filters=[filter_])['Tags']:
if (key := tag[instance]['Key']) in ['ms_type', 'Name']:
output.setdefault(instance, []).append(key)
print(output)
uj5u.com熱心網友回復:
如果我是你,我會將字典值初始化為空串列,所以
empty_instance_dict = {k:[] for k in instance_id}
代替
empty_instance_dict = {k:None for k in instance_id}
然后做
empty_instance_dict[each].append(instance_name)
empty_instance_dict[each].append(ms_type)
當你需要
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/436672.html
標籤:Python python-3.x 列表 字典 aws-lambda
上一篇:從嵌套串列/元組創建多輸入字典
下一篇:回圈時如何從字典中彈出?
