Skip to content

Instantly share code, notes, and snippets.

@markilott
Created July 18, 2021 09:20
Show Gist options
  • Save markilott/7529b7c4b19d8acd0207252e27cbec94 to your computer and use it in GitHub Desktop.
Save markilott/7529b7c4b19d8acd0207252e27cbec94 to your computer and use it in GitHub Desktop.
CDK - Lambda Function to start/stop ECS services
// In the Scheduler Stack ===========================================
// Lambda Function to start/stop tasks
const ecsScheduleFnc = new Function(this, 'ecsScheduleFnc', {
description: 'Lambda ECS Service Mgt Function',
functionName: 'ecsScheduleFnc',
runtime: Runtime.NODEJS_14_X,
handler: 'index.handler',
timeout: Duration.seconds(5),
code: Code.fromAsset(`${__dirname}/lambda/manage-task`),
});
// IAM Policy to allow access to ECS Services from Lambda
ecsScheduleFnc.addToRolePolicy(new iam.PolicyStatement({
sid: 'ECSServices',
resources: ['*'],
actions: [
'ecs:ListServices',
'ecs:ListClusters',
],
}));
// IAM Policy to allow Start/Stop of the demo services
ecsScheduleFnc.addToRolePolicy(new iam.PolicyStatement({
sid: 'DemoApp',
// Allow access to all ECS tasks - not production ready
// Alternatives include using Tags or prefixes, or moving this policy add to the app stacks themselves
resources: ['*'],
actions: [
'ecs:UpdateService',
'ecs:DescribeServices',
],
}));
// In the Application Stack =====================================
// Lambda target config
const params = {
clusterArn: cluster.clusterArn,
serviceName: service.serviceName,
};
// Schedule Rules
params.active = true; // Start
const mgtTarget = new LambdaFunction(ecsScheduleFnc, {
event: RuleTargetInput.fromObject({ params }),
retryAttempts: 3,
});
const startRule = new Rule(this, 'startRule', {
description: 'Start ECS Task',
schedule: Schedule.expression(`cron('0 2 ? * MON-FRI *')`), // UTC, seconds not supported
});
startRule.addTarget(mgtTarget);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment