Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
export class Service extends cdk.Construct implements ServiceInterface {
public addons: Map<string, ServiceAddon>;
protected taskDefinition: ecs.Ec2TaskDefinition;
protected service: ecs.Ec2Service;
readonly scope: cdk.Stack;
readonly id: string;
readonly vpc: ec2.Vpc;
readonly cluster: ecs.Cluster;
constructor(scope: cdk.Stack, id: string, props: ServiceProps) {
super(scope, id);
this.scope = scope; = id;
this.vpc = props.vpc;
this.cluster = props.cluster;
this.addons = new Map();
// Add an addon to the service
add(addon: ServiceAddon) {
if (this.addons.get( {
throw new Error(`The addon ${} has already been added`);
this.addons.set(, addon);
if (addon.prehook) {
addon.prehook(this, this.scope);
return this;
// Run all the addon hooks to prepare the final service
prepare() {
var taskDefProps = {};
// At the point of preparation all addons have been defined on the service
// so give each addon a chance to now add hooks to other addons if
// needed
this.addons.forEach((addon) => {
if (addon.addHooks) {
// Give each addon a chance to mutate the task def creation properties
this.addons.forEach((addon) => {
if (addon.mutateTaskDefinitionProps) {
// Now that the task definition properties are assembled, create it
this.taskDefinition = new ecs.Ec2TaskDefinition(this.scope, `${}-task-definition`, taskDefProps);
// Now give each addon a chance to use the task definition
this.addons.forEach((addon) => {
if (addon.useTaskDefinition) {
// Now that all containers are created, give each addon a chance
// to bake its dependency graph
this.addons.forEach((addon) => {
if (addon.bakeContainerDependencies) {
let serviceProps = {
cluster: this.cluster,
taskDefinition: this.taskDefinition
// Give each addon a chance to mutate the service props before
// service creation
this.addons.forEach((addon) => {
if (addon.mutateServiceProps) {
// Now that the service props are determined we can create
// the service
this.service = new ecs.Ec2Service(this.scope, `${}-service`, serviceProps);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment