gpt4 book ai didi

python - 如何使用 boto3 和 lambda 函数停止和启动 EC2 实例

转载 作者:行者123 更新时间:2023-12-05 02:01:37 25 4
gpt4 key购买 nike

我想使用 Lambda 函数启动和停止 EC2 实例

我可以使用实例 ID 启动和停止 EC2 实例,但是如何对实例名称执行相同的操作,我正在尝试这样做,因为我的最终用户不知道什么是实例 ID,它们只是知道实例名称

下面是我的代码,它可以很好地处理实例 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)
}

关于python - 如何使用 boto3 和 lambda 函数停止和启动 EC2 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66364247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com