Skip to content

Instantly share code, notes, and snippets.

@mrpackethead
Created March 23, 2026 11:36
Show Gist options
  • Select an option

  • Save mrpackethead/43a725d51921ac6e8e2580fa39900905 to your computer and use it in GitHub Desktop.

Select an option

Save mrpackethead/43a725d51921ac6e8e2580fa39900905 to your computer and use it in GitHub Desktop.
import * as core from 'aws-cdk-lib';
import { aws_s3 as s3 } from 'aws-cdk-lib';
import * as constructs from 'constructs';
export class BucketNamespace extends core.Mixin {
static accountRegional(): BucketNamespace {
return new BucketNamespace('account-regional');
}
static global(): BucketNamespace {
return new BucketNamespace('global');
}
private constructor(private readonly namespace: 'global' | 'account-regional') {
super();
}
supports(construct: constructs.IConstruct): construct is s3.CfnBucket {
return construct instanceof s3.CfnBucket;
}
applyTo(construct: constructs.IConstruct): void {
const cfnBucket = construct as s3.CfnBucket;
cfnBucket.addPropertyOverride('BucketNamespace', this.namespace);
if (this.namespace === 'account-regional' && cfnBucket.bucketName) {
const stack = core.Stack.of(construct);
const expectedSuffix = `-${stack.account}-${stack.region}-an`;
const suffixPattern = /-\d{12}-[a-z0-9-]+-an$/;
const name = cfnBucket.bucketName as string;
if (name.endsWith(expectedSuffix)) {
return;
}
if (suffixPattern.test(name)) {
throw new Error(
`Bucket name '${name}' has an account-regional suffix that does not match this stack's account/region. Expected suffix: '${expectedSuffix}'`,
);
}
cfnBucket.bucketName = core.Fn.sub(
'${BucketName}-${AWS::AccountId}-${AWS::Region}-an',
{ BucketName: name },
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment