简体   繁体   中英

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?

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.

There is a handy method called fromBucketName you can use if it wasn't defined in your current app:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM