Skip to content
v2.273.0

Secret L2 construct ​

Creates a new secret in AWS SecretsManager.

Example ​

ts
const user = new iam.User(this, 'User');
const accessKey = new iam.AccessKey(this, 'AccessKey', { user });
declare const stack: Stack;

new secretsmanager.Secret(this, 'Secret', {
  secretObjectValue: {
    username: SecretValue.unsafePlainText(user.userName),
    database: SecretValue.unsafePlainText('foo'),
    password: accessKey.secretAccessKey,
  },
})
python
# stack: Stack
user = iam.User(self, "User")
access_key = iam.AccessKey(self, "AccessKey", user=user)

secretsmanager.Secret(self, "Secret",
    secret_object_value={
        "username": SecretValue.unsafe_plain_text(user.user_name),
        "database": SecretValue.unsafe_plain_text("foo"),
        "password": access_key.secret_access_key
    }
)
java
Stack stack;
User user = new User(this, "User");
AccessKey accessKey = AccessKey.Builder.create(this, "AccessKey").user(user).build();

Secret.Builder.create(this, "Secret")
        .secretObjectValue(Map.of(
                "username", SecretValue.unsafePlainText(user.getUserName()),
                "database", SecretValue.unsafePlainText("foo"),
                "password", accessKey.getSecretAccessKey()))
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
Stack stack;
var user = new User(this, "User");
var accessKey = new AccessKey(this, "AccessKey", new AccessKeyProps { User = user });

new Secret(this, "Secret", new SecretProps {
    SecretObjectValue = new Dictionary<string, SecretValue> {
        { "username", SecretValue.UnsafePlainText(user.UserName) },
        { "database", SecretValue.UnsafePlainText("foo") },
        { "password", accessKey.SecretAccessKey }
    }
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
var stack Stack
user := iam.NewUser(this, jsii.String("User"))
accessKey := iam.NewAccessKey(this, jsii.String("AccessKey"), &AccessKeyProps{
	User: User,
})

secretsmanager.NewSecret(this, jsii.String("Secret"), &SecretProps{
	SecretObjectValue: map[string]SecretValue{
		"username": awscdk.SecretValue_unsafePlainText(user.userName),
		"database": awscdk.SecretValue_unsafePlainText(jsii.String("foo")),
		"password": accessKey.secretAccessKey,
	},
})

Initializer ​

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

Construct Props ​

descriptionstringdescriptionstrdescriptionStringDescriptionstringDescription*string= No description.#
An optional, human-friendly description of the secret.
encryptionKeyIKeyencryption_keyIKeyencryptionKeyIKeyEncryptionKeyIKeyEncryptionKeyIKey= A default KMS key for the accoun…#
The customer-managed encryption key to use for encrypting the secret value.
default

Default: A default KMS key for the account and region is used.

generateSecretStringSecretStringGeneratorgenerate_secret_stringSecretStringGeneratorgenerateSecretStringSecretStringGeneratorGenerateSecretStringSecretStringGeneratorGenerateSecretStringSecretStringGenerator= 32 characters with upper-case le…#
Configuration for how to generate a secret value.

Only one of secretString and generateSecretString can be provided.

default

Default: 32 characters with upper-case letters, lower-case letters, punctuation and numbers (at least one from each category), per the default values of SecretStringGenerator.

removalPolicyRemovalPolicyremoval_policyRemovalPolicyremovalPolicyRemovalPolicyRemovalPolicyRemovalPolicyRemovalPolicyRemovalPolicy= Not set.#
Policy to apply when the secret is removed from this stack.
replicaRegionsReplicaRegion[]replica_regionstyping.List[ReplicaRegion]replicaRegionsList<ReplicaRegion>ReplicaRegionsReplicaRegion[]ReplicaRegions*[]ReplicaRegion= Secret is not replicated#
A list of regions where to replicate this secret.
secretNamestringsecret_namestrsecretNameStringSecretNamestringSecretName*string= A name is generated by CloudForm…#
A name for the secret.

Note that deleting secrets from SecretsManager does not happen immediately, but after a 7 to 30 days blackout period. During that period, it is not possible to create another secret that shares the same name.

default

Default: A name is generated by CloudFormation.

secretObjectValue{ [key: string]: SecretValue }secret_object_valuetyping.Mapping[str, SecretValue]secretObjectValueMap<String, SecretValue>SecretObjectValueIDictionary<string, SecretValue>SecretObjectValue*map[string]SecretValue= SecretsManager generates a new s…#
Initial value for a JSON secret.
notes · default · example

NOTE: *It is highly encouraged to leave this field undefined and allow SecretsManager to create the secret value. The secret object -- if provided -- will be included in the output of the cdk as part of synthesis, and will appear in the CloudFormation template in the console. This can be secure(-ish) if that value is merely reference to another resource (or one of its attributes), but if the value is a plaintext string, it will be visible to anyone with access to the CloudFormation template (via the AWS Console, SDKs, or CLI).

Specifies a JSON object that you want to encrypt and store in this new version of the secret. To specify a simple string value instead, use SecretProps.secretStringValue

Only one of secretStringBeta1, secretStringValue, 'secretObjectValue', and generateSecretString can be provided.

Default: SecretsManager generates a new secret value.

ts
declare const user: iam.User;
declare const accessKey: iam.AccessKey;
declare const stack: Stack;
new secretsmanager.Secret(stack, 'JSONSecret', {
  secretObjectValue: {
    username: SecretValue.unsafePlainText(user.userName), // intrinsic reference, not exposed as plaintext
    database: SecretValue.unsafePlainText('foo'), // rendered as plain text, but not a secret
    password: accessKey.secretAccessKey, // SecretValue
  },
});
secretStringBeta1SecretStringValueBeta1secret_string_beta1SecretStringValueBeta1secretStringBeta1SecretStringValueBeta1SecretStringBeta1SecretStringValueBeta1SecretStringBeta1SecretStringValueBeta1= SecretsManager generates a new s…deprecated#
Use `secretStringValue` instead.
notes · default

NOTE: *It is highly encouraged to leave this field undefined and allow SecretsManager to create the secret value. The secret string -- if provided -- will be included in the output of the cdk as part of synthesis, and will appear in the CloudFormation template in the console. This can be secure(-ish) if that value is merely reference to another resource (or one of its attributes), but if the value is a plaintext string, it will be visible to anyone with access to the CloudFormation template (via the AWS Console, SDKs, or CLI).

Specifies text data that you want to encrypt and store in this new version of the secret. May be a simple string value, or a string representation of a JSON structure.

Only one of secretStringBeta1, secretStringValue, and generateSecretString can be provided.

Default: SecretsManager generates a new secret value.

secretStringValueSecretValuesecret_string_valueSecretValuesecretStringValueSecretValueSecretStringValueSecretValueSecretStringValueSecretValue= SecretsManager generates a new s…#
Initial value for the secret.
notes · default

NOTE: *It is highly encouraged to leave this field undefined and allow SecretsManager to create the secret value. The secret string -- if provided -- will be included in the output of the cdk as part of synthesis, and will appear in the CloudFormation template in the console. This can be secure(-ish) if that value is merely reference to another resource (or one of its attributes), but if the value is a plaintext string, it will be visible to anyone with access to the CloudFormation template (via the AWS Console, SDKs, or CLI).

Specifies text data that you want to encrypt and store in this new version of the secret. May be a simple string value. To provide a string representation of JSON structure, use SecretProps.secretObjectValue instead.

Only one of secretStringBeta1, secretStringValue, 'secretObjectValue', and generateSecretString can be provided.

Default: SecretsManager generates a new secret value.

Properties ​

encryptionKeyIKeyencryption_keyIKeyencryptionKeyIKeyEncryptionKeyIKeyEncryptionKeyIKey#
The customer-managed encryption key that is used to encrypt this secret, if any.

When not specified, the default KMS key for the account and region is being used.

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.

excludeCharactersstringexclude_charactersstrexcludeCharactersStringExcludeCharactersstringExcludeCharacters*string#
The string of the characters that are excluded in this secret when it is generated.
nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.
secretArnstringsecret_arnstrsecretArnStringSecretArnstringSecretArn*stringrequired#
The ARN of the secret in AWS Secrets Manager.

Will return the full ARN if available, otherwise a partial arn. For secrets imported by the deprecated fromSecretName, it will return the secretName.

secretFullArnstringsecret_full_arnstrsecretFullArnStringSecretFullArnstringSecretFullArn*string#
The full ARN of the secret in AWS Secrets Manager, which is the ARN including the Secrets Manager-supplied 6-character suffix.

This is equal to secretArn in most cases, but is undefined when a full ARN is not available (e.g., secrets imported by name).

secretNamestringsecret_namestrsecretNameStringSecretNamestringSecretName*stringrequired#
The name of the secret.

For "owned" secrets, this will be the full resource name (secret name + suffix), unless the '@aws-cdk/aws-secretsmanager:parseOwnedSecretName' feature flag is set.

secretRefSecretReferencesecret_refSecretReferencesecretRefSecretReferenceSecretRefSecretReferenceSecretRefSecretReferencerequired#
A reference to a Secret resource.
secretValueSecretValuesecret_valueSecretValuesecretValueSecretValueSecretValueSecretValueSecretValueSecretValuerequired#
Retrieve the value of the stored secret as a `SecretValue`.
stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.

Methods ​

addReplicaRegion(region: string, encryptionKey?: IKeyRef): voiddef add_replica_region(self, region: str, encryption_key: typing.Optional[IKeyRef] = None) -> Nonepublic void addReplicaRegion(String region, IKeyRef encryptionKey)public void AddReplicaRegion(string region, IKeyRef? encryptionKey = null)func AddReplicaRegion(Region *string, EncryptionKey IKeyRef)#
Adds a replica region for the secret.
2 parameters

Parameters

  • regionregionregionregionRegion — The name of the region.
  • encryptionKeyencryption_keyencryptionKeyencryptionKeyEncryptionKey — The customer-managed encryption key to use for encrypting the secret value.
addRotationSchedule(id: string, options: RotationScheduleOptions): RotationScheduledef add_rotation_schedule(self, id: str, options: RotationScheduleOptions) -> RotationSchedulepublic RotationSchedule addRotationSchedule(String id, RotationScheduleOptions options)public RotationSchedule AddRotationSchedule(string id, RotationScheduleOptions options)func AddRotationSchedule(Id *string, Options RotationScheduleOptions) RotationSchedule#
Adds a rotation schedule to the secret.
addToResourcePolicy(statement: PolicyStatement): AddToResourcePolicyResultdef add_to_resource_policy(self, statement: PolicyStatement) -> AddToResourcePolicyResultpublic AddToResourcePolicyResult addToResourcePolicy(PolicyStatement statement)public AddToResourcePolicyResult AddToResourcePolicy(PolicyStatement statement)func AddToResourcePolicy(Statement PolicyStatement) AddToResourcePolicyResult#
Adds a statement to the IAM resource policy associated with this secret.

If this secret was created in this stack, a resource policy will be automatically created upon the first call to addToResourcePolicy. If the secret is imported, then this is a 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).

attach(target: ISecretAttachmentTarget): ISecretdef attach(self, target: ISecretAttachmentTarget) -> ISecretpublic ISecret attach(ISecretAttachmentTarget target)public ISecret Attach(ISecretAttachmentTarget target)func Attach(Target ISecretAttachmentTarget) ISecret#
Attach a target to this secret.
1 parameter · returns

Parameters

  • targettargettargettargetTarget — The target to attach.

Returns: An attached secret

cfnDynamicReferenceKey(options?: SecretsManagerSecretOptions): stringdef cfn_dynamic_reference_key(self, options: typing.Optional[SecretsManagerSecretOptions] = None) -> strpublic String cfnDynamicReferenceKey(SecretsManagerSecretOptions options)public string CfnDynamicReferenceKey(SecretsManagerSecretOptions? options = null)func CfnDynamicReferenceKey(Options SecretsManagerSecretOptions) *string#
Returns a key which can be used within an AWS CloudFormation dynamic reference to dynamically load this secret from AWS Secrets Manager.
1 parameter

Parameters

  • optionsoptionsoptionsoptionsOptions — Options.
denyAccountRootDelete(): voiddef deny_account_root_delete(self, ) -> Nonepublic void denyAccountRootDelete()public void DenyAccountRootDelete()func DenyAccountRootDelete()#
Denies the `DeleteSecret` action to all principals within the current account.
fromSecretAttributes(scope: Construct, id: string, attrs: SecretAttributes): ISecret@staticmethod def from_secret_attributes(scope: Construct, id: str, attrs: SecretAttributes) -> ISecretpublic static ISecret fromSecretAttributes(Construct scope, String id, SecretAttributes attrs)public static ISecret FromSecretAttributes(Construct scope, string id, SecretAttributes attrs)func FromSecretAttributes(Scope Construct, Id *string, Attrs SecretAttributes) ISecretstatic#
Import an existing secret into the Stack.
3 parameters

Parameters

  • scopescopescopescopeScope — the scope of the import.
  • ididididId — the ID of the imported Secret in the construct tree.
  • attrsattrsattrsattrsAttrs — the attributes of the imported secret.
fromSecretCompleteArn(scope: Construct, id: string, secretCompleteArn: string): ISecret@staticmethod def from_secret_complete_arn(scope: Construct, id: str, secret_complete_arn: str) -> ISecretpublic static ISecret fromSecretCompleteArn(Construct scope, String id, String secretCompleteArn)public static ISecret FromSecretCompleteArn(Construct scope, string id, string secretCompleteArn)func FromSecretCompleteArn(Scope Construct, Id *string, SecretCompleteArn *string) ISecretstatic#
Imports a secret by complete ARN.

The complete ARN is the ARN with the Secrets Manager-supplied suffix.

fromSecretNameV2(scope: Construct, id: string, secretName: string): ISecret@staticmethod def from_secret_name_v2(scope: Construct, id: str, secret_name: str) -> ISecretpublic static ISecret fromSecretNameV2(Construct scope, String id, String secretName)public static ISecret FromSecretNameV2(Construct scope, string id, string secretName)func FromSecretNameV2(Scope Construct, Id *string, SecretName *string) ISecretstatic#
Imports a secret by secret name.
notes

A secret with this name must exist in the same account & region. Replaces the deprecated fromSecretName. Please note this method returns ISecret that only contains partial ARN and could lead to AccessDeniedException when you pass the partial ARN to CLI or SDK to get the secret value. If your secret name ends with a hyphen and 6 characters, you should always use fromSecretCompleteArn() to avoid potential AccessDeniedException.

fromSecretPartialArn(scope: Construct, id: string, secretPartialArn: string): ISecret@staticmethod def from_secret_partial_arn(scope: Construct, id: str, secret_partial_arn: str) -> ISecretpublic static ISecret fromSecretPartialArn(Construct scope, String id, String secretPartialArn)public static ISecret FromSecretPartialArn(Construct scope, string id, string secretPartialArn)func FromSecretPartialArn(Scope Construct, Id *string, SecretPartialArn *string) ISecretstatic#
Imports a secret by partial ARN.

The partial ARN is the ARN without the Secrets Manager-supplied suffix.

grantRead(grantee: IGrantable, versionStages?: string[]): Grantdef grant_read(self, grantee: IGrantable, version_stages: typing.Optional[typing.List[str]] = None) -> Grantpublic Grant grantRead(IGrantable grantee, List<String> versionStages)public Grant GrantRead(IGrantable grantee, string[]? versionStages = null)func GrantRead(Grantee IGrantable, VersionStages *[]*string) Grant#
[disable-awslint:no-grants].
grantWrite(grantee: IGrantable): Grantdef grant_write(self, grantee: IGrantable) -> Grantpublic Grant grantWrite(IGrantable grantee)public Grant GrantWrite(IGrantable grantee)func GrantWrite(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#
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.

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.
isSecret(x: any): boolean@staticmethod def is_secret(x: Any) -> boolpublic static Boolean isSecret(Object x)public static bool IsSecret(object x)func IsSecret(X interface{}) *boolstatic#
Return whether the given object is a Secret.
secretValueFromJson(jsonField: string): SecretValuedef secret_value_from_json(self, json_field: str) -> SecretValuepublic SecretValue secretValueFromJson(String jsonField)public SecretValue SecretValueFromJson(string jsonField)func SecretValueFromJson(JsonField *string) SecretValue#
Interpret the secret as a JSON object and return a field's value from it as a `SecretValue`.
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.