Skip to content
v2.274.0

Key L2 construct ​

Defines a KMS key.

Example ​

ts
declare const vpc: ec2.Vpc;
const engine = rds.DatabaseInstanceEngine.postgres({ version: rds.PostgresEngineVersion.VER_16_3 });
const myKey = new kms.Key(this, 'MyKey');

new rds.DatabaseInstance(this, 'InstanceWithCustomizedSecret', {
  engine,
  vpc,
  credentials: rds.Credentials.fromGeneratedSecret('postgres', {
    secretName: 'my-cool-name',
    encryptionKey: myKey,
    excludeCharacters: '!&*^#@()',
    replicaRegions: [{ region: 'eu-west-1' }, { region: 'eu-west-2' }],
  }),
});
python
# vpc: ec2.Vpc

engine = rds.DatabaseInstanceEngine.postgres(version=rds.PostgresEngineVersion.VER_16_3)
my_key = kms.Key(self, "MyKey")

rds.DatabaseInstance(self, "InstanceWithCustomizedSecret",
    engine=engine,
    vpc=vpc,
    credentials=rds.Credentials.from_generated_secret("postgres",
        secret_name="my-cool-name",
        encryption_key=my_key,
        exclude_characters="!&*^#@()",
        replica_regions=[secretsmanager.ReplicaRegion(region="eu-west-1"), secretsmanager.ReplicaRegion(region="eu-west-2")]
    )
)
java
Vpc vpc;

IInstanceEngine engine = DatabaseInstanceEngine.postgres(PostgresInstanceEngineProps.builder().version(PostgresEngineVersion.VER_16_3).build());
Key myKey = new Key(this, "MyKey");

DatabaseInstance.Builder.create(this, "InstanceWithCustomizedSecret")
        .engine(engine)
        .vpc(vpc)
        .credentials(Credentials.fromGeneratedSecret("postgres", CredentialsBaseOptions.builder()
                .secretName("my-cool-name")
                .encryptionKey(myKey)
                .excludeCharacters("!&*^#@()")
                .replicaRegions(List.of(ReplicaRegion.builder().region("eu-west-1").build(), ReplicaRegion.builder().region("eu-west-2").build()))
                .build()))
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
Vpc vpc;

var engine = DatabaseInstanceEngine.Postgres(new PostgresInstanceEngineProps { Version = PostgresEngineVersion.VER_16_3 });
var myKey = new Key(this, "MyKey");

new DatabaseInstance(this, "InstanceWithCustomizedSecret", new DatabaseInstanceProps {
    Engine = engine,
    Vpc = vpc,
    Credentials = Credentials.FromGeneratedSecret("postgres", new CredentialsBaseOptions {
        SecretName = "my-cool-name",
        EncryptionKey = myKey,
        ExcludeCharacters = "!&*^#@()",
        ReplicaRegions = new [] { new ReplicaRegion { Region = "eu-west-1" }, new ReplicaRegion { Region = "eu-west-2" } }
    })
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
var vpc Vpc

engine := rds.DatabaseInstanceEngine_Postgres(&PostgresInstanceEngineProps{
	Version: rds.PostgresEngineVersion_VER_16_3(),
})
myKey := kms.NewKey(this, jsii.String("MyKey"))

rds.NewDatabaseInstance(this, jsii.String("InstanceWithCustomizedSecret"), &DatabaseInstanceProps{
	Engine: Engine,
	Vpc: Vpc,
	Credentials: rds.Credentials_FromGeneratedSecret(jsii.String("postgres"), &CredentialsBaseOptions{
		SecretName: jsii.String("my-cool-name"),
		EncryptionKey: myKey,
		ExcludeCharacters: jsii.String("!&*^#@()"),
		ReplicaRegions: []ReplicaRegion{
			&ReplicaRegion{
				Region: jsii.String("eu-west-1"),
			},
			&ReplicaRegion{
				Region: jsii.String("eu-west-2"),
			},
		},
	}),
})

Initializer ​

ts
new Key(scope: Construct, id: string, props?: KeyProps)
python
Key(scope: Construct, id: str, props: typing.Optional[KeyProps] = None)
java
new Key(Construct scope, String id, KeyProps props)
csharp
new Key(Construct scope, string id, KeyProps? props = null)
go
NewKey(Scope Construct, Id *string, Props KeyProps)

Construct Props ​

adminsIPrincipal[]adminstyping.List[IPrincipal]adminsList<IPrincipal>AdminsIPrincipal[]Admins*[]IPrincipal= []#
A list of principals to add as key administrators to the key policy.
notes

Key administrators have permissions to manage the key (e.g., change permissions, revoke), but do not have permissions to use the key in cryptographic operations (e.g., encrypt, decrypt).

These principals will be added to the default key policy (if none specified), or to the specified policy (if provided).

aliasstringaliasstraliasStringAliasstringAlias*string= No alias is added for the key.#
Initial alias to add to the key.

More aliases can be added later by calling addAlias.

descriptionstringdescriptionstrdescriptionStringDescriptionstringDescription*string= No description.#
A description of the key.

Use a description that helps your users decide whether the key is appropriate for a particular task.

enabledbooleanenabledboolenabledBooleanEnabledboolEnabled*bool= Key is enabled.#
Indicates whether the key is available for use.
enableKeyRotationbooleanenable_key_rotationboolenableKeyRotationBooleanEnableKeyRotationboolEnableKeyRotation*bool= false#
Indicates whether AWS KMS rotates the key.
keySpecKeySpeckey_specKeySpeckeySpecKeySpecKeySpecKeySpecKeySpecKeySpec= KeySpec.SYMMETRIC_DEFAULT#
The cryptographic configuration of the key. The valid value depends on usage of the key.

IMPORTANT: If you change this property of an existing key, the existing key is scheduled for deletion and a new key is created with the specified value.

keyUsageKeyUsagekey_usageKeyUsagekeyUsageKeyUsageKeyUsageKeyUsageKeyUsageKeyUsage= KeyUsage.ENCRYPT_DECRYPT#
The cryptographic operations for which the key can be used.

IMPORTANT: If you change this property of an existing key, the existing key is scheduled for deletion and a new key is created with the specified value.

multiRegionbooleanmulti_regionboolmultiRegionBooleanMultiRegionboolMultiRegion*bool= false#
Creates a multi-Region primary key that you can replicate in other AWS Regions.
notes

You can't change the multiRegion value after the KMS key is created.

IMPORTANT: If you change the value of the multiRegion property on an existing KMS key, the update request fails, regardless of the value of the UpdateReplacePolicy attribute. This prevents you from accidentally deleting a KMS key by changing an immutable property value.

pendingWindowDurationpending_windowDurationpendingWindowDurationPendingWindowDurationPendingWindowDuration= 30 days#
Specifies the number of days in the waiting period before AWS KMS deletes a CMK that has been removed from a CloudFormation stack.
notes

When you remove a customer master key (CMK) from a CloudFormation stack, AWS KMS schedules the CMK for deletion and starts the mandatory waiting period. The PendingWindowInDays property determines the length of waiting period. During the waiting period, the key state of CMK is Pending Deletion, which prevents the CMK from being used in cryptographic operations. When the waiting period expires, AWS KMS permanently deletes the CMK.

Enter a value between 7 and 30 days.

policyPolicyDocumentpolicyPolicyDocumentpolicyPolicyDocumentPolicyPolicyDocumentPolicyPolicyDocument= A policy document with permissio…#
Custom policy document to attach to the KMS key.
notes · default

NOTE - If the @aws-cdk/aws-kms:defaultKeyPolicies feature flag is set (the default for new projects), this policy will override the default key policy and become the only key policy for the key. If the feature flag is not set, this policy will be appended to the default key policy.

Default: A policy document with permissions for the account root to administer the key will be created.

removalPolicyRemovalPolicyremoval_policyRemovalPolicyremovalPolicyRemovalPolicyRemovalPolicyRemovalPolicyRemovalPolicyRemovalPolicy= RemovalPolicy.Retain#
Whether the encryption key should be retained when it is removed from the Stack.

This is useful when one wants to retain access to data that was encrypted with a key that is being retired.

rotationPeriodDurationrotation_periodDurationrotationPeriodDurationRotationPeriodDurationRotationPeriodDuration= set by CFN to 365 days.#
The period between each automatic rotation.

Properties ​

DEFAULT_DUMMY_KEY_IDstringdefault_dummy_key_idstrDEFAULT_DUMMY_KEY_IDStringDEFAULT_DUMMY_KEY_IDstringDEFAULT_DUMMY_KEY_ID*stringrequiredstatic#
The default key id of the dummy key.

This value is used as a dummy key id if the key was not found by the Key.fromLookup() method.

The environment this resource belongs to.
notes

For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.

For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.

grantsKeyGrantsgrantsKeyGrantsgrantsKeyGrantsGrantsKeyGrantsGrantsKeyGrantsrequired#
Collection of grant methods for a Key.
keyArnstringkey_arnstrkeyArnStringKeyArnstringKeyArn*stringrequired#
The ARN of the key.
keyIdstringkey_idstrkeyIdStringKeyIdstringKeyId*stringrequired#
The ID of the key (the part that looks something like: 1234abcd-12ab-34cd-56ef-1234567890ab).
A reference to a Key resource.
nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.
stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.

Methods ​

addAlias(aliasName: string): Aliasdef add_alias(self, alias_name: str) -> Aliaspublic Alias addAlias(String aliasName)public Alias AddAlias(string aliasName)func AddAlias(AliasName *string) Alias#
Defines a new alias for the key.
addToResourcePolicy(statement: PolicyStatement, allowNoOp?: boolean): AddToResourcePolicyResultdef add_to_resource_policy(self, statement: PolicyStatement, allow_no_op: typing.Optional[bool] = None) -> AddToResourcePolicyResultpublic AddToResourcePolicyResult addToResourcePolicy(PolicyStatement statement, Boolean allowNoOp)public AddToResourcePolicyResult AddToResourcePolicy(PolicyStatement statement, bool? allowNoOp = null)func AddToResourcePolicy(Statement PolicyStatement, AllowNoOp *bool) AddToResourcePolicyResult#
Adds a statement to the KMS key resource policy.
2 parameters

Parameters

  • statementstatementstatementstatementStatement — The policy statement to add.
  • allowNoOpallow_no_opallowNoOpallowNoOpAllowNoOp — If this is set to false and there is no policy defined (i.e. external key), the operation will fail. Otherwise, it will no-op.
applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#
Override the cross-stack reference strength for this resource.
notes · 1 parameter

When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.

Parameters

  • strengthstrengthstrengthstrengthStrength — - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#
Apply the given removal policy to this resource.
notes

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).

fromCfnKey(cfnKey: CfnKey): IKey@staticmethod def from_cfn_key(cfn_key: CfnKey) -> IKeypublic static IKey fromCfnKey(CfnKey cfnKey)public static IKey FromCfnKey(CfnKey cfnKey)func FromCfnKey(CfnKey CfnKey) IKeystatic#
Create a mutable `IKey` based on a low-level `CfnKey`.
notes

This is most useful when combined with the cloudformation-include module. This method is different than fromKeyArn() because the IKey returned from this method is mutable; meaning, calling any mutating methods on it, like IKey.addToResourcePolicy(), will actually be reflected in the resulting template, as opposed to the object returned from fromKeyArn(), on which calling those methods would have no effect.

fromKeyArn(scope: Construct, id: string, keyArn: string): IKey@staticmethod def from_key_arn(scope: Construct, id: str, key_arn: str) -> IKeypublic static IKey fromKeyArn(Construct scope, String id, String keyArn)public static IKey FromKeyArn(Construct scope, string id, string keyArn)func FromKeyArn(Scope Construct, Id *string, KeyArn *string) IKeystatic#
Import an externally defined KMS Key using its ARN.
3 parameters

Parameters

  • scopescopescopescopeScope — the construct that will "own" the imported key.
  • ididididId — the id of the imported key in the construct tree.
  • keyArnkey_arnkeyArnkeyArnKeyArn — the ARN of an existing KMS key.
fromLookup(scope: Construct, id: string, options: KeyLookupOptions): IKey@staticmethod def from_lookup(scope: Construct, id: str, options: KeyLookupOptions) -> IKeypublic static IKey fromLookup(Construct scope, String id, KeyLookupOptions options)public static IKey FromLookup(Construct scope, string id, KeyLookupOptions options)func FromLookup(Scope Construct, Id *string, Options KeyLookupOptions) IKeystatic#
Import an existing Key by querying the AWS environment this stack is deployed to.
notes

This function only needs to be used to use Keys not defined in your CDK application. If you are looking to share a Key between stacks, you can pass the Key object between stacks and use it as normal. In addition, it's not necessary to use this method if an interface accepts an IKey. In this case, Alias.fromAliasName() can be used which returns an alias that extends IKey.

Calling this method will lead to a lookup when the CDK CLI is executed. You can therefore not use any values that will only be available at CloudFormation execution time (i.e., Tokens).

If you set returnDummyKeyOnMissing to true in options and the key was not found, this method will return a dummy key with a key id '1234abcd-12ab-34cd-56ef-1234567890ab'. The value of the dummy key id can also be referenced using the Key.DEFAULT_DUMMY_KEY_ID variable, and you can check if the key is a dummy key by using the Key.isLookupDummy() method.

The Key information will be cached in cdk.context.json and the same Key will be used on future runs. To refresh the lookup, you will have to evict the value from the cache using the cdk context command. See https://docs.aws.amazon.com/cdk/latest/guide/context.html for more information.

grant(grantee: IGrantable, ...actions: string[]): Grantdef grant(self, grantee: IGrantable, actions: str) -> Grantpublic Grant grant(IGrantable grantee, String actions)public Grant Grant(IGrantable grantee, string actions)func Grant(Grantee IGrantable, Actions *string) Grant#
Grant the indicated permissions on this key to the given principal.

This modifies both the principal's policy as well as the resource policy, since the default CloudFormation setup for KMS keys is that the policy must not be empty and so default grants won't work.

[disable-awslint:no-grants]

grantAdmin(grantee: IGrantable): Grantdef grant_admin(self, grantee: IGrantable) -> Grantpublic Grant grantAdmin(IGrantable grantee)public Grant GrantAdmin(IGrantable grantee)func GrantAdmin(Grantee IGrantable) Grant#
Grant admins permissions using this key to the given principal.

Key administrators have permissions to manage the key (e.g., change permissions, revoke), but do not have permissions to use the key in cryptographic operations (e.g., encrypt, decrypt).

[disable-awslint:no-grants]

grantDecrypt(grantee: IGrantable): Grantdef grant_decrypt(self, grantee: IGrantable) -> Grantpublic Grant grantDecrypt(IGrantable grantee)public Grant GrantDecrypt(IGrantable grantee)func GrantDecrypt(Grantee IGrantable) Grant#
Grant decryption permissions using this key to the given principal.

[disable-awslint:no-grants]

grantEncrypt(grantee: IGrantable): Grantdef grant_encrypt(self, grantee: IGrantable) -> Grantpublic Grant grantEncrypt(IGrantable grantee)public Grant GrantEncrypt(IGrantable grantee)func GrantEncrypt(Grantee IGrantable) Grant#
Grant encryption permissions using this key to the given principal.

[disable-awslint:no-grants]

grantEncryptDecrypt(grantee: IGrantable): Grantdef grant_encrypt_decrypt(self, grantee: IGrantable) -> Grantpublic Grant grantEncryptDecrypt(IGrantable grantee)public Grant GrantEncryptDecrypt(IGrantable grantee)func GrantEncryptDecrypt(Grantee IGrantable) Grant#
Grant encryption and decryption permissions using this key to the given principal.

[disable-awslint:no-grants]

grantGenerateMac(grantee: IGrantable): Grantdef grant_generate_mac(self, grantee: IGrantable) -> Grantpublic Grant grantGenerateMac(IGrantable grantee)public Grant GrantGenerateMac(IGrantable grantee)func GrantGenerateMac(Grantee IGrantable) Grant#
Grant permissions to generating MACs to the given principal.

[disable-awslint:no-grants]

grantSign(grantee: IGrantable): Grantdef grant_sign(self, grantee: IGrantable) -> Grantpublic Grant grantSign(IGrantable grantee)public Grant GrantSign(IGrantable grantee)func GrantSign(Grantee IGrantable) Grant#
Grant sign permissions using this key to the given principal.

[disable-awslint:no-grants]

grantSignVerify(grantee: IGrantable): Grantdef grant_sign_verify(self, grantee: IGrantable) -> Grantpublic Grant grantSignVerify(IGrantable grantee)public Grant GrantSignVerify(IGrantable grantee)func GrantSignVerify(Grantee IGrantable) Grant#
Grant sign and verify permissions using this key to the given principal.

[disable-awslint:no-grants]

grantVerify(grantee: IGrantable): Grantdef grant_verify(self, grantee: IGrantable) -> Grantpublic Grant grantVerify(IGrantable grantee)public Grant GrantVerify(IGrantable grantee)func GrantVerify(Grantee IGrantable) Grant#
Grant verify permissions using this key to the given principal.

[disable-awslint:no-grants]

grantVerifyMac(grantee: IGrantable): Grantdef grant_verify_mac(self, grantee: IGrantable) -> Grantpublic Grant grantVerifyMac(IGrantable grantee)public Grant GrantVerifyMac(IGrantable grantee)func GrantVerifyMac(Grantee IGrantable) Grant#
Grant permissions to verifying MACs to the given principal.

[disable-awslint:no-grants]

isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

isLookupDummy(key: IKeyRef): boolean@staticmethod def is_lookup_dummy(key: IKeyRef) -> boolpublic static Boolean isLookupDummy(IKeyRef key)public static bool IsLookupDummy(IKeyRef key)func IsLookupDummy(Key IKeyRef) *boolstatic#
Checks if the key returned by the `Key.fromLookup()` method is a dummy key, i.e., a key that was not found.

This method can only be used if the returnDummyKeyOnMissing option is set to true in the options for the Key.fromLookup() method.

isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#
Returns true if the construct was created by CDK, and false otherwise.
isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#
Check whether the given construct is a Resource.
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.