KMSKey object cannot add a key policy by calling the addToResourcePolicy function in cdk code?

0

Hello ! I'm having trouble setting the KMS Key policy via CDK code, here's how I'm dealing with it so far.

First, I create a KMS Key in a stack and then use the "new cdk. CfnOutput" to export the arn of the KMS key.

Then, In another stack use "cdk. Fn.importValue" to import the ARN of the KMS Key, use ”kms.Key.fromKeyArn“ to get the KMS Key object.

Finally, I want to add a key policy to a KMS key by calling the "addToResourcePolicy" method, but after the deployment is completed, I cannot see the added key policy in the AWS KMS console, but there is no error during the deployment.

The CDK uses the language typescript.

The basic invocation process is as follows:

// Stask A
demoKMSKey = new kms.Key(this, 'demoKMSKey', {
    alias: `demoKMSKey`,
});

new cdk.CfnOutput(this, 'demoKMSKey-Arn', {
    exportName: 'demoKMSKey-Arn',
    value: demoKMSKey.keyArn,
});

// Stack B
const demoKMSKey = kms.Key.fromKeyArn(
    this,
    'demoKMSKey',
    cdk.Fn.importValue('demoKMSKey-Arn')
);

demoKMSKey.addToResourcePolicy(
    new iam.PolicyStatement({
        sid: `demoKMSKeyPolicy`,
        effect: iam.Effect.ALLOW,
        principals: [new iam.ArnPrincipal(ec2RoleArn)],
        actions: ['kms:Encrypt', 'kms:Decrypt', 'kms:ReEncrypt*', 'kms:GenerateDataKey*', 'kms:DescribeKey'],
        resources: ['*'],
    })
);

Current KMS Key Policy is:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::12345678901234:root"
            },
            "Action": "kms:*",
            "Resource": "*"
        }
    ]
}

Additional Notes: The user who performs the CDK deployment operation has the kms:* permission on any resources.

1 Answer
1
Accepted Answer

Hello.

If you add a policy to "new kms.Key" as shown below, will it be displayed?
https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_kms.Key.html

demoKMSKey = new kms.Key(this, 'demoKMSKey', {
    alias: `demoKMSKey`,
    policy: ...
});
profile picture
EXPERT
answered a month ago
profile picture
EXPERT
reviewed a month ago
  • After I added the policy object[PolicyDocument], I performed the deployment and got the following error: Resource handler returned message: "Service returned error code MalformedPolicyDocumentException (Service: Kms, Status Code: 400, Request ID: 4b9b)" (RequestToken: bea34c2, HandlerErrorCode: InvalidRequest)

  • Then I also used the addToResourcePolicy method to add the policy in the stack of creating KMSKey, but I got the same error when deploying.

  • For the time being, I was able to confirm that it works with the code below. I was able to create code that can be referenced within the same stack.

    import * as cdk from 'aws-cdk-lib';
    import { Construct } from 'constructs';
    import * as kms from 'aws-cdk-lib/aws-kms';
    import * as iam from 'aws-cdk-lib/aws-iam';
    
    export class CdkAppStack extends cdk.Stack {
      constructor(scope: Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props);
    
        const demoKMSKey = new kms.Key(this, 'demoKMSKey', {
          alias: `demoKMSKey`,
        });
    
        const ec2Role = new iam.Role(this, "Role",{
          roleName: "test-assume",
          assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com')
        });
    
        const ec2RoleArn= ec2Role.roleArn
    
        demoKMSKey.addToResourcePolicy(
          new iam.PolicyStatement({
              sid: `demoKMSKeyPolicy`,
              effect: iam.Effect.ALLOW,
              principals: [new iam.ArnPrincipal(ec2RoleArn)],
              actions: ['kms:Encrypt', 'kms:Decrypt', 'kms:ReEncrypt*', 'kms:GenerateDataKey*', 'kms:DescribeKey'],
              resources: ['*'],
          })
        );
    
        new cdk.CfnOutput(this, 'demoKMSKey-Arn', {
          exportName: 'demoKMSKey-Arn',
          value: demoKMSKey.keyArn,
        });
      }
    }
    
  • I haven't been able to confirm this due to lack of time, but it may be possible to reference KMS from another stack using the method described in the document below. https://repost.aws/knowledge-center/cdk-cross-stack-reference

  • Thanks for you help, I'm going to keep investigating. Could you tell me the permissions of your deployment user? Thanks again.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions