Skip to content
v2.278.0

Credentials Class ​

Username and password combination.

Example ​

ts
declare const vpc: ec2.IVpc;

const instance1 = new rds.DatabaseInstance(this, "PostgresInstance1", {
  engine: rds.DatabaseInstanceEngine.POSTGRES,
  // Generate the secret with admin username `postgres` and random password
  credentials: rds.Credentials.fromGeneratedSecret('postgres'),
  vpc
});
// Templated secret with username and password fields
const templatedSecret = new secretsmanager.Secret(this, 'TemplatedSecret', {
  generateSecretString: {
    secretStringTemplate: JSON.stringify({ username: 'postgres' }),
    generateStringKey: 'password',
    excludeCharacters: '/@"',
  },
});
// Using the templated secret as credentials
const instance2 = new rds.DatabaseInstance(this, "PostgresInstance2", {
  engine: rds.DatabaseInstanceEngine.POSTGRES,
  credentials: {
    username: templatedSecret.secretValueFromJson('username').toString(),
    password: templatedSecret.secretValueFromJson('password')
  },
  vpc
});
python
# vpc: ec2.IVpc


instance1 = rds.DatabaseInstance(self, "PostgresInstance1",
    engine=rds.DatabaseInstanceEngine.POSTGRES,
    # Generate the secret with admin username `postgres` and random password
    credentials=rds.Credentials.from_generated_secret("postgres"),
    vpc=vpc
)
# Templated secret with username and password fields
templated_secret = secretsmanager.Secret(self, "TemplatedSecret",
    generate_secret_string=secretsmanager.SecretStringGenerator(
        secret_string_template=JSON.stringify({"username": "postgres"}),
        generate_string_key="password",
        exclude_characters="/@\""
    )
)
# Using the templated secret as credentials
instance2 = rds.DatabaseInstance(self, "PostgresInstance2",
    engine=rds.DatabaseInstanceEngine.POSTGRES,
    credentials={
        "username": templated_secret.secret_value_from_json("username").to_string(),
        "password": templated_secret.secret_value_from_json("password")
    },
    vpc=vpc
)
java
IVpc vpc;


DatabaseInstance instance1 = DatabaseInstance.Builder.create(this, "PostgresInstance1")
        .engine(DatabaseInstanceEngine.POSTGRES)
        // Generate the secret with admin username `postgres` and random password
        .credentials(Credentials.fromGeneratedSecret("postgres"))
        .vpc(vpc)
        .build();
// Templated secret with username and password fields
Secret templatedSecret = Secret.Builder.create(this, "TemplatedSecret")
        .generateSecretString(SecretStringGenerator.builder()
                .secretStringTemplate(JSON.stringify(Map.of("username", "postgres")))
                .generateStringKey("password")
                .excludeCharacters("/@\"")
                .build())
        .build();
// Using the templated secret as credentials
DatabaseInstance instance2 = DatabaseInstance.Builder.create(this, "PostgresInstance2")
        .engine(DatabaseInstanceEngine.POSTGRES)
        .credentials(Map.of(
                "username", templatedSecret.secretValueFromJson("username").toString(),
                "password", templatedSecret.secretValueFromJson("password")))
        .vpc(vpc)
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
IVpc vpc;


var instance1 = new DatabaseInstance(this, "PostgresInstance1", new DatabaseInstanceProps {
    Engine = DatabaseInstanceEngine.POSTGRES,
    // Generate the secret with admin username `postgres` and random password
    Credentials = Credentials.FromGeneratedSecret("postgres"),
    Vpc = vpc
});
// Templated secret with username and password fields
var templatedSecret = new Secret(this, "TemplatedSecret", new SecretProps {
    GenerateSecretString = new SecretStringGenerator {
        SecretStringTemplate = JSON.Stringify(new Dictionary<string, string> { { "username", "postgres" } }),
        GenerateStringKey = "password",
        ExcludeCharacters = "/@\""
    }
});
// Using the templated secret as credentials
var instance2 = new DatabaseInstance(this, "PostgresInstance2", new DatabaseInstanceProps {
    Engine = DatabaseInstanceEngine.POSTGRES,
    Credentials = new Dictionary<string, object> {
        { "username", templatedSecret.SecretValueFromJson("username").ToString() },
        { "password", templatedSecret.SecretValueFromJson("password") }
    },
    Vpc = vpc
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
var vpc IVpc


instance1 := rds.NewDatabaseInstance(this, jsii.String("PostgresInstance1"), &DatabaseInstanceProps{
	Engine: rds.DatabaseInstanceEngine_POSTGRES(),
	// Generate the secret with admin username `postgres` and random password
	Credentials: rds.Credentials_FromGeneratedSecret(jsii.String("postgres")),
	Vpc: Vpc,
})
// Templated secret with username and password fields
templatedSecret := secretsmanager.NewSecret(this, jsii.String("TemplatedSecret"), &SecretProps{
	GenerateSecretString: &SecretStringGenerator{
		SecretStringTemplate: jSON.stringify(map[string]*string{
			"username": jsii.String("postgres"),
		}),
		GenerateStringKey: jsii.String("password"),
		ExcludeCharacters: jsii.String("/@\""),
	},
})
// Using the templated secret as credentials
instance2 := rds.NewDatabaseInstance(this, jsii.String("PostgresInstance2"), &DatabaseInstanceProps{
	Engine: rds.DatabaseInstanceEngine_POSTGRES(),
	Credentials: map[string]interface{}{
		"username": templatedSecret.secretValueFromJson(jsii.String("username")).toString(),
		"password": templatedSecret.secretValueFromJson(jsii.String("password")),
	},
	Vpc: Vpc,
})

Initializer ​

ts
new Credentials()
python
Credentials()
java
new Credentials()
csharp
new Credentials()
go
NewCredentials()

Properties ​

encryptionKeymay be undefinedIKeyencryption_keymay be undefinedIKeyencryptionKeymay be undefinedIKeyEncryptionKeymay be undefinedIKeyEncryptionKeymay be undefinedIKey #
KMS encryption key to encrypt the generated secret.

Default: default master key

excludeCharactersmay be undefinedstringexclude_charactersmay be undefinedstrexcludeCharactersmay be undefinedStringExcludeCharactersmay be undefinedstringExcludeCharactersmay be undefined*string #
The characters to exclude from the generated password.

Default: the DatabaseSecret default exclude character set (" %+~`#$&*()|[]{}:;<>?!'/@"\")

Only used if password has not been set.

passwordmay be undefinedSecretValuepasswordmay be undefinedSecretValuepasswordmay be undefinedSecretValuePasswordmay be undefinedSecretValuePasswordmay be undefinedSecretValue #
Password.

Default: a Secrets Manager generated password

Do not put passwords in your CDK code directly.

replicaRegionsmay be undefinedReplicaRegion[]replica_regionsmay be undefinedtyping.List[ReplicaRegion]replicaRegionsmay be undefinedList<ReplicaRegion>ReplicaRegionsmay be undefinedReplicaRegion[]ReplicaRegionsmay be undefined*[]ReplicaRegion #
A list of regions where to replicate the generated secret.

Default: Secret is not replicated

secretmay be undefinedISecretsecretmay be undefinedISecretsecretmay be undefinedISecretSecretmay be undefinedISecretSecretmay be undefinedISecret = none #
Secret used to instantiate this Login.
secretNamemay be undefinedstringsecret_namemay be undefinedstrsecretNamemay be undefinedStringSecretNamemay be undefinedstringSecretNamemay be undefined*string #
The name to use for the Secret if a new Secret is to be generated in SecretsManager for these Credentials.

Default: A name is generated by CloudFormation.

usernamestringusernamestrusernameStringUsernamestringUsername*string #
Username.
usernameAsStringmay be undefinedbooleanusername_as_stringmay be undefinedboolusernameAsStringmay be undefinedBooleanUsernameAsStringmay be undefinedboolUsernameAsStringmay be undefined*bool = false #
Whether the username should be referenced as a string and not as a dynamic reference to the username in the secret.

Methods ​

fromGeneratedSecret(username: string, options?: CredentialsBaseOptions): Credentials // chainable@staticmethod def from_generated_secret(username: str, options: typing.Optional[CredentialsBaseOptions] = None) -> Credentialspublic static Credentials fromGeneratedSecret(String username, CredentialsBaseOptions options)public static Credentials FromGeneratedSecret(string username, CredentialsBaseOptions? options = null)func FromGeneratedSecret(Username *string, Options CredentialsBaseOptions) Credentials static #
Creates Credentials with a password generated and stored in Secrets Manager.
fromPassword(username: string, password: SecretValue): Credentials // chainable@staticmethod def from_password(username: str, password: SecretValue) -> Credentialspublic static Credentials fromPassword(String username, SecretValue password)public static Credentials FromPassword(string username, SecretValue password)func FromPassword(Username *string, Password SecretValue) Credentials static #
Creates Credentials from a password.

Do not put passwords in your CDK code directly.

fromSecret(secret: ISecret, username?: string): Credentials // chainable@staticmethod def from_secret(secret: ISecret, username: typing.Optional[str] = None) -> Credentialspublic static Credentials fromSecret(ISecret secret, String username)public static Credentials FromSecret(ISecret secret, string? username = null)func FromSecret(Secret ISecret, Username *string) Credentials static #
Creates Credentials from an existing Secrets Manager ``Secret`` (or ``DatabaseSecret``).

The Secret must be a JSON string with a username and password field:

{
  ...
  "username": <required: username>,
  "password": <required: password>,
}
2 parameters

Parameters

  • secretsecretsecretsecretSecret — The secret where the credentials are stored.
  • usernameusernameusernameusernameUsername — The username defined in the secret.
fromUsername(username: string, options?: CredentialsFromUsernameOptions): Credentials // chainable@staticmethod def from_username(username: str, options: typing.Optional[CredentialsFromUsernameOptions] = None) -> Credentialspublic static Credentials fromUsername(String username, CredentialsFromUsernameOptions options)public static Credentials FromUsername(string username, CredentialsFromUsernameOptions? options = null)func FromUsername(Username *string, Options CredentialsFromUsernameOptions) Credentials static #
Creates Credentials for the given username, and optional password and key.

If no password is provided, one will be generated and stored in Secrets Manager.