aws-cdk

aws_secretsmanager: Secret Value is not correct. How does this work?


I want to create a new secret via cdk. It seems that I don't understand it...

Python code:

foo = secretsmanager.Secret(
        self,
        "foo",
        generate_secret_string=secretsmanager.SecretStringGenerator(
            secret_string_template=json.dumps({'bar':'xyz'}),
            generate_string_key="bar"
        ),
)

In "cdk synth" everything looks correct:

foo6445C170:
Type: AWS::SecretsManager::Secret
Properties:
  GenerateSecretString:
    GenerateStringKey: bar
    SecretStringTemplate: '{"bar": "xyz"}'
UpdateReplacePolicy: Delete
DeletionPolicy: Delete
Metadata:
  aws:cdk:path: MyStack/foo/Resource

The value in the newly created secret looks like this:

enter image description here

What I'm doing wrong?


Solution

  • This is the expected behavior. generate_secret_string is for specifying how you want a random string to be generated for the secret.

    Here are the docs for the secret_string_template field:

    The generateStringKey is combined with the generated random string and inserted into the JSON structure that's specified by this parameter. The merged JSON string is returned as the completed SecretString of the secret. If you specify secretStringTemplate then generateStringKey must be also be specified.

    In other words, the JSON object you specify is just a template where the generated random string will be inserted. The value for the field you specify via generate_string_key will be replaced by the randomly generated string. The value from your template is discarded.

    You can specify the literal value if you absolutely want to via the secret_object_value prop:

    foo = secretsmanager.Secret(
        self,
        "foo",
        secret_object_value={
            # DO NOT DO THIS
            "bar": cdk.SecretValue.unsafe_plain_text("xyz")
        },
    )
    

    You should not do this, though - it defeats the purpose. Here is a note from the docs:

    *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).