ECS Fargate任务无法运行:Cognito身份凭证权限问题求解
解决Cognito未认证角色执行ECS RunTask的权限问题
问题原因
错误提示明确显示:当前使用的Cognito未认证角色(Cognito_<appname>Unauth_Role)未被授权执行ecs:RunTask操作,需要为该角色补充对应的IAM权限策略。
解决步骤
1. 为Cognito未认证角色添加IAM权限策略
登录AWS控制台,进入IAM服务,找到目标Cognito_<appname>Unauth_Role角色,添加以下权限策略:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "ecs:RunTask", "Resource": "arn:aws:ecs:us-west-2:<accountid>:task-definition/<image-name>:<version>", "Condition": { "ArnEquals": { "ecs:cluster": "arn:aws:ecs:us-west-2:<accountid>:cluster/<your-cluster-name>" } } }, // 如需额外ECS权限可添加以下内容 { "Effect": "Allow", "Action": [ "ecs:DescribeClusters", "ecs:DescribeTaskDefinitions" ], "Resource": "*" } ] }
替换策略中的
<accountid>、<image-name>、<version>、<your-cluster-name>为你实际的AWS账号ID、任务定义名称、版本号和ECS集群名称。若需允许所有任务定义,可将Resource设为arn:aws:ecs:us-west-2:<accountid>:task-definition/*。
2. 正确配置AWS SDK并调用RunTask
确保代码中设置了AWS区域,并传入Fargate任务所需的必要参数:
const aws = require("aws-sdk"); // 设置AWS区域 aws.config.update({ region: "us-west-2" }); // 配置Cognito身份凭证 aws.config.credentials = new aws.CognitoIdentityCredentials({ IdentityPoolId: "<your-identity-pool-id>" // 替换为你的身份池ID }); // 初始化ECS客户端 const ecs = new aws.ECS(); // 定义RunTask参数(Fargate必填网络配置) const runTaskParams = { cluster: "<your-cluster-name>", // 替换为你的ECS集群名称 taskDefinition: "<image-name>:<version>", // 替换为你的任务定义名称和版本 launchType: "FARGATE", networkConfiguration: { awsvpcConfiguration: { subnets: ["<subnet-id-1>", "<subnet-id-2>"], // 替换为你的VPC子网ID securityGroups: ["<security-group-id>"], // 替换为你的安全组ID assignPublicIp: "ENABLED" // 根据需求选择ENABLED或DISABLED } }, count: 1 }; // 执行RunTask操作 ecs.runTask(runTaskParams) .promise() .then(data => { console.log("任务启动成功:", data); }) .catch(err => { console.error("任务启动失败:", err); });
验证权限
更新IAM策略后,等待数分钟让权限生效,重新运行代码即可执行ecs:RunTask操作。
内容的提问来源于stack exchange,提问作者karkir subu
相关产品推荐
相关产品推荐

