Skip to content

Instantly share code, notes, and snippets.

@michaelfecher
Created July 25, 2020 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelfecher/1ea2b3399a67c751ea6781d4c0e7d924 to your computer and use it in GitHub Desktop.
Save michaelfecher/1ea2b3399a67c751ea6781d4c0e7d924 to your computer and use it in GitHub Desktop.
Blogpost: ECS Fargate with passing secrets - ECS Fargate Task Definition
// 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