Hassan
Hassan

Reputation: 39

How to force CloudFormation to create a new bucket of the similar name if a bucket exist?

Can someone help me out how can I make a template where the cloudformation automatically creates a new bucket of similar name. For example if the name of my bucket is myownbucket, can cloudformation create a new bucket automatically with a name myownbucket1 (if there is already a bucket named myownbucket). Thanks

Upvotes: 0

Views: 596

Answers (1)

Rishitosh Guha
Rishitosh Guha

Reputation: 11

To create or update existing buckets in AWS resource management via cloudformation, You need to have custom resources in your cfn.yaml/json.

  S3Checking:
    Type: 'Custom::CheckS3Bucket'
    Properties:
      ServiceToken: !GetAtt CustomResourceS3Function.Arn
      Bucket: !Ref NotifyBucket

And CustomResourceS3Function will be look like this

 CustomResourceLambdaFunction:
    Type: 'AWS::Lambda::Function'
    Properties:
      Handler: index.lambda_handler
      Role: !GetAtt LambdaIAMRole.Arn
      Code:
        ZipFile: |
            from __future__ import print_function
            import json
            import boto3
            import cfnresponse

            SUCCESS = "SUCCESS"
            FAILED = "FAILED"

            print('Loading function')
            s3 = boto3.resource('s3')

            def lambda_handler(event, context):
                print("Received event: " + json.dumps(event, indent=2))
                responseData={}
                try:
                      print("Request Type:",event['RequestType'])
                      bucket_name=event['ResourceProperties']['Bucket']
                      bucket=event['ResourceProperties']['Bucket']
                      update_delete_buckets(bucket_name)
                      responseData={'Bucket':Bucket}
                      print("Sending response to custom resource")
                    responseStatus = 'SUCCESS'
                except Exception as e:
                    print('Failed to process:', e)
                    responseStatus = 'FAILED'
                    responseData = {'Failure': 'Something bad happened.'}
                cfnresponse.send(event, context, responseStatus, responseData)

            def update_delete_buckets(bucket):
                bucket_obj = s3.Bucket(bucket)
                if bucket_obj.creation_date:
                  print("The bucket exists")
                else:
                   print("The bucket does not exist")
                   s3.create_bucket(Bucket=bucket)

      Runtime: python3.9
      Timeout: 50

Upvotes: 1

Related Questions