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.

All Real-World Interview questions Roadmap: Interview readiness

More on Python for DevOps