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
已提問 1 年前檢視次數 731 次
2 個答案
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
已回答 1 年前
  • 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
已回答 1 年前

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南