Home > Blockchain >  How to run a Fargate Task on an existing ecs cluster using aws cdk
How to run a Fargate Task on an existing ecs cluster using aws cdk

Time:10-25

I have an ECS cluster that will be created by my cdk stack. Before my ECS service stack deployment I have to run a fargate task to generate the build files and configs for my application. I want to run a standalone task inside an existing Ecs cluster.

CodePudding user response:

There are two questions. I Will try to answer both:

  1. First of all you need to run the Fargate task via CDK

you need to create a Rule which runs your ECS task by schedule (or some else event)

import { Rule, Schedule } from '@aws-cdk/aws-events';
import { EcsTask } from '@aws-cdk/aws-events-targets';

new Rule(this, 'ScheduleRule', {
        schedule: schedule,
        targets: [
          new EcsTask({
            cluster,
            taskDefinition: task,
          }),
        ],
      });
  1. Second one - how I can use the existing cluster

you can find your cluster by attributes

import { Cluster } from '@aws-cdk/aws-ecs';

let cluster = Cluster.fromClusterAttributes(this, 'cluster_id', {
     clusterName: "CLUSTER_NAME", securityGroups: [], vpc: iVpc
 });

update: you can trigger you task via some custom event:

 new Rule(this, 'EventPatternRule', {
         eventPattern: {
             "version": "0",
             "id": "CWE-event-id",
             "detail-type": "CodePipeline Pipeline Execution State Change",
             "source": "aws.codepipeline",
             "account": "123456789012",
             "time": "2017-04-22T03:31:47Z",
             "region": "us-east-1",
             "resources": [
                 "arn:aws:codepipeline:us-east-1:123456789012:pipeline:myPipeline"
             ],
             "detail": {
                 "pipeline": "myPipeline",
                 "version": "1",
                 "state": "STARTED",
                 "execution-id": "01234567-0123-0123-0123-012345678901"
             }
         }
         targets: [
           new EcsTask({
             cluster,
             taskDefinition: task,
           }),
         ],
       });

please, see this doc for the understanding of Event Patterns

  • Related