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
gefragt vor 2 Jahren2038 Aufrufe
1 Antwort
1
Akzeptierte Antwort

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
beantwortet vor 2 Jahren
  • 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.

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen