Balu
Balu

Reputation: 161

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?

Upvotes: 4

Views: 12685

Answers (2)

ryanjdillon
ryanjdillon

Reputation: 18948

There is a handy method called fromBucketName you can use:

const bucket = aws_s3.Bucket.fromBucketName(this, "bucketLabel", "nameYouGaveBucket")

Otherwise, I believe you are looking for bucket.bucketName (typescript) or bucket.bucket_name (python).

See typescript docs python docs. This is also available in the CDK wrappers in other languages.

Note that there are similar methods for all sorts of CDK constructs, so you should refer often to the API docs, as there is lots like this you can find easily there.

Upvotes: 4

Max Schenkelberg
Max Schenkelberg

Reputation: 855

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.

Upvotes: 1

Related Questions