Env variables for the lambda script:
JSON_KEY : blocked_ips_list.json
S3_BUCKET_NAME: custom-rbr-log-bucket-522d8090 (in your case, it might differ)

import json
import boto3
import os

s3_client = boto3.client('s3')

def lambda_handler(event, context):
    bucket_name = os.environ['S3_BUCKET_NAME']
    json_key = os.environ['JSON_KEY']
    ip_address_to_remove = "106.51.48.86/32"  # IP Address to Whitelist; Deploy and click Test to run
    try:
        # Fetch the existing JSON file from S3
        response = s3_client.get_object(Bucket=bucket_name, Key=json_key)
        json_data = response['Body'].read().decode('utf-8')
        data = json.loads(json_data)
        # Remove the IP address entry if it exists
        if ip_address_to_remove in data['IPv4']:
            del data['IPv4'][ip_address_to_remove]
            # Save the updated JSON back to S3
            updated_json_data = json.dumps(data)
            s3_client.put_object(Bucket=bucket_name, Key=json_key, Body=updated_json_data)
            return {
                'statusCode': 200,
                'body': json.dumps({'message': f'{ip_address_to_remove} removed successfully'})
            }
        elif ip_address_to_remove in data['IPv6']:
            del data['IPv6'][ip_address_to_remove]
            # Save the updated JSON back to S3
            updated_json_data = json.dumps(data)
            s3_client.put_object(Bucket=bucket_name, Key=json_key, Body=updated_json_data)
            return {
                'statusCode': 200,
                'body': json.dumps({'message': f'{ip_address_to_remove} removed successfully'})
            }
        else:
            return {
                'statusCode': 404,
                'body': json.dumps({'message': f'{ip_address_to_remove} not found'})
            }
    except Exception as e:
        return {
            'statusCode': 500,
            'body': json.dumps({'error': str(e)})
        }
Edit Report
Pub: 21 Jan 2025 04:25 UTC
Views: 37