如何检查s3 bucket是否存在,如果不存在,则创建它,如果存在,则将其放入typescript cdk中?

amrnrhlw  于 2023-01-31  发布在  TypeScript
关注(0)|答案(1)|浏览(126)

我需要检查帐户中是否存在存储区,如果不存在,则创建一个存储区,或者使用现有存储区
我试着这样做:

import {Bucket} from 'aws-cdk-lib/aws-s3';

const bucketName = 'testing-bucket-12345';
const checkBucket = Bucket.fromBucketName(this, bucketName, bucketName);
if (!checkBucket) {
    console.log("testinggggg new bucket")
    // Create the S3 bucket if it does not exist
    new Bucket(this, bucketName, {
        bucketName: bucketName
    });
}

但看起来CDK并没有读取这些行

62o28rlo

62o28rlo1#

可以使用Bucket.exists方法。
示例:

import { Bucket } from '@aws-cdk/aws-s3';
const bucketName = 'testing-bucket-12345';

Bucket.exists(this, bucketName).then(bucketExists => {
    if (!bucketExists) {
        new Bucket(this, bucketName, {
            bucketName: bucketName
        });
    } else {
        console.log(`Bucket "${bucketName}" already exists.`);
    }
});

来源:https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/s3-example-does-bucket-exist.html

相关问题