Amazon web services AWS-boto3 EC2启动/停止-自动化
我编写了lambda函数,我使用的是python boto3模块,代码如下。现在我面临错误消息“errorMessage:“start\u instances()只接受关键字参数。”。可能是什么问题,我在使用这个自动化,两个星期以来我一直面临这个错误Amazon web services AWS-boto3 EC2启动/停止-自动化,amazon-web-services,aws-lambda,boto3,Amazon Web Services,Aws Lambda,Boto3,我编写了lambda函数,我使用的是python boto3模块,代码如下。现在我面临错误消息“errorMessage:“start\u instances()只接受关键字参数。”。可能是什么问题,我在使用这个自动化,两个星期以来我一直面临这个错误 import boto3 def lambda_handler(event, context): client = boto3.client('ec2') ec2_regions = [region['RegionName'] fo
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)
可以使用:
您好,不幸的是错误消息仍然出现
“errorMessage”:“调用StartInstances操作时发生错误(InvalidParameterCombination):未指定实例”,“errorType”:“ClientError”,
@tester81您能检查StoppedInstances
是否包含正确的实例ID吗?也许它是空的?嗨,是的,我刚刚用print(StoppedInstances),print(ec2\u区域)
对它进行了测试。这些值都正常,只有一件事在这个启动过程中不起作用…@tester81你能用新版本的代码和打印输出更新你的问题吗?@tester81相同,client=boto3.client('ec2',region\u name=region)。显然,这也必须在for循环中。
client.start_instances(InstanceIds=StoppedInstances)