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
質問済み 2年前2037ビュー
1回答
1
承認された回答

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
回答済み 2年前
  • 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.

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン