首页 > 解决方案 > AWSLambdaBasicExecutionRole not able to describe instances

问题描述

I am trying to write a basic lambda function to start and stop ec2 instaces and following is my code and i created a role by choosing existing AWSLambdaBasicExecutionRole but i am getting following error.

An error occurred (UnauthorizedOperation) when calling the DescribeInstances operation: You are not authorized to perform this operation.: ClientError

import boto3
ec2 = boto3.client('ec2')
# get the list of all the ec2 instances
def get_all_ec2_ids():
    response = ec2.describe_instances(DryRun=False)
    instances = []
    for reservation in response["Reservations"]:
        for instance in reservation["Instances"]:
            # This sample print will output entire Dictionary object
            # This will print will output the value of the Dictionary key 'InstanceId'
            instances.append(instance["InstanceId"])
    return instances

标签: amazon-ec2aws-lambda

解决方案


首先,AWSLambdaBasicExecutionRole 是一个 POLICY 而不是一个角色,尽管它的名字暗示了它。该政策仅提供以下权限:

    {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "*"
        }
    ]
}

如您所见,这不会为 DescribeInstances 提供任何权限。如果您要添加 AWS 托管策略:

AmazonEC2ReadOnlyAccess

例如,这将为您的 Lambda 提供 DescribeInstances 权限以及其他一些权限。根据您最终希望 Lambda 执行的操作,您可能需要添加不同的策略,或者更好的是,创建您自己的自定义策略,该策略将准确授予您的 Lambda 运行所需的权限。


推荐阅读