如何在AWS Lambda中读取CSV并转为字典列表用于EC2打标签
解决AWS Lambda读取S3 CSV生成EC2标签格式问题
核心解决方案
csv.DictReader返回的OrderedDict可直接通过dict()转换为标准字典,再根据CSV结构调整成EC2 create_tags要求的格式即可。
完整代码示例
假设你的S3中CSV文件表头为Key和Value(正好匹配EC2标签格式),Lambda代码可以这样写:
import boto3 import csv s3_client = boto3.client('s3') ec2_client = boto3.client('ec2') def lambda_handler(event, context): # 从事件中获取切换到running状态的EC2实例ID target_instance_id = event['detail']['instance-id'] # 读取S3中的CSV文件 bucket_name = 'your-s3-bucket-name' csv_file_key = 'path/to/your/tags.csv' s3_response = s3_client.get_object(Bucket=bucket_name, Key=csv_file_key) csv_content = s3_response['Body'].read().decode('utf-8').splitlines() # 解析CSV并转换为标准字典列表 csv_reader = csv.DictReader(csv_content) # 将OrderedDict转为普通字典,直接生成符合要求的Tags列表 ec2_tags = [dict(tag_row) for tag_row in csv_reader] # 为实例打标签 ec2_client.create_tags( Resources=[target_instance_id], Tags=ec2_tags ) return { 'statusCode': 200, 'body': f"Successfully applied tags to instance {target_instance_id}" }
适配非标准CSV表头
如果你的CSV表头不是Key/Value(比如是TagKey/TagValue),只需手动映射键名:
ec2_tags = [ {'Key': row['TagKey'], 'Value': row['TagValue']} for row in csv_reader ]
说明
OrderedDict是Python标准字典的子类,用dict()转换后完全符合EC2 API对参数格式的要求,不需要额外复杂处理。
内容的提问来源于stack exchange,提问作者n00
相关产品推荐
相关产品推荐

