如何解决使用 ECS + Fargate 在 CDK 堆栈中使用来自 AWS Secrets Manager 的密钥
我使用 TypeScript 定义了一个 CDK 应用程序堆栈(敏感信息在下面的代码中重新定义):
import * as cdk from "@aws-cdk/core";
import * as ec2 from "@aws-cdk/aws-ec2";
import * as ecs from "@aws-cdk/aws-ecs";
import * as ecr from "@aws-cdk/aws-ecr";
import * as ecr_assets from "@aws-cdk/aws-ecr-assets";
import * as ecs_patterns from "@aws-cdk/aws-ecs-patterns";
import * as sm from "@aws-cdk/aws-secretsmanager";
export class CdkAppStack extends cdk.Stack {
constructor(scope: cdk.Construct,id: string,props?: cdk.StackProps) {
super(scope,id,props);
// Create a Docker image and upload it to the Amazon Elastic Container Registry (ECR)
const dockerImage = new ecr_assets.DockerImageAsset(this,"ApiDockerImage",{
directory: "/home/ec2-user/environment/node-test"
});
// Create a new VPC and NAT Gateway
const vpc = new ec2.Vpc(this,"ApiVpc",{
maxAzs: 3 // Default is all AZs in region
});
// Create a new Amazon Elastic Container Service (ECS) cluster
const cluster = new ecs.Cluster(this,"ApiCluster",{
vpc: vpc
});
// Create a load-balanced Fargate service and make it public
new ecs_patterns.ApplicationLoadBalancedFargateService(this,"ApiFargateService",{
cluster: cluster,// Required
cpu: 512,// Default is 256
desiredCount: 2,// Default is 1
taskImageOptions: {
image: ecs.ContainerImage.fromDockerImageAsset(dockerImage),containerPort: 8080,enableLogging: true,secrets: sm.Secret.fromSecretCompleteArn(this,"ImportedSecret","arn:aws:secretsmanager:ap-south-1:762589711820:secret:/api/production/FrOibp")
},memoryLimitMiB: 2048,// Default is 512
publicLoadBalancer: true // Default is false
});
}
}
如果我从 cdk deploy
中删除 secrets
键,但使用 taskImageOptions
时,使用 secrets
部署成功,尝试部署时出现此错误:
ec2-user:~/environment/cdk-app (master) $ cdk deploy
⨯ Unable to compile TypeScript:
lib/cdk-app-stack.ts:42:9 - error TS2322: Type 'ISecret' is not assignable to type '{ [key: string]: Secret; }'.
Index signature is missing in type 'ISecret'.
42 secrets: secret
~~~~~~~
Subprocess exited with error 1
我在尝试使用 Secrets Manager 中的机密时做错了。在 ApplicationLoadBalancedFargateService
中引用机密的正确方法是什么?
解决方法
这里有两个问题:
-
secrets
是索引签名类型。因此,您应该命名您的秘密(这是将在您的容器中公开的环境变量) - 需要
ecs.Secret
(您可以从sm.Secret
创建)
这是一个工作版本:
new ecs_patterns.ApplicationLoadBalancedFargateService(this,"ApiFargateService",{
cluster: cluster,// Required
cpu: 512,// Default is 256
desiredCount: 2,// Default is 1
taskImageOptions: {
image: ecs.ContainerImage.fromDockerImageAsset(dockerImage),containerPort: 8080,enableLogging: true,secrets: {
"MY_SECRET": ecs.Secret.fromSecretsManager( sm.Secret.fromSecretCompleteArn(this,"ImportedSecret","arn:aws:secretsmanager:ap-south-1:762589711820:secret:/api/production/FrOibp"))
}
},memoryLimitMiB: 2048,// Default is 512
publicLoadBalancer: true // Default is false
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。