Automating S3 misconfiguration fixes with Lambda
A public S3 bucket is one of those mistakes that is easy to make and expensive to leave. Instead of hoping a review catches it, you can wire AWS itself to notice and fix it.
The shape of the solution
Three pieces do the work:
- AWS Config evaluates buckets against a rule and marks a public one as non-compliant.
- EventBridge routes that finding to compute.
- Lambda re-applies block-public-access and reports what it did.
The remediation function
The function receives the resource id, applies the fix, and notifies. The core is small:
import boto3
s3 = boto3.client("s3")
sns = boto3.client("sns")
def handler(event, context):
bucket = event["detail"]["resourceId"]
s3.put_public_access_block(
Bucket=bucket,
PublicAccessBlockConfiguration={
"BlockPublicAcls": True,
"IgnorePublicAcls": True,
"BlockPublicPolicy": True,
"RestrictPublicBuckets": True,
},
)
sns.publish(
TopicArn=TOPIC_ARN,
Subject="S3 public access remediated",
Message=f"Re-applied block-public-access to {bucket}",
)
Why notify on every action
The temptation is to let automation run silently. Don't. Publishing each change to SNS keeps the system auditable and gives a human the chance to review or roll back. Automated remediation earns trust by being legible, not by being invisible.
Keep the rule set small and well understood. A guardrail you can reason about is worth more than a clever one you can't.