amazon-web-services - AWS - boto3 EC2 启动/停止 - 自动化
问题描述
我准备了 lambda 函数,我使用的是 python boto3 模块,代码如下。现在我面临错误消息"errorMessage": "start_instances() only accepts keyword arguments."
。可能是什么问题,我正在使用这种自动化,两周以来我都面临这个错误。
import boto3
def lambda_handler(event, context):
client = boto3.client('ec2')
ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
for region in ec2_regions:
ec2 = boto3.resource('ec2',region_name=region)
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])
StoppedInstances = [instance.id for instance in instances]
for i in StoppedInstances:
startingInstances = ec2.instances.start(i)
print(startingInstances)
print(ec2_regions)
更新后的版本
import boto3
def lambda_handler(event, context):
client = boto3.client('ec2')
#region = 'eu-west-1'
ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
for region in ec2_regions:
ec2 = boto3.resource('ec2',region_name=region)
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])
StoppedInstances = [instance.id for instance in instances]
print(StoppedInstances)
print(ec2_regions)
client.start_instances(InstanceIds=StoppedInstances)
Lambda 角色配置
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"ec2:DescribeInstances",
"ec2:StartInstances",
"ec2:StopInstances",
"ec2:DescribeRegions",
"ec2:DescribeInstanceStatus"
],
"Resource": "*"
}
]
}
更正和工作代码如下:
import boto3
def lambda_handler(event, context):
client = boto3.client('ec2')
#region = 'eu-west-1'
ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
for region in ec2_regions:
client = boto3.client('ec2',region_name=region)
ec2 = boto3.resource('ec2',region_name=region)
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])
StoppedInstances = [instance.id for instance in instances]
for i in StoppedInstances:
client.start_instances(InstanceIds=[i])
解决方案
我认为您可以尝试以下方法。
反而
for i in StoppedInstances:
startingInstances = ec2.instances.start(i)
可以使用start_instances:
client.start_instances(InstanceIds=StoppedInstances)
推荐阅读
- swift - 使用 NSTintConfiguration 自定义侧边栏
- reactjs - 如何在数组中创建一个新对象
- javascript - 覆盖类实例方法有什么问题吗?
- php - 如何使用 VUE 在 Laravel Blade 中显示数据库信息
- algorithm - 按位与和按位或对数字进行运算
- vaadin - Vaadin 14 TreeGrid - 不能多次添加同一个项目
- javascript - Discord bot Embed 未按我的意愿返回文本
- symbols - 当我尝试在pycharm中输入反斜杠时获取日元符号
- c - 如何在 3D 坐标系中绘制线条
- excel - 如果两个 Range 对象在 for 循环中具有相同的范围,如何返回 true?