Как использовать лямбда-функцию в Python для автоматического закрытия экземпляров EC2 в зависимости от часового пояса

Вот фрагмент кода Python для функции Lambda, которая завершает работу экземпляра EC2 в зависимости от указанного часового пояса:

import boto3
import datetime
import pytz
def lambda_handler(event, context):
    ec2 = boto3.client('ec2')
    current_time = datetime.datetime.now(pytz.timezone('<TIME_ZONE>'))

    # Define the time zone and shutdown time
    target_time_zone = pytz.timezone('<TIME_ZONE>')
    shutdown_time = datetime.time(hour=18, minute=0, second=0)  # Adjust the desired shutdown time

    # Convert the current time to the target time zone
    current_time = current_time.astimezone(target_time_zone)

    # Check if the current time matches the shutdown time
    if current_time.time() >= shutdown_time:
        # Retrieve running instances
        response = ec2.describe_instances(
            Filters=[
                {'Name': 'instance-state-name', 'Values': ['running']}
            ]
        )

        # Extract the instance IDs
        instance_ids = []
        for reservation in response['Reservations']:
            for instance in reservation['Instances']:
                instance_ids.append(instance['InstanceId'])

        # Stop the instances
        if instance_ids:
            ec2.stop_instances(InstanceIds=instance_ids)
            print('EC2 instances stopped:', instance_ids)
        else:
            print('No running EC2 instances found.')
    else:
        print('Current time:', current_time.time(), 'is before the shutdown time:', shutdown_time)

Замените на желаемый часовой пояс (например, «Америка/Нью_Йорк», «Азия/Токио» и т. д.). Настройте переменную shutdown_timeв соответствии с вашими требованиями.