Write a script that creates an S3 bucket only if it doesn't exist, in a non-us-east-1 region.
IntermediateHands-onPython for DevOps
Answer
import boto3
from botocore.exceptions import ClientError
region, bucket = "ap-south-1", "devopsshack-artifacts-123456"
s3 = boto3.client("s3", region_name=region)
try:
s3.head_bucket(Bucket=bucket)
print("exists")
except ClientError as e:
if e.response["Error"]["Code"] in ("404", "NoSuchBucket"):
s3.create_bucket(
Bucket=bucket,
CreateBucketConfiguration={"LocationConstraint": region},
)
print("created")
else:
raise # 403 = exists but owned by someone else
Key trick → Outside us-east-1 you must pass LocationConstraint, or the call fails with IllegalLocationConstraintException. A 403 from head_bucket means the name is taken by someone else.
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