【问题标题】:How to Stop and Start EC2 Instance using boto3 and lambda Function如何使用 boto3 和 lambda 函数停止和启动 EC2 实例
【发布时间】:2021-05-27 13:27:48
【问题描述】:

我想使用 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"
}

【问题讨论】:

  • 实例名称不唯一。您可能有许多具有相同名称的实例。那你要全部阻止吗?
  • 是的,有道理
  • 所以您要传递实例名称而不是实例 ID?
  • 是的,我们只有实例名称,因为最终用户不知道实例 ID

标签: python amazon-web-services amazon-ec2 lambda boto3


【解决方案1】:

实例名称基于名为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)
    }

【讨论】:

  • 请注意,名称不必是唯一的,这将立即启动/停止所有名称(同名)
  • @lipek 是的,因为名字不是唯一的。否则必须要求您的客户获取实例 ID,而不是名称。或者您的客户确定他/她没有重名?
  • @lipek 哦。我以为你是OP。所以我的评论可能断章取义:-)
  • @RahultheSWE 你是什么意思?答案有效吗?
猜你喜欢
  • 2019-12-08
  • 2017-11-28
  • 2019-08-03
  • 2022-12-13
  • 2022-11-18
  • 2018-08-15
  • 1970-01-01
  • 2020-06-01
  • 2016-08-20
相关资源
最近更新 更多