logo NodeSeekbeta

【教程】使用AWS Lambda 监控 AWS Lightsail 流量限额,超额自动关机

  • 突然发现日志流这里是空的,什么情况?之前创建的有问题,全部东西删除重新创建发现没有日志了。 ac03
    image
    解决了!因为连日志写入权限一块儿删除了导致的,重新添加即可! ac01
    image

  • 好用,bd!

  • 教程】使用AWS Lambda 监控 AWS Lightsail 流量限额,超额自动关机

  • 可以用脚本限流关机了

  • 感谢楼主,已部署。

  • 我开的是2C2G 60G配置的机型,月流量3T的流量,奇怪,为什么函数返回我每月只有2T的额度?

    image

    image

    image

  • 找到原因了,代码里面的流量应该是按总流量和可用日期做了平均。
    实际aws的流量是按月计算的。
    让GPT把代码调整了一下:

    import json
    import boto3
    import calendar
    from datetime import datetime, date, time
    
    def get_current_month_first_day_zero_time():
        today = date.today()
        first_day = today.replace(day=1)
        return datetime.combine(first_day, time.min)
        
    def get_current_time_utc():
        return datetime.utcnow()
    
    def stop_instance(instance_name):
        client = boto3.client('lightsail')
        response = client.stop_instance(
            instanceName=instance_name,
            force=True
        )
        print(f"Stopped instance: {instance_name}")
        
    def list_instances():
        client = boto3.client('lightsail')
        instances_list = []
        paginator = client.get_paginator('get_instances')
        page_iterator = paginator.paginate()
        for page in page_iterator:
            for instance in page['instances']:
                print(f"Found instance: {instance['name']}")
                instances_list.append(instance['name'])
        return instances_list
            
    def get_monthly_quota(instance_name):
        client = boto3.client('lightsail')
        response = client.get_instance(instanceName=instance_name)
        quota_gb = response['instance']['networking']['monthlyTransfer']['gbPerMonthAllocated']
        print(f"Instance {instance_name} monthly quota: {quota_gb} GB")
        return quota_gb
        
    def get_instance_data_usage(instance_name, data_type):
        client = boto3.client('lightsail')
        start_time = get_current_month_first_day_zero_time()
        end_time = get_current_time_utc()
        
        response = client.get_instance_metric_data(
            instanceName=instance_name,
            metricName=data_type,
            period=86400,  # 1 day
            unit='Bytes',
            statistics=['Sum'],
            startTime=start_time,
            endTime=end_time
        )
        
        data_points = response.get('metricData', [])
        total_usage_bytes = sum([dp['sum'] for dp in data_points])
        print(f"Total {data_type} usage for {instance_name}: {total_usage_bytes} Bytes")
        return total_usage_bytes
        
    def lambda_handler(event, context):
        instances = list_instances()
        for instance_name in instances:
            quota_gb = get_monthly_quota(instance_name)
            quota_bytes = quota_gb * 1024 ** 3  # GB to Bytes
            
            network_out_bytes = get_instance_data_usage(instance_name, "NetworkOut")
            network_in_bytes = get_instance_data_usage(instance_name, "NetworkIn")
            total_usage_bytes = network_out_bytes + network_in_bytes
            
            usage_percent = (total_usage_bytes / quota_bytes) * 100 if quota_bytes > 0 else 0
            
            msg = (f"Instance: {instance_name}\n"
                   f"Usage: {total_usage_bytes} Bytes\n"
                   f"Quota: {quota_bytes} Bytes\n"
                   f"Usage Percent: {usage_percent:.2f}%")
            print(msg)
            
            # 如果使用超过90%,停止实例
            if total_usage_bytes >= 0.9 * quota_bytes:
                print(f"Usage exceeds 90% quota, stopping instance: {instance_name}")
                stop_instance(instance_name)
                
        return {
            'statusCode': 200,
            'body': json.dumps('Lightsail network usage checked successfully.')
        }
    
    
  • 感谢分享,已部署 xhj020

  • 感谢分享,已部署

你好啊,陌生人!

我的朋友,看起来你是新来的,如果想参与到讨论中,点击下面的按钮!

📈用户数目📈

目前论坛共有72269位seeker

🎉欢迎新用户🎉