cdk-fargate-run-task
Define and run container tasks on AWS Fargate at once or by schedule.
sample
const app = new cdk.App();
const env = {
account: process.env.CDK_DEFAULT_ACCOUNT,
region: process.env.CDK_DEFAULT_REGION,
};
const stack = new cdk.Stack(app, 'run-task-demo-stack', { env });
const task = new ecs.FargateTaskDefinition(stack, 'Task', { cpu: 256, memoryLimitMiB: 512 });
task.addContainer('Ping', {
image: ecs.ContainerImage.fromRegistry('busybox'),
command: [
'sh', '-c',
'ping -c 3 google.com',
],
logging: new ecs.AwsLogDriver({
streamPrefix: 'Ping',
logGroup: new LogGroup(stack, 'LogGroup', {
logGroupName: `${stack.stackName}LogGroup`,
retention: RetentionDays.ONE_DAY,
}),
}),
});
const runTaskAtOnce = new RunTask(stack, 'RunDemoTaskOnce', { task });
new RunTask(stack, 'RunDemoTaskEveryHour', {
task,
cluster: runTaskAtOnce.cluster,
runOnce: false,
schedule: Schedule.cron({ minute: '0' }),
});
Public Subnets only VPC
To run task in public subnets only VPC:
new RunTask(stack, 'RunTask', {
task,
vpcSubnets: {
subnetType: ec2.SubnetType.PUBLIC,
},
ECS Anywhere
Amazon ECS Anywhere allows you to run ECS tasks on external instances. To run external task once or on schedule:
const externalTask = new ecs.TaskDefinition(stack, 'ExternalTask', {
cpu: '256',
memoryMiB: '512',
compatibility: ecs.Compatibility.EXTERNAL,
});
externalTask.addContainer('ExternalPing', {
image: ecs.ContainerImage.fromRegistry('busybox'),
command: [
'sh', '-c',
'ping -c 3 google.com',
],
logging: new ecs.AwsLogDriver({
streamPrefix: 'Ping',
logGroup: new LogGroup(stack, 'ExternalLogGroup', {
retention: RetentionDays.ONE_DAY,
removalPolicy: cdk.RemovalPolicy.DESTROY,
}),
}),
});
new RunTask(stack, 'RunDemoTaskFromExternal', {
task: externalTask,
cluster: existingCluster,
launchType: LaunchType.EXTERNAL,
});
new RunTask(stack, 'RunDemoTaskFromExternalSchedule', {
task: externalTask,
cluster: existingCluster,
launchType: LaunchType.EXTERNAL,
runAtOnce: false,
schedule: Schedule.cron({ minute: '0' }),
});
Please note when you run task in EXTERNAL
launch type, no fargate tasks will be scheduled. You will be responsible to register the external instances to your ECS cluster. See Registering an external instance to a cluster for more details.