Python 如何使用boto3和lambda函数停止和启动EC2实例
我想使用Lambda函数启动和停止EC2实例 我可以使用实例ID启动和停止EC2实例,但如何对实例名称执行相同的操作,我正在尝试这样做,因为我的最终用户不知道什么是实例ID,他们只知道实例名称 下面是我的代码,它在实例ID中运行良好Python 如何使用boto3和lambda函数停止和启动EC2实例,python,amazon-web-services,amazon-ec2,lambda,boto3,Python,Amazon Web Services,Amazon Ec2,Lambda,Boto3,我想使用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):
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)
}
实例名称不唯一。您可能有许多同名的实例。那么您想停止所有实例吗?是的,有意义吗?因此,您要传递的不是实例ID,而是实例名称?是的,我们只有实例名称,因为最终用户不知道实例ID。请注意,名称不必是唯一的,这将启动/停止所有实例(使用相同的名称)once@lipek是的,因为名字不是unqiue。否则,必须要求客户机获取实例id,而不是名称。或者你的客户确定他/她没有重复的名字?是的,谢谢你的帮助help@lipek哦我以为你是OP。所以我的评论可能是断章取义的:-)是的,很好