AWS Lambda 代码抛出“调用 StartInstances 操作时发生错误 (UnauthorizedOperation)

AWS Lambda code is throwing "An error occurred (UnauthorizedOperation) when calling the StartInstances operation

我的 lambda 代码:

instances = [aws_instance]

ec2 = boto3.client('ec2',region_name="us-west-2")
if task == 'start':
    ec2.start_instances(InstanceIds=instances)

我的 IAM 用户策略:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ec2:DescribeInstances",
                "ec2:DescribeVolumes",
                "ec2:StartInstances",
                "ec2:StopInstances",
                "ec2:CreateSnapshot",
                "ec2:DeleteSnapshot",
                "ec2:DescribeSnapshots",
         }
```       "ec2:RunInstances",
                "ec2:CopySnapshot",
                "ec2:CreateTags",
                "rds:DescribeDBInstances",
                "rds:CreateDBSnapshot",
                "rds:DeleteDBSnapshot",
                "rds:DescribeDBSnapshots",
                "rds:ListTagsForResource",
                "lambda:AddPermission",
                "lambda:CreateFunction",
                "lambda:InvokeFunction",
                "apigateway:PUT",
                "apigateway:POST",
                "apigateway:GET",
                "ssm:SendCommand"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}

这是抛出错误"An error occurred (UnauthorizedOperation) when calling the StartInstances operation: You are not authorized to perform this operation."

C:\Program Files\Microsoft Visual Studio 11.0>aws --region us-west-2 ec2 start-instances --instance-id i-cd2cb9d5

工作正常。

我无法理解,为什么 lambda 函数说,我不允许执行 "start_instances"

您的 Lambda 不使用 IAM 用户,而是使用 IAM 执行角色。 您可以在 "Configuration" 选项卡 >> "Existing role" 中检查与 Lambda 关联的角色。 然后就可以在IAM中找到这个角色,给它添加策略了。

控制台可能为您创建了当前角色,并且只允许在CloudWatch 中写入。可以 "manually" 创建此角色。使用以下信任关系 可以将其关联到 Lambda:

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

More about creating an execution role for Lambda

Getting error while testing lambda function.

"errorMessage": "An error occurred (UnauthorizedOperation) when calling the StopInstances operation: You are not authorized to perform this operation...

Solution:

  1. open IAM(Identity and Access Management) page.
  2. Select Lambda Function from list.
  3. Open Basic setting page.
  4. Find the selected role in Roles list in IAM page.
  5. In permissions section, attach AdministratorAccess policy and change permission boundary to AdministratorAccess.

我 运行 使用 ec2:RunInstances 解决了这个问题,因为我试图将实例配置文件传递给 EC2 实例。解决方案是向 Lambda 函数添​​加“iam:PassRole”权限。