Reputation: 73
I'm trying to create S3 bucket through CDK by using the following code
const myBucket = new Bucket(this, 'mybucket', {
bucketName: `NewBucket`
});
Since S3 bucket names are unique stack deployment fails when I try to upload to another account.
I can change bucketname manually everytime I deploy but Is there a way for me to add 'NewBucket-${Stack.AWSaccountId}' dynamically so that whenever stack is deployed to any aws account bucket gets created without any error
Upvotes: 2
Views: 7151
Reputation: 73
Use account ID Hash
I know this is an older question but I ran into this problem and came up with a nice solution.
Firstly it is important to check that the account is resolved before using it as a value.
After that a neat little trick we can do is just to hash the account id to give us a deterministic unique identifier while preserving privacy. We just need to cut of the tail of the hash because the max bucket name length is 63. I use SHA-256 in this example from crypto.js (https://www.npmjs.com/package/crypto-js).
// Check account is resolved
if (cdk.Token.isUnresolved(this.account)) {
throw new Error('Account is unresolved')
}
// Create a deterministic bucket name
let s3BucketPrefix = 'image-bucket'
let maxS3BucketNameLength = 60
let shortHash = SHA256(s3BucketPrefix).toString().slice(0, maxS3BucketNameLength-s3BucketPrefix.length)
let s3BucketName = `${s3BucketPrefix}-${shortHash}`
// Create a bucket
const bucket = new cdk.aws_s3.Bucket(this, `${this.account}`, {
bucketName: s3BucketName,
});
Upvotes: 0
Reputation: 1191
You can prepend the AWS account ID like:
const myBucket = new Bucket(this, `${id}-bucket`, {
bucketName: `${this.account}-NewBucket`
});
But generally and recommend extending the default props, pass into your stack and provide a prefix/name if you wanted something specific for each environment as the account ID is regarded by AWS as sensitive.
For example:
export interface Config extends cdk.StackProps {
readonly params: {
readonly environment: string;
};
}
Then you can use ${props.params.environment}
in your bucket name.
Upvotes: 5
Reputation: 609
I name my buckets projectprefix-name-stage and my cloudformation resource ProjectprefixNameStage (CamelCase) and omit names with randoms.
So cloudformation name MyProjectDataBucketProduction becomes my-project-data-bucket-production
Upvotes: 0
Reputation: 1584
If you do not specify the bucket name, it will generate one for you that will be unique among accounts.
Otherwise, generate your own hash and append to the end of your bucket name string.
Edit: While you could programmatically pull the account number and feed that into the stack as a variable for your bucket name append, I wouldn't recommend attaching an account number to an S3 bucket name for security reasons.
Upvotes: 1