2

I have a bucket that is defined/managed in a different stack. The bucket is encrypted by a key managed in KMS. In my own stack, I am trying to create a role and grant read and decrypt permissions for that role on the bucket and the key respectively.

I reference the bucket and the key as follows:

const otherBucket = Bucket.fromBucketName(this, 'otherBucket', '<BucketName>');
const otherKeyArn = otherBucket.encryptionKey?.keyArn || '';

I use the key arn to create policy statements for my role, and it always is returned as ''. I created another bucket in my stack and when I try to access the encryption key for that bucket, I am getting the correct key arn for that bucket.

Is there a bug in the fromBucketName method that's causing this? I am currently having to store the string arn for the key as a hard coded value in my constants file, is there a better way of doing this?

Keshav Potluri
  • 479
  • 5
  • 15

1 Answers1

3

fromBucketName method is not making any aws calls to get the attributes of the S3 bucket, it is merely creating a Javascript object with attributes passed, which in this case, it is just the bucket name.

const bucket = s3.Bucket.fromBucketName(
  this,
  "mybucket",
  "my-bucket-name"
);

Two standard ways for this situation are:

First method, export the name of the key where you have original created the bucket as

const myBucket = new s3.Bucket(this, "my-bucket", {
  encryption: s3.BucketEncryption.KMS,
});

new cdk.CfnOutput(this, "my-bucket-arn-out", {
  value: myBucket.encryptionKey?.keyArn!,
  description: "This is my-bucket kms key arn",
  exportName: "my-bucket-kms-key-arn",
});

Then import is where ever we need using importValue

const s3KeyArn = cdk.Fn.importValue('my-bucket-kms-key-arn')

Second Method, we can use a custom resource which creates a Lambda and calls an AWS Api to get Key Arn behind the scenes.

Balu Vyamajala
  • 9,287
  • 1
  • 20
  • 42
  • My stacks are separate (as in the s3 bucket was created and is managed by another team) and in a separate repo, would the first method still work? Would really like to avoid a Lambda for this. For now, I just basically just used a hardcoded arn for the key, but would like to change this. – Keshav Potluri Apr 21 '21 at 00:52
  • @KeshavPotluri For the first method, we need to change in template/cdk where s3 bucket is created, if it is maintained by other team, we can't do much. They at least need to set an alias to the Kms Key, then you can use alias name, rather than hard coding a kms key directly. – Balu Vyamajala Apr 21 '21 at 02:37