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

标签 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):
    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/

相关文章:

amazon-web-services - eb deploy 不更新代码

python - 从 AWS Lambda 连接 Oracle

amazon-web-services - 如何限制ASG中竞价型实例池的数量?

python - Amazon EC2 和 S3 何时使用 Python/SQLite?

python - 缩放 GeoJSON 以查找附近的纬度和经度点

Python 正则表达式命名捕获组

python - 允许 Argparse 参数的特定值

Python 2.7.9 安装 esmre,错误为 'cl.exe',退出状态为 2

asp.net - 在 Elastic Beanstalk 上访问 Dockerized ASP.NET Core Web API 时出现 502 Bad Gateway

linux - 在 Linux EC2 实例上未检测到 g++