如何在AWS CDK中检索SecretsManager机密

时间:2020-08-27 13:44:48

标签: amazon-web-services aws-cdk aws-secrets-manager

我正在使用CDK在AWS中设置Fargate服务

const albFargateService = new ecs_patterns.ApplicationLoadBalancedFargateService(
    this,
    'FargateService',
    {
        vpc: ...,
        taskImageOptions: {
            image: ...,
            containerPort: ...,
            secrets: {
                MY_ENV_VAR: Secret.fromSecretsManager(
                    **ISecret**,
                    'fieldWithinTheSecret'
                ),
            }
        }
    }
)

在给出秘密名称的情况下,我应该如何掌握 ISecret 实例?

我已经从AWS开发工具包中查看了AWS.SecretsManager,但它仅返回字符串。

1 个答案:

答案 0 :(得分:1)

当前没有Secret.fromSecretName方法。假设您使用的是现有机密,则应使用Secret.fromSecretArn方法。

请注意,如果您使用KMS密钥,则应使用Get a value from AWS secrets manager中所述的Secret.fromSecretAttributes方法。

import * as ecs from "@aws-cdk/aws-ecs";
import * as ecs_patterns from "@aws-cdk/aws-ecs-patterns";
import * as secretsmanager from "@aws-cdk/aws-secretsmanager";

const mySecret = secretsmanager.Secret.fromSecretArn(this, "mySecret", "arn:aws:secretsmanager:<region>:<account-id-number>:secret:<secret-name>-<random-6-characters>");

const albFargateService = new ecs_patterns.ApplicationLoadBalancedFargateService(
    this,
    'FargateService',
    {
        vpc: ...,
        taskImageOptions: {
            image: ...,
            containerPort: ...,
            secrets: {
                MY_ENV_VAR: ecs.Secret.fromSecretsManager(mySecret),
            }
        }
    }
);