diff --git a/packages/@aws-cdk/aws-kms/lib/key.ts b/packages/@aws-cdk/aws-kms/lib/key.ts index db334374593ed..0dc523fb73c37 100644 --- a/packages/@aws-cdk/aws-kms/lib/key.ts +++ b/packages/@aws-cdk/aws-kms/lib/key.ts @@ -1,6 +1,6 @@ import * as iam from '@aws-cdk/aws-iam'; import * as cxschema from '@aws-cdk/cloud-assembly-schema'; -import { FeatureFlags, IResource, Lazy, RemovalPolicy, Resource, Stack, Duration, Token, ContextProvider, Arn, ArnFormat } from '@aws-cdk/core'; +import { FeatureFlags, IResource, Lazy, RemovalPolicy, Resource, ResourceProps, Stack, Duration, Token, ContextProvider, Arn, ArnFormat } from '@aws-cdk/core'; import * as cxapi from '@aws-cdk/cx-api'; import { Construct } from 'constructs'; import { Alias } from './alias'; @@ -94,8 +94,8 @@ abstract class KeyBase extends Resource implements IKey { */ private readonly aliases: Alias[] = []; - constructor(scope: Construct, id: string) { - super(scope, id); + constructor(scope: Construct, id: string, props: ResourceProps = {}) { + super(scope, id, props); this.node.addValidation({ validate: () => this.policy?.validateForResourcePolicy() ?? [] }); } @@ -464,8 +464,8 @@ export class Key extends KeyBase { // policies is really the only option protected readonly trustAccountIdentities: boolean = true; - constructor(keyId: string) { - super(scope, id); + constructor(keyId: string, props: ResourceProps = {}) { + super(scope, id, props); this.keyId = keyId; } @@ -476,7 +476,9 @@ export class Key extends KeyBase { throw new Error(`KMS key ARN must be in the format 'arn:aws:kms:::key/', got: '${keyArn}'`); } - return new Import(keyResourceName); + return new Import(keyResourceName, { + environmentFromArn: keyArn, + }); } /** diff --git a/packages/@aws-cdk/aws-kms/test/key.test.ts b/packages/@aws-cdk/aws-kms/test/key.test.ts index 43d6fbdf82aaa..5c4c2adee490d 100644 --- a/packages/@aws-cdk/aws-kms/test/key.test.ts +++ b/packages/@aws-cdk/aws-kms/test/key.test.ts @@ -1240,3 +1240,34 @@ describe('key specs and key usages', () => { .toThrow('key rotation cannot be enabled on asymmetric keys'); }); }); + +describe('Key.fromKeyArn()', () => { + let stack: cdk.Stack; + + beforeEach(() => { + const app = new cdk.App(); + stack = new cdk.Stack(app, 'Base', { + env: { account: '111111111111', region: 'stack-region' }, + }); + }); + + describe('for a key in a different account and region', () => { + let key: kms.IKey; + + beforeEach(() => { + key = kms.Key.fromKeyArn( + stack, + 'iKey', + 'arn:aws:kms:key-region:222222222222:key:key-name', + ); + }); + + test("the key's region is taken from the ARN", () => { + expect(key.env.region).toBe('key-region'); + }); + + test("the key's account is taken from the ARN", () => { + expect(key.env.account).toBe('222222222222'); + }); + }); +});