Blogpost: ECS Fargate with passing secrets - ECS Fargate Task Definition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// file: lib/backend-task-stack.ts | |
import * as cdk from "@aws-cdk/core"; | |
import * as ecs from "@aws-cdk/aws-ecs"; | |
import * as iam from "@aws-cdk/aws-iam"; | |
import * as ecr from "@aws-cdk/aws-ecr"; | |
import { DBCredentials } from "./db-credentials-stack"; | |
export interface BackendStackProps extends cdk.StackProps { | |
backendPort: number; | |
dbEndpoint: string; | |
dbCredentials: DBCredentials; | |
dbHost: string; | |
dbPort: string; | |
dbName: string; | |
} | |
export class BackendTaskStack extends cdk.Stack { | |
readonly taskDefinition: ecs.TaskDefinition; | |
constructor(scope: cdk.Construct, id: string, props: BackendStackProps) { | |
super(scope, id, props); | |
const usernameSecret = props.dbCredentials.username; | |
const passwordSecret = props.dbCredentials.password; | |
const taskRole = new iam.Role(this, "BackendTaskRole", { | |
roleName: "BackendECSTaskRole", | |
assumedBy: new iam.ServicePrincipal("ecs-tasks.amazonaws.com"), | |
managedPolicies: [ | |
iam.ManagedPolicy.fromAwsManagedPolicyName( | |
"service-role/AmazonECSTaskExecutionRolePolicy" | |
), | |
], | |
}); | |
usernameSecret.grantRead(taskRole); | |
passwordSecret.grantRead(taskRole); | |
const taskDef = new ecs.FargateTaskDefinition(this, "BackendTask", { | |
taskRole: taskRole, | |
}); | |
taskDef.addContainer("BackendContainer", { | |
image: ecs.ContainerImage.fromEcrRepository("yourEcrRepo"), | |
secrets: { | |
DB_USER: ecs.Secret.fromSecretsManager(usernameSecret), | |
DB_PW: ecs.Secret.fromSecretsManager(passwordSecret), | |
}, | |
environment: { | |
NODE_ENV: "production", | |
DB_DIALECT: "postgres", | |
DB_HOST: props.dbHost, | |
DB_PORT: props.dbPort, | |
DB_NAME: props.dbName, | |
}, | |
}); | |
this.taskDefinition = taskDef; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment