繁体   English   中英

如何使用带有Boto3的AWS Lambda函数动态调整ec2实例类型的大小

[英]How to resize ec2 instance type dynamically using AWS Lambda function with Boto3

如何使用python lambda函数更改多个实例的实例类型,而无需对实例ID进行硬编码。

import boto3

client = boto3.client('ec2')

# Insert your Instance ID here
my_instance = <<some code here to fetch instance IDs of all instances 
filtering all t2.micro instance types>>

# Stop the instance
client.stop_instances(InstanceIds=[my_instance])
waiter=client.get_waiter('instance_stopped')
waiter.wait(InstanceIds=[my_instance])

# Change the instance type
client.modify_instance_attribute(InstanceId=my_instance, 
Attribute='instanceType', Value='m3.xlarge')

# Start the instance
client.start_instances(InstanceIds=[my_instance])

仅提供一个列表,例如:

import boto3

client = boto3.client('ec2')

# Get t2.micro instances
response = client.describe_instances(
   Filters=[{'Name': 'instance-type','Values':['t2.micro']}]
)

instances = [i['InstanceId'] for i in r['Instances'] for r in response['Reservations']]

# Stop the instances
client.stop_instances(InstanceIds=instances)
waiter=client.get_waiter('instance_stopped')
waiter.wait(InstanceIds=instances)

# Change the instance type
for i in instances:
    client.modify_instance_attribute(InstanceId=i, Attribute='instanceType', Value='m3.xlarge')

# Start the instance
client.start_instances(InstanceIds=instances)

我没有测试代码,所以请先测试!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM