Key L2 construct
Defines a KMS key.
Example
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' }],
}),
});
# 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")]
)
)
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();
// 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" } }
})
});
// 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
Construct Props
adminsIPrincipal[]adminstyping.List[IPrincipal]adminsList<IPrincipal>AdminsIPrincipal[]Admins*[]IPrincipal= []#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).
More aliases can be added later by calling addAlias.
descriptionstringdescriptionstrdescriptionStringDescriptionstringDescription*string= No description.#Use a description that helps your users decide whether the key is appropriate for a particular task.
enableKeyRotationbooleanenable_key_rotationboolenableKeyRotationBooleanEnableKeyRotationboolEnableKeyRotation*bool= false#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#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.
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#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…#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#This is useful when one wants to retain access to data that was encrypted with a key that is being retired.
Properties
DEFAULT_DUMMY_KEY_IDstringdefault_dummy_key_idstrDEFAULT_DUMMY_KEY_IDStringDEFAULT_DUMMY_KEY_IDstringDEFAULT_DUMMY_KEY_ID*stringrequiredstatic#This value is used as a dummy key id if the key was not found by the Key.fromLookup() method.
envResourceEnvironmentenvResourceEnvironmentenvResourceEnvironmentEnvResourceEnvironmentEnvResourceEnvironmentrequired#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.
keyRefKeyReferencekey_refKeyReferencekeyRefKeyReferenceKeyRefKeyReferenceKeyRefKeyReferencerequired#PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#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#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#2 parameters
Parameters
statementstatementstatementstatementStatement— The policy statement to add.allowNoOpallow_no_opallowNoOpallowNoOpAllowNoOp— If this is set tofalseand 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)#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)#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#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#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#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#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#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#[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#[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#[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#[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#[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#[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#[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#[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#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#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#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#toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#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.