首页 > 解决方案 > 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])

标签: amazon-web-servicesaws-lambdaboto3

解决方案


我认为您可以尝试以下方法。

反而

for i in StoppedInstances:
    startingInstances = ec2.instances.start(i)

可以使用start_instances

client.start_instances(InstanceIds=StoppedInstances) 

推荐阅读