簡體   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