Keshav Potluri
Keshav Potluri

Reputation: 499

AWS CDK `Bucket.encryptionKey?.arn` doesn't return a value despite having an encryption key associated with it

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?

Upvotes: 3

Views: 2429

Answers (1)

Balu Vyamajala
Balu Vyamajala

Reputation: 10333

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.

Upvotes: 5

Related Questions