Pass AWS SM Secret Key to Lambda Environment with CDK

Issue

I am having some trouble getting a specific Secrets Manager Secret key value to pass it to my lambda through CDK.

After some time I finally realized that my SecretValue is only resolved when I actually deploy this to lambda, and not while running local through SAM CLI.
By doing

cdk.SecretValue.secretsManager(secretId).toString()

I get something like "{\"apiKey\":\"sdfsdf-sdfsdf-sddsf\"}", but I want to rather have the apiKey directly.
Unfortunately, in my CDK code, I cannot JSON:parse(...secretsManager(..).toString()) as this will only be resolved once deployed. Before, the value is simply:
{{resolve:secretsmanager:apiKey:SecretString:::}} (which seems to be a Token: https://docs.aws.amazon.com/cdk/latest/guide/tokens.html)

So I guess I would need some way to tell CDK how to use the rendered value, maybe by passing a callback that transforms the rendered result – is that possible?
Are there any other tools I can use in my CDK setup that allow me to receive a specific key from a secret so that I can pass it to lambda directly?

I hope the problem is understandable. Thanks in advance for your help.

Solution

You need to use Secret. You can use any of the static from methods to get the secret. From there you can use the secretValueFromJson method to get the value.

Example (secret for Postgres db):

    import * as secretsmanager from '@aws-cdk/aws-secretsmanager';

    const dbSecret = secretsmanager.Secret.fromSecretNameV2(this, 'db-secret', 'db-secret-name');
    const dbUser = dbSecret.secretValueFromJson('username').toString();
    const dbPass = dbSecret.secretValueFromJson('password').toString();
    const dbName = dbSecret.secretValueFromJson('dbname').toString();

Answered By – Jason Wadsworth

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.