AWS Lambda触发异步Comprehend任务时IAM角色权限报错排查
AWS Lambda触发Comprehend异步情感检测任务权限问题排查
问题场景
我用AWS Lambda触发异步Amazon Comprehend情感检测任务,输入数据存在S3桶的input文件夹,结果输出到同桶的output文件夹。已经给任务配置了ComprehendFullAccess和AWSLambdaExecute权限,Lambda代码如下:
import boto3 def lambda_handler(event, context): s3 = boto3.client("s3") bucket = "bucketName" key = "input/inputTextFile.txt" text = s3.get_object(Bucket = bucket, Key = key) review = str(text['Body'].read()) client = boto3.client('comprehend') response = client.start_sentiment_detection_job( InputDataConfig={ 'S3Uri': 's3://bucketName/input/inputTextFile.txt', 'InputFormat': 'ONE_DOC_PER_LINE', 'DocumentReaderConfig': { 'DocumentReadAction': 'TEXTRACT_ANALYZE_DOCUMENT', 'DocumentReadMode': 'SERVICE_DEFAULT', 'FeatureTypes': [ 'FORMS' ] } }, OutputDataConfig={ 'S3Uri': 's3://bucketName/output/' }, DataAccessRoleArn='arn:aws:iam::randomNumbers:role/testrole', JobName='nameOfMyJob', LanguageCode='en' ) print(response) return "response"
但执行时持续报错:
{ "errorMessage": "An error occurred (AccessDeniedException) when calling the StartSentimentDetectionJob operation: User: arn:aws:sts::randomNumbers:assumed-role/testrole/testfunc is not authorized to perform: iam:PassRole on resource: arn:aws:iam::randomNumbers:role/testrole because no identity-based policy allows the iam:PassRole action", "errorType": "ClientError", "requestId": "d3a54dbd-a011-42f0-bc74-440ce9cbaa8d", "stackTrace": [ " File \"/var/task/lambda_function.py\", line 10, in lambda_handler\n response = client.start_sentiment_detection_job(\n", " File \"/var/runtime/botocore/client.py\", line 391, in _api_call\n return self._make_api_call(operation_name, kwargs)\n", " File \"/var/runtime/botocore/client.py\", line 719, in _make_api_call\n raise error_class(parsed_response, operation_name)\n" ] }
当前角色的信任实体配置:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }
我更新后的IAM策略:
{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": [ "iam:PassRole" ], "Resource": "arn:aws:iam::randomNumbers:role/testrole" }] }
请问这是代码问题还是权限问题?
问题分析与解决
这是权限问题,和代码无关。
错误原因
报错信息明确指出:Lambda的执行角色(testrole)没有iam:PassRole权限,无法将该角色传递给Comprehend服务。当调用start_sentiment_detection_job异步API时,Comprehend需要临时获取指定角色的权限来访问S3存储的输入输出数据,因此Lambda执行角色必须被允许将这个角色“传递”给Comprehend,这就需要iam:PassRole权限。
配置验证
你更新的iam:PassRole策略是正确的,但需要确认:
- 该策略是直接附加在**Lambda的执行角色(
testrole)**上的,而非你的个人IAM用户; testrole角色本身需要具备访问指定S3桶的权限(读写input和output文件夹),以及Comprehend相关操作权限(你已配置ComprehendFullAccess,这部分没问题);- 代码中存在冗余逻辑:你先通过
s3.get_object读取了文本内容,但调用异步检测API时直接使用了S3Uri,这段读文本的代码可以删除,不影响功能执行。
内容的提问来源于stack exchange,提问作者bendan
相关产品推荐
相关产品推荐

