Skip to content

Instantly share code, notes, and snippets.

Embed
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;
this.id = 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(addon.name)) {
throw new Error(`The addon ${addon.name} has already been added`);
}
this.addons.set(addon.name, 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) {
addon.addHooks();
}
});
// Give each addon a chance to mutate the task def creation properties
this.addons.forEach((addon) => {
if (addon.mutateTaskDefinitionProps) {
addon.mutateTaskDefinitionProps(taskDefProps)
}
});
// Now that the task definition properties are assembled, create it
this.taskDefinition = new ecs.Ec2TaskDefinition(this.scope, `${this.id}-task-definition`, taskDefProps);
// Now give each addon a chance to use the task definition
this.addons.forEach((addon) => {
if (addon.useTaskDefinition) {
addon.useTaskDefinition(this.taskDefinition);
}
});
// Now that all containers are created, give each addon a chance
// to bake its dependency graph
this.addons.forEach((addon) => {
if (addon.bakeContainerDependencies) {
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) {
addon.mutateServiceProps(serviceProps)
}
});
// Now that the service props are determined we can create
// the service
this.service = new ecs.Ec2Service(this.scope, `${this.id}-service`, serviceProps);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment