- Newest
- Most votes
- Most comments
Hello, So you can use a lambda function that takes and event as input which can contain a "bucket_name" field with the name you want. Then using the native boto3 library, create an s3 client and check if it exists already by calling the "head_bucket" method. If it doesn't exist, have the function create it with the "create_bucket" api call. finally, you can add a statement to just print the bucket name if it already exists. Feel free to reference the code below as a base:
*You will need to replace the "event" and "context" parameters with the desired event and objects for when the function is called.
Hope this helps!
import boto3
def create_s3_bucket(event, context):
# Get the bucket name from the event data
bucket_name = event['bucket_name']
# Create an S3 client
s3 = boto3.client('s3')
# Check if the bucket already exists
try:
s3.head_bucket(Bucket=bucket_name)
except s3.exceptions.NoSuchBucket:
# Create the bucket if it does not exist
s3.create_bucket(Bucket=bucket_name)
print(f'Bucket {bucket_name} created')
else:
print(f'Bucket {bucket_name} already exists')
Thank you for your response. I have already tried what you have suggested. The function doesn't get triggered and the bucket name doesn't get passed to the function either because I don't see S3 bucket. I see that the function is created but the Custom Resource remains in "Create in Progress" status until I delete the stack.
What are you using as an event trigger for Lambda? CloudTrail or EventBridge?
Relevant content
- Accepted Answerasked 3 years ago
- Accepted Answerasked a year ago
- AWS OFFICIALUpdated a year ago
- AWS OFFICIALUpdated 4 months ago
- AWS OFFICIALUpdated 10 months ago
- AWS OFFICIALUpdated 6 months ago
What will you do if the bucket exists?
If it exists, do nothing. If it doesn't exist, create it.
OK for CloudFormation to not manage the bucket? What if the bucket is owned by another account?
Bucket is going to be created and owned by the same account.