[英]How to resize ec2 instance type dynamically using AWS Lambda function with Boto3
[英]How to Stop and Start EC2 Instance using boto3 and lambda Function
我想使用 Lambda Function 启动和停止 EC2 实例
我可以使用实例 ID 启动和停止 EC2 实例,但是我如何才能对实例名称执行相同操作,我正在尝试这样做,因为我的最终用户不知道什么是实例 ID,他们只知道 Instance姓名
下面是我的代码,它可以正常工作,例如 ID
import json
import boto3
region = 'us-east-1'
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
instances = event["instances"].split(',')
action = event["action"]
if action == 'Start':
print("STARTing your instances: " + str(instances))
ec2.start_instances(InstanceIds=instances)
response = "Successfully started instances: " + str(instances)
elif action == 'Stop':
print("STOPping your instances: " + str(instances))
ec2.stop_instances(InstanceIds=instances)
response = "Successfully stopped instances: " + str(instances)
return {
'statusCode': 200,
'body': json.dumps(response)
}
我为停止而传递的事件
{
"instances": "i-0edb625f45fd4ae5e,i-0818263a2152a23bd,i-0cd2e17ba6f62f651",
"action": "Stop"
}
我为开始而传递的事件
{
"instances": "i-0edb625f45fd4ae5e,i-0818263a2152a23bd,i-0cd2e17ba6f62f651",
"action": "Start"
}
实例名称基于名为Name
的标签。 因此,要根据名称获取实例 ID,您必须按标签过滤实例。 以下是一种可能的方法:
import json
import boto3
region = 'us-east-1'
ec2 = boto3.client('ec2', region_name=region)
def get_instance_ids(instance_names):
all_instances = ec2.describe_instances()
instance_ids = []
# find instance-id based on instance name
# many for loops but should work
for instance_name in instance_names:
for reservation in all_instances['Reservations']:
for instance in reservation['Instances']:
if 'Tags' in instance:
for tag in instance['Tags']:
if tag['Key'] == 'Name' \
and tag['Value'] == instance_name:
instance_ids.append(instance['InstanceId'])
return instance_ids
def lambda_handler(event, context):
instance_names = event["instances"].split(',')
action = event["action"]
instance_ids = get_instance_ids(instance_names)
print(instance_ids)
if action == 'Start':
print("STARTing your instances: " + str(instance_ids))
ec2.start_instances(InstanceIds=instance_ids)
response = "Successfully started instances: " + str(instance_ids)
elif action == 'Stop':
print("STOPping your instances: " + str(instance_ids))
ec2.stop_instances(InstanceIds=instance_ids)
response = "Successfully stopped instances: " + str(instance_ids)
return {
'statusCode': 200,
'body': json.dumps(response)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.