AWS新手用Lambda创建EBS快照遇UnauthorizedOperation权限错误求助
问题原因
错误日志已明确指出核心问题:你的Lambda执行角色没有ec2:CreateTags权限。因为你在调用create_snapshot API时,通过TagSpecifications参数直接为新创建的快照添加标签,这个操作会触发单独的ec2:CreateTags权限校验,但你当前的IAM策略仅配置了ec2:CreateSnapshot等权限,未覆盖标签操作。
解决建议
1. 更新IAM策略
在现有策略的Action列表中添加ec2:CreateTags权限,修改后的策略如下:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ec2:CreateSnapshot", "ec2:CreateTags", "ec2:DescribeInstances", "ec2:DescribeVolumes" ], "Resource": "*" } ] }
新手阶段用"Resource": "*"可快速验证问题,后续若需精细化权限控制,可将资源限定为具体的卷ARN和快照ARN。
2. 优化Lambda代码(可选)
你的代码存在冗余和潜在时区问题,可做如下优化:
- 删除未使用的
pathlib导入和lambda_client实例 - 使用UTC时间生成快照名称,避免时区差异导致的命名不一致
修正后的代码:
import json import boto3 import logging from datetime import datetime, timezone logger = logging.getLogger() logger.setLevel(logging.INFO) def handler(event, context): myec2 = boto3.client("ec2") # 使用UTC时间避免时区问题 current_date = datetime.now(timezone.utc).strftime("%Y-%m-%d") print("Hey hello") try: response = myec2.create_snapshot( Description="My Ec2 Daily Snapshot", VolumeId="vol-0ce1640002f882ad1", TagSpecifications=[ { "ResourceType": "snapshot", "Tags": [ { "Key": "Name", "Value": f"My Ec2 Snapshot {current_date}" } ] } ] ) logger.info(f"Successfully Created Snapshot {json.dumps(response, default=str)}") except Exception as e: logger.error(f"Error Creating Snapshot {str(e)}")
内容的提问来源于stack exchange,提问作者Kiran
相关产品推荐
相关产品推荐

