如何在CDK中将存储在 Secrets Manager 中的数据库凭据的ARN传递给Lambda?

0

【以下的问题经过翻译处理】 在CDK堆栈中,我创建了数据库凭据如下

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

那么如何获取密钥的ARN并将其传递到Lambda函数的环境变量中?

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

这里有什么最佳实践?我将数据库凭证存储在 Secrets Manager中,但是如何在CDK中将其传递给Lambda函数?

profile picture
전문가
질문됨 2년 전48회 조회
1개 답변
0

【以下的回答经过翻译处理】 这种方法在创建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'
    })

如果您不创建RDS,请使用aws_secretsmanager.Secret代替aws_rds.Credentials.fromGeneratedSecret。

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'
    })

如果你解决了问题并点击采纳答案,我将非常高兴

profile picture
전문가
답변함 2년 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인