amazon-ec2 - 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
解决方案
首先,AWSLambdaBasicExecutionRole 是一个 POLICY 而不是一个角色,尽管它的名字暗示了它。该政策仅提供以下权限:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "*"
}
]
}
如您所见,这不会为 DescribeInstances 提供任何权限。如果您要添加 AWS 托管策略:
AmazonEC2ReadOnlyAccess
例如,这将为您的 Lambda 提供 DescribeInstances 权限以及其他一些权限。根据您最终希望 Lambda 执行的操作,您可能需要添加不同的策略,或者更好的是,创建您自己的自定义策略,该策略将准确授予您的 Lambda 运行所需的权限。
推荐阅读
- flutter - 如何将 Image.file 添加为圆形头像的背景图像
- java - java的复杂性选择
- javascript - 如何在没有 JSDoc 的情况下为给定的 .js 脚本定义和使用类型?
- javascript - 我的反应函数钩子没有在函数内返回数据状态?
- google-apps-script - Google Script:根据多个条件将行移动到不同的工作表
- react-native - 在 react-native 的屏幕之间传递数据
- c++ - 使用大括号和圆括号
- python - 如何使用 Python/selenium 循环获取鼠标悬停元素的内容?
- oracle - Oracle SQL Loader 和日期字段的问题
- sql - Big Query - 背靠背计算开始和结束日期