AWS - boto3 EC2 start/stop - автоматизация
Я подготовил лямбда-функцию, я использую модуль 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)
Конфигурация роли лямбда
{
"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])
1 ответ
Решение
Думаю, вы могли бы попробовать следующее.
Вместо
for i in StoppedInstances:
startingInstances = ec2.instances.start(i)
Можно использовать start_instances:
client.start_instances(InstanceIds=StoppedInstances)