How do I trigger inline lambda function within cloudformation template during stack creation?

0

I am trying to create S3 bucket based on a condition whether the bucket already exists or not. I am trying to use inline lambda for this purpose. How do I trigger the inline lambda function? Is there any other way to accomplish what I am trying to do here?

  • 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.

JMK
gefragt vor einem Jahr731 Aufrufe
2 Antworten
0

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')

Cloud_G
beantwortet vor einem Jahr
  • 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.

0

What are you using as an event trigger for Lambda? CloudTrail or EventBridge?

Cloud_G
beantwortet vor einem Jahr

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen