You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS Lambda调用MediaConvert CreateJob遇AccessDenied权限问题求助

问题:Lambda调用AWS MediaConvert时的IAM权限错误

问题场景

通过Terraform部署流水线:S3 Put事件触发Python Lambda,调用MediaConvert创建转码任务。控制台使用mediaConverterRole可正常创建任务,但Lambda调用create_job()时抛出权限错误:

(AccessDeniedException) when calling the CreateJob operation: User: arn:aws:sts::---:assumed-role/vidstream-inputVideoProcessor-lambda-role/vidstream-inputVideoProcessor is not authorized to perform: iam:PassRole on resource: arn:aws:iam::---:role/mediaConverterRole

错误原因

Lambda执行角色缺少iam:PassRole权限。当Lambda调用MediaConvert的create_job并指定Role参数时,AWS要求调用者(Lambda执行角色)必须拥有传递该角色的权限,允许MediaConvert服务使用该角色完成转码操作。

修复方案

1. 更新Terraform IAM配置(iam.tf)

调整Lambda角色的信任策略

Lambda角色的信任策略只需允许lambda.amazonaws.com扮演,不需要包含mediaconvert.amazonaws.com(这是MediaConvert角色的信任范围)。

添加iam:PassRole权限

在Lambda的权限策略中添加对mediaConverterRole的iam:PassRole权限,同时保留原有日志和S3权限。

修改后的iam.tf:

# Lambda执行角色
resource "aws_iam_role" "lambda_role" {
  name = "${local.resource_component}-lambda-role"
  assume_role_policy = jsonencode({
    "Version": "2012-10-17",
    "Statement": [{
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }]
  })
}

# Lambda权限策略
resource "aws_iam_policy" "policy" {
  name = "${local.resource_component}-lambda-policy"
  policy = jsonencode({
    "Version": "2012-10-17",
    "Statement": [
      {
        "Effect": "Allow",
        "Action": [
            "logs:*"
        ],
        "Resource": "arn:aws:logs:*:*:*"
      },
      {
        "Effect": "Allow",
        "Action": [
            "s3:*"
        ],
        "Resource": "arn:aws:s3:::*"
      },
      {
        "Effect": "Allow",
        "Action": "iam:PassRole",
        "Resource": "arn:aws:iam::---:role/mediaConverterRole" # 替换为你的mediaConverterRole ARN
      },
      {
        "Effect": "Allow",
        "Action": "mediaconvert:CreateJob",
        "Resource": "*"
      }
    ]
  })
}

# 策略关联到角色
resource "aws_iam_role_policy_attachment" "policy_attachment" {
  role       = aws_iam_role.lambda_role.name
  policy_arn = aws_iam_policy.policy.arn
}

2. 优化Lambda Python代码

  • 指定MediaConvert的区域Endpoint(MediaConvert不使用通用的区域域名,需要通过describe_endpoints获取)
  • 处理S3对象键的URL编码(避免特殊字符导致路径错误)
  • 简化任务模板加载逻辑

修改后的Lambda代码:

import json
import logging
import boto3
from urllib.parse import unquote_plus

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def handler(event, context):
    # 解析S3事件,处理URL编码的对象键
    record = event['Records'][0]['s3']
    input_bucket_name = record['bucket']['name']
    media_object = unquote_plus(record['object']['key'])
    input_file = f's3://{input_bucket_name}/{media_object}'
    logger.info(f"Processing file: {input_file}")

    # MediaConvert客户端初始化(获取区域特定Endpoint)
    mediaconvert_client = boto3.client('mediaconvert')
    endpoints = mediaconvert_client.describe_endpoints()
    mediaconvert_client = boto3.client('mediaconvert', endpoint_url=endpoints['Endpoints'][0]['Url'])

    # 构建转码任务配置
    job_config = {
        "Queue": "arn:aws:mediaconvert:ap-south-1:----:queues/Default", # 替换为你的队列ARN
        "UserMetadata": {},
        "Role": "arn:aws:iam::----:role/mediaConverterRole", # 替换为你的mediaConverterRole ARN
        "Settings": {
            "TimecodeConfig": {"Source": "ZEROBASED"},
            "OutputGroups": [
                {
                    "Name": "File Group",
                    "Outputs": [
                        {
                            "Preset": "System-Generic_Hd_Mp4_Av1_Aac_16x9_640x360p_24Hz_250Kbps_Qvbr_Vq6",
                            "Extension": ".mp4",
                            "NameModifier": "converted"
                        }
                    ],
                    "OutputGroupSettings": {
                        "Type": "FILE_GROUP_SETTINGS",
                        "FileGroupSettings": {
                            "Destination": "s3://----/" # 替换为你的输出S3桶
                        }
                    }
                }
            ],
            "Inputs": [
                {
                    "AudioSelectors": {"Audio Selector 1": {"DefaultSelection": "DEFAULT"}},
                    "VideoSelector": {},
                    "TimecodeSource": "ZEROBASED",
                    "FileInput": input_file
                }
            ]
        },
        "AccelerationSettings": {"Mode": "DISABLED"},
        "StatusUpdateInterval": "SECONDS_60",
        "Priority": 0
    }

    try:
        response = mediaconvert_client.create_job(**job_config)
        logger.info(f"MediaConvert job created: {response['Job']['Id']}")
    except Exception as e:
        logger.error(f"Error creating job: {str(e)}", exc_info=True)
        raise e

    return {
        'statusCode': 200,
        'body': json.dumps({"job_id": response['Job']['Id'] if 'Job' in response else None})
    }

3. 验证MediaConvert角色配置

确保mediaConverterRole的信任策略允许MediaConvert服务扮演:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "mediaconvert.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

同时该角色需要有访问输入S3桶、输出S3桶的权限,以及MediaConvert相关的权限。

内容的提问来源于stack exchange,提问作者ashraf minhaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 06:10:50