# Credentials

Username and password combination.

Obtainable from: Credentials.fromGeneratedSecret, Credentials.fromPassword, Credentials.fromSecret, Credentials.fromUsername

- Source: [`aws-rds/lib/props.ts`](https://github.com/aws/aws-cdk/blob/v2.278.0/packages/aws-cdk-lib/aws-rds/lib/props.ts#L197)
- Type last changed: v2.72.0 · 29 Mar 2023

## Example

TypeScript:

```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:

```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:

```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();
```

C# / .NET:

```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
});
```

Golang:

```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

TypeScript:

```ts
new Credentials()
```

Python:

```python
Credentials()
```

Java:

```java
new Credentials()
```

C# / .NET:

```csharp
new Credentials()
```

Golang:

```go
NewCredentials()
```

## Properties

- `encryptionKey`: [IKey](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_kms.IKey.html) — KMS encryption key to encrypt the generated secret.

  **Default:** default master key

- `excludeCharacters`: string — The characters to exclude from the generated password.

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

  Only used if `password` has not been set.

- `password`: [SecretValue](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.SecretValue.html) — Password.

  **Default:** a Secrets Manager generated password

  Do not put passwords in your CDK code directly.

- `replicaRegions`: [ReplicaRegion](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_secretsmanager.ReplicaRegion.html)[] — A list of regions where to replicate the generated secret.

  **Default:** Secret is not replicated

- `secret`: [ISecret](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_secretsmanager.ISecret.html) = none — Secret used to instantiate this Login.

- `secretName`: 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.

- `username`: string — Username.

- `usernameAsString`: boolean = 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` (static) — Creates Credentials with a password generated and stored in Secrets Manager.

- `fromPassword(username: string, password: SecretValue): Credentials // chainable` (static) — Creates Credentials from a password.

  Do not put passwords in your CDK code directly.

- `fromSecret(secret: ISecret, username?: string): Credentials // chainable` (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>,
  }
  ```

  **Parameters**

  - `secret` — The secret where the credentials are stored.
  - `username` — The username defined in the secret.

- `fromUsername(username: string, options?: CredentialsFromUsernameOptions): Credentials // chainable` (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.
