'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 1:[1]
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),
}
}
}
);
Solution 2:[2]
The updated one with CDK version 2
You can refer to a secret either with Secret.fromSecretNameV2()
and retrieve a particular secret value using Secret.secretValueFromJson('keyname').toString();
Refer to the code snippet below
const appSecret = Secret.fromSecretNameV2(this,'app-secret',"secret-name");
const value1 = appSecret.secretValueFromJson('KeyName1').toString();
const value2 = appSecret.secretValueFromJson('KeyName2').toString();
The best thing is, you can use this secret value anywhere like Cognito Secrets, and it will not hardcode the secret value in your cloud formation stack. Instead, it will use a token and it will be resolved to the value when it is deployed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Abinash |