How to pass ARN of DB credentials stored in secret manager to Lambda in CDK?

1

In CDK stack, I create DB credential as

    const credentials = aws_rds.Credentials.fromGeneratedSecret(
      "mysqlSecret",
      {
        secretName: props.secretName,
      }
    );

Then how to get the ARN of the secret and pass to environment variable of a Lambda function?

aws_lambda.Function({
   environment: {
    "SECRET_ARN": ??? 
}
})

What is the best practice here? I store DB credentials in secret manager, but how to pass it to Lambda construct in CDK?

hai
asked 2 years ago2000 views
1 Answer
1
Accepted Answer

This method worked well for creating RDS.

    const cred = aws_rds.Credentials.fromGeneratedSecret('mysqlSecret2', {
      secretName: 'mysql-secret2'
    })

    const rds = new aws_rds.DatabaseInstance(this, 'rds', {
      vpc: new aws_ec2.Vpc(this, 'vpc'),
      engine: aws_rds.DatabaseInstanceEngine.MARIADB,
      instanceType: aws_ec2.InstanceType.of(aws_ec2.InstanceClass.T3, aws_ec2.InstanceSize.SMALL),
      credentials: cred
    })

    new aws_lambda.Function(this, 'lambd2', {
      environment: {
        "SECRET_ARN": rds.secret!.secretArn
      },
      code: aws_lambda.Code.fromInline('print()'),
      runtime: aws_lambda.Runtime.PYTHON_3_9,
      handler: 'app.handler'
    })

If you are not creating an RDS, using aws_secretsmanager.Secret instead of aws_rds.Credentials.fromGeneratedSecret worked.

    const secret = new aws_secretsmanager.Secret(this, 'secret', {
      secretName: 'mysql-secret',
      generateSecretString: {
        secretStringTemplate: JSON.stringify({ username: 'user' }),
        generateStringKey: 'password',
      },
    })

    new aws_lambda.Function(this, 'lambda', {
      environment: {
        "SECRET_ARN": secret.secretArn
      },
      code: aws_lambda.Code.fromInline('print()'),
      runtime: aws_lambda.Runtime.PYTHON_3_9,
      handler: 'app.handler'
    })

I would be very happy if you could ACCEPTE ANSWER when you solve the problem😀😀😀

profile picture
answered 2 years ago
  • Thank you! it works for me.

    In addition, when I create the secret (your second method) then pass into RDS, I got an error from CDK. Can't recall it.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions