Skip to content
v2.275.0

SecretValue Class ​

Work with secret values in the CDK.

Constructs that need secrets will declare parameters of type SecretValue.

The actual values of these secrets should not be committed to your repository, or even end up in the synthesized CloudFormation template. Instead, you should store them in an external system like AWS Secrets Manager or SSM Parameter Store, and you can reference them by calling SecretValue.secretsManager() or SecretValue.ssmSecure().

You can use SecretValue.unsafePlainText() to construct a SecretValue from a literal string, but doing so is highly discouraged.

To make sure secret values don't accidentally end up in readable parts of your infrastructure definition (such as the environment variables of an AWS Lambda Function, where everyone who can read the function definition has access to the secret), using secret values directly is not allowed. You must pass them to constructs that accept SecretValue properties, which are guaranteed to use the value only in CloudFormation properties that are write-only.

If you are sure that what you are doing is safe, you can call secretValue.unsafeUnwrap() to access the protected string of the secret value.

(If you are writing something like an AWS Lambda Function and need to access a secret inside it, make the API call to GetSecretValue directly inside your Lamba's code, instead of using environment variables.)

Example ​

ts
const amplifyApp = new amplify.App(this, 'MyApp', {
  sourceCodeProvider: new amplify.GitHubSourceCodeProvider({
    owner: '<user>',
    repository: '<repo>',
    oauthToken: SecretValue.secretsManager('my-github-token'),
  }),
  basicAuth: amplify.BasicAuth.fromCredentials('username', SecretValue.secretsManager('my-github-token')),
});
python
amplify_app = amplify.App(self, "MyApp",
    source_code_provider=amplify.GitHubSourceCodeProvider(
        owner="<user>",
        repository="<repo>",
        oauth_token=SecretValue.secrets_manager("my-github-token")
    ),
    basic_auth=amplify.BasicAuth.from_credentials("username", SecretValue.secrets_manager("my-github-token"))
)
java
App amplifyApp = App.Builder.create(this, "MyApp")
        .sourceCodeProvider(GitHubSourceCodeProvider.Builder.create()
                .owner("<user>")
                .repository("<repo>")
                .oauthToken(SecretValue.secretsManager("my-github-token"))
                .build())
        .basicAuth(BasicAuth.fromCredentials("username", SecretValue.secretsManager("my-github-token")))
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
var amplifyApp = new App(this, "MyApp", new AppProps {
    SourceCodeProvider = new GitHubSourceCodeProvider(new GitHubSourceCodeProviderProps {
        Owner = "<user>",
        Repository = "<repo>",
        OauthToken = SecretValue.SecretsManager("my-github-token")
    }),
    BasicAuth = BasicAuth.FromCredentials("username", SecretValue.SecretsManager("my-github-token"))
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
amplifyApp := amplify.NewApp(this, jsii.String("MyApp"), &AppProps{
	SourceCodeProvider: amplify.NewGitHubSourceCodeProvider(&GitHubSourceCodeProviderProps{
		Owner: jsii.String("<user>"),
		Repository: jsii.String("<repo>"),
		OauthToken: awscdk.SecretValue_SecretsManager(jsii.String("my-github-token")),
	}),
	BasicAuth: amplify.BasicAuth_FromCredentials(jsii.String("username"), awscdk.SecretValue_*SecretsManager(jsii.String("my-github-token"))),
})

Initializer ​

ts
new SecretValue(protectedValue: any, options?: IntrinsicProps)
python
SecretValue(protected_value: Any, options: typing.Optional[IntrinsicProps] = None)
java
new SecretValue(Object protectedValue, IntrinsicProps options)
csharp
new SecretValue(object protectedValue, IntrinsicProps? options = null)
go
NewSecretValue(ProtectedValue interface{}, Options IntrinsicProps)

Properties ​

creationStackstring[]creation_stacktyping.List[str]creationStackList<String>CreationStackstring[]CreationStack*[]*string#
The captured stack trace which represents the location in which this token was created.
typeHintmay be undefinedResolutionTypeHinttype_hintmay be undefinedResolutionTypeHinttypeHintmay be undefinedResolutionTypeHintTypeHintmay be undefinedResolutionTypeHintTypeHintmay be undefinedResolutionTypeHint#
Type that the Intrinsic is expected to evaluate to.

Methods ​

cfnDynamicReference(ref: CfnDynamicReference): SecretValue // chainable@staticmethod def cfn_dynamic_reference(ref: CfnDynamicReference) -> SecretValuepublic static SecretValue cfnDynamicReference(CfnDynamicReference ref)public static SecretValue CfnDynamicReference(CfnDynamicReference ref)func CfnDynamicReference(Ref CfnDynamicReference) SecretValuestatic#
Obtain the secret value through a CloudFormation dynamic reference.

If possible, use SecretValue.ssmSecure or SecretValue.secretsManager directly.

1 parameter

Parameters

  • refrefrefrefRef — The dynamic reference to use.
cfnDynamicReferenceKey(secretId: string, options?: SecretsManagerSecretOptions): string@staticmethod def cfn_dynamic_reference_key(secret_id: str, options: typing.Optional[SecretsManagerSecretOptions] = None) -> strpublic static String cfnDynamicReferenceKey(String secretId, SecretsManagerSecretOptions options)public static string CfnDynamicReferenceKey(string secretId, SecretsManagerSecretOptions? options = null)func CfnDynamicReferenceKey(SecretId *string, Options SecretsManagerSecretOptions) *stringstatic#
Returns a key which can be used within an AWS CloudFormation dynamic reference to dynamically load a secret from AWS Secrets Manager.
2 parameters

Parameters

  • secretIdsecret_idsecretIdsecretIdSecretId — The ID or ARN of the secret.
  • optionsoptionsoptionsoptionsOptions — Options.
cfnParameter(param: CfnParameter): SecretValue // chainable@staticmethod def cfn_parameter(param: CfnParameter) -> SecretValuepublic static SecretValue cfnParameter(CfnParameter param)public static SecretValue CfnParameter(CfnParameter param)func CfnParameter(Param CfnParameter) SecretValuestatic#
Obtain the secret value through a CloudFormation parameter.

Generally, this is not a recommended approach. AWS Secrets Manager is the recommended way to reference secrets.

1 parameter

Parameters

  • paramparamparamparamParam — The CloudFormation parameter to use.
isSecretValue(x: any): boolean@staticmethod def is_secret_value(x: Any) -> boolpublic static Boolean isSecretValue(Object x)public static bool IsSecretValue(object x)func IsSecretValue(X interface{}) *boolstatic#
Test whether an object is a SecretValue.
plainText(secret: string): SecretValue // chainable@staticmethod def plain_text(secret: str) -> SecretValuepublic static SecretValue plainText(String secret)public static SecretValue PlainText(string secret)func PlainText(Secret *string) SecretValuestaticdeprecated#
Use `unsafePlainText()` instead.
notes

Do not use this method for any secrets that you care about! The value will be visible to anyone who has access to the CloudFormation template (via the AWS Console, SDKs, or CLI).

The only reasonable use case for using this method is when you are testing.

resolve(context: IResolveContext): anydef resolve(self, context: IResolveContext) -> Anypublic Object resolve(IResolveContext context)public object Resolve(IResolveContext context)func Resolve(Context IResolveContext) interface{}#
Resolve the secret.

If the feature flag is not set, resolve as normal. Otherwise, throw a descriptive error that the usage guard is missing.

resourceAttribute(attr: string): SecretValue // chainable@staticmethod def resource_attribute(attr: str) -> SecretValuepublic static SecretValue resourceAttribute(String attr)public static SecretValue ResourceAttribute(string attr)func ResourceAttribute(Attr *string) SecretValuestatic#
Use a resource's output as secret value.
secretsManager(secretId: string, options?: SecretsManagerSecretOptions): SecretValue // chainable@staticmethod def secrets_manager(secret_id: str, options: typing.Optional[SecretsManagerSecretOptions] = None) -> SecretValuepublic static SecretValue secretsManager(String secretId, SecretsManagerSecretOptions options)public static SecretValue SecretsManager(string secretId, SecretsManagerSecretOptions? options = null)func SecretsManager(SecretId *string, Options SecretsManagerSecretOptions) SecretValuestatic#
Creates a `SecretValue` with a value which is dynamically loaded from AWS Secrets Manager.

If you rotate the value in the Secret, you must also change at least one property on the resource where you are using the secret, to force CloudFormation to re-read the secret.

2 parameters

Parameters

  • secretIdsecret_idsecretIdsecretIdSecretId — The ID or ARN of the secret.
  • optionsoptionsoptionsoptionsOptions — Options.
ssmSecure(parameterName: string, version?: string): SecretValue // chainable@staticmethod def ssm_secure(parameter_name: str, version: typing.Optional[str] = None) -> SecretValuepublic static SecretValue ssmSecure(String parameterName, String version)public static SecretValue SsmSecure(string parameterName, string? version = null)func SsmSecure(ParameterName *string, Version *string) SecretValuestatic#
Use a secret value stored from a Systems Manager (SSM) parameter.
notes · 2 parameters

This secret source in only supported in a limited set of resources and properties. Click here for the list of supported properties.

Parameters

  • parameterNameparameter_nameparameterNameparameterNameParameterName — The name of the parameter in the Systems Manager Parameter Store.
  • versionversionversionversionVersion — An integer that specifies the version of the parameter to use.
toJSON(): anydef to_json(self, ) -> Anypublic Object toJSON()public object ToJSON()func ToJSON() interface{}#
Turn this Token into JSON.

Called automatically when JSON.stringify() is called on a Token.

toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Convert an instance of this Token to a string.

This method will be called implicitly by language runtimes if the object is embedded into a string. We treat it the same as an explicit stringification.

toStringList(): string[]def to_string_list(self, ) -> typing.List[str]public List<String> toStringList()public string[] ToStringList()func ToStringList() *[]*string#
Convert an instance of this Token to a string list.

This method will be called implicitly by language runtimes if the object is embedded into a list. We treat it the same as an explicit stringification.

unsafePlainText(secret: string): SecretValue // chainable@staticmethod def unsafe_plain_text(secret: str) -> SecretValuepublic static SecretValue unsafePlainText(String secret)public static SecretValue UnsafePlainText(string secret)func UnsafePlainText(Secret *string) SecretValuestatic#
Construct a literal secret value for use with secret-aware constructs.
notes · example

Do not use this method for any secrets that you care about! The value will be visible to anyone who has access to the CloudFormation template (via the AWS Console, SDKs, or CLI).

The primary use case for using this method is when you are testing.

The other use case where this is appropriate is when constructing a JSON secret. For example, a JSON secret might have multiple fields where only some are actual secret values.

ts
declare const secret: SecretValue;
const jsonSecret = {
  username: SecretValue.unsafePlainText('myUsername'),
  password: secret,
};
unsafeUnwrap(): stringdef unsafe_unwrap(self, ) -> strpublic String unsafeUnwrap()public string UnsafeUnwrap()func UnsafeUnwrap() *string#
Disable usage protection on this secret.
notes

Call this to indicate that you want to use the secret value held by this object in an unchecked way. If you don't call this method, using the secret value directly in a string context or as a property value somewhere will produce an error.

This method has 'unsafe' in the name on purpose! Make sure that the construct property you are using the returned value in is does not end up in a place in your AWS infrastructure where it could be read by anyone unexpected.

When in doubt, don't call this method and only pass the object to constructs that accept SecretValue parameters.