Write a boto3 script that finds S3 buckets without default encryption or with public access not blocked.
AdvancedHands-onPython for DevOps
Answer
import boto3
from botocore.exceptions import ClientError
s3 = boto3.client("s3")
for b in s3.list_buckets()["Buckets"]:
name = b["Name"]
issues = []
try:
pab = s3.get_public_access_block(Bucket=name)["PublicAccessBlockConfiguration"]
if not all(pab.values()):
issues.append("public access block partially off")
except ClientError as e:
if e.response["Error"]["Code"] == "NoSuchPublicAccessBlockConfiguration":
issues.append("no public access block")
else:
raise
try:
s3.get_bucket_encryption(Bucket=name)
except ClientError as e:
if e.response["Error"]["Code"] == "ServerSideEncryptionConfigurationNotFoundError":
issues.append("no default encryption")
print(f"{name}: {', '.join(issues) or 'OK'}")
Key trick → boto3 reports "not configured" as a ClientError with a specific code, so branch on e.response["Error"]["Code"] instead of catching everything. (Since January 2023 new buckets get SSE-S3 by default, so the encryption check mostly flags old buckets.)
More on Python for DevOps
Write a Python script using boto3 that lists all running EC2 instances with their Name tag.BeginnerWrite a script that finds unattached EBS volumes and deletes them (with a dry-run flag).IntermediateCall a REST API with `requests`, handle timeouts and non-2xx responses properly.BeginnerAdd retry with exponential backoff to HTTP calls without writing the loop yourself.IntermediateWrite your own retry decorator with exponential backoff and jitter.AdvancedParse a YAML file and print every container image in a multi-document Kubernetes manifest.Intermediate