Search code examples
amazon-web-servicesaws-cdkaws-secrets-manager

How to retrieve SecretsManager secret in AWS CDK


I'm setting up a Fargate service in AWS using CDK

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

How am I supposed to get hold of the ISecret instance given the name of the secret?

I've looked at the AWS.SecretsManager from the AWS SDK, but it only returns strings.


Solution

  • Currently there is no Secret.fromSecretName-method. Assuming that you are using an existing secret, you should use the Secret.fromSecretArn-method.

    Note that if you use a KMS key, you should use the Secret.fromSecretAttributes-method as described at Get a value from AWS secrets manager.

    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),
                }
            }
        }
    );