How do I pass a string to inline lambda function in Cloudformation for S3 bucket name

0

I am trying to create a S3 bucket using Custom Resource and Inline lambda function using a name passed to it in Cloudformation. How do I pass a string for the bucket name as a parameter to the inline lambda function? I tried in vain to use the event['ResourceProperties']['BucketName'] which is a string defined under Custom Resource section and also tried to use Environment: Variables: None of these two seem to be working.

  • Can you add the code here? Why are you using a custom resource?

  • MyS3Resource: Type: AWS::CloudFormation::CustomResource Properties: ServiceToken: !GetAtt S3BucketLambda.Arn BucketName: !Sub cache-${AWS::AccountId} Region: !Ref AWS::Region

    S3BucketLambda: Type: AWS::Lambda::Function Properties: FunctionName: Index Handler: index.handler Runtime: python3.7 Role: !Join ["", ["arn:aws:iam::", !Ref "AWS::AccountId", ":role/companyname/aws-projectname-lambda-role"]] MemorySize: 128 Timeout: 10 Description: "Testing S3" Environment: Variables: BucketName: "cache-11223344" Code: ZipFile: | import boto3 import os import cfnresponse

          s3_client = boto3.client('s3')
    
          def handler(event, context):
            bucketName = event['ResourceProperties']['BucketName']
            this_event = event['RequestType']
            regionName = event['ResourceProperties']['Region']
            response_data = {}
    
            try:
              if this_event in ('Create', 'Update'):
                output = s3_client.head_bucket(Bucket=bucketName)
                print (output['ResponseMetadata']['HTTPStatusCode'])
            except Exception as e:
              try:
                response = s3_client.create_bucket(Bucket=bucketName)
                print (response)
                response_data['Data'] = json.dumps(response)
              except Exception as e:
                print (str (e))
    
1 Answer
0

Hi

If you are passing parameters to the stack that you want to use in the bucket name then this is possible.
There are two ways I use to create bucket names. Note, all this can also be used in a Lambda if you are putting the lambda code "inline" in the CloudFormation template.

First with a parameter for bucket name [bucketname].
In the resource section I can then just use "!Ref bucketname" under the bucket resource to reference the parameter.

The other way I have used, especially in multi-landscape, is referencing one or many parameters and concatenating text along with text using !Sub. For example with parameters for [landscape], [tier], [environment] and pseudo parameters I could create the following naming.
!Sub bucket-${AWS::Region}-${landscape}-${tier}-${environment}.

Might be worth taking a look at the AWS CloudFormation Workshop.

Hope this helps and solve your challenges.

profile picture
answered a year ago
  • Thank you, Mr. Ford, for your response. I do not want to use the parameter as I want the name to be dynamically created. I will try the second option you have suggested.

  • So, I used !Sub to define the bucket name under Custom Resource section, but the name never gets passed to the function.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions