Search code examples
amazon-web-servicesamazon-s3aws-cdk

How to get bucket name from Bucket object in AWS CDK for python


I've create an S3 bucket for hosting my website. For that I've used the below code from the AWS CDK for python docs

self.bucket = s3.Bucket(
    self,
    "my-bucket-name",
    bucket_name="my-bucket-name",
    removal_policy=core.RemovalPolicy.DESTROY,
    website_index_document="index.html",
    public_read_access=True
)

For a reason, I want to send this bucket object as an argument to another object and get the bucket name from the argument. So, I've tried

self.bucket.bucket_name
self.bucket.bucket_arn

nothing seems working, instead the object returns ${Token[TOKEN.189]}. Could anyone guide me through this?


Solution

  • If the bucket name is hard coded like the example you pasted above, you can always externalize it to the cdk context file. As you've seen, when you access the bucket name from the Bucket construct, it creates a reference to it and that is so if you need it in another resource, cloud formation will depend on the value from the Bucket resource by using the Ref/GetAtt capabilities in CloudFormation. Then it will be guaranteed that the bucket actually exists before it is used downstream.

    If you don't care about that and just want the actual bucket name in the cdk app code then put the value in the cdk context json file and use node.try_get_context to retrieve it wherever.