Create ECS Cluster

Create ECS Cluster stack

  1. Open your CDK project and create a new stack named ClusterStack.java.

    Step 1

  2. To create the ECS stack, we need the VPC that we previously created. Therefore, we need to create a record class to pass the VPC into the ECS Stack. Add the following code outside the ClusterStack class:

    record ClusterStackProps(Vpc vpc) {}
    

Architect

  1. Create the cluster property and a getter method within the ClusterStack class:

    private final Cluster cluster;
    
    public Cluster getCluster() {
        return cluster;
    }
    

Architect

  1. Create constructor
public ClusterStack(final Construct scope, final String id,
            final StackProps props, ClusterStackProps clusterStackProps) {
        super(scope, id, props);
            }

Architect

  1. Initialize the Cluster object in the constructor of ClusterStack.java using the following code:
       this.cluster = new Cluster(this, "Cluster", ClusterProps.builder()
                .build());

Architect

  1. Set the name of the cluster to ECommerce*
       .clusterName("ECommerce")

Architect

  1. Add VPC to the cluster
.vpc(clusterStackProps.vpc())

Architect

  1. Finally, set containerInsight to true.
       .containerInsights(true)

Architect

Organize ECS stack in CDK project

  1. Open the file named Fcj2024CdkApp in the root directory.

    Architecture

  2. Create an ECS Stack with the ID Vpc using the following code snippet:

ClusterStack clusterStack = new ClusterStack(app, "Cluster", StackProps.builder()
                .build());

Architect

  1. Pass the previously created VPC to the ClusterStackProps of the ECS stack:
   new ClusterStackProps(vpcStack.getVpc())

Architect

  1. Add environment and tags to the ECS Stack:
   .env(environment)
   .tags(infraTags)

Architect

  1. Because ECS requires a VPC but we cannot be certain whether the VPC has been created before the ECS, let’s add a dependency constraint to ensure that the ECS is only created after the VPC has been successfully created:
   clusterStack.addDependency(vpcStack);

Architect

Deploy ECS Cluster using AWS CDK

  1. To deploy the ECS cluster, open your terminal and enter the following commands:
  • Deploy all stacks using:
cdk deploy --all
  • Alternatively, you can skip the confirmation prompt by using:
   cdk deploy --all --require-approval never

Architect

Deploy ECS Cluster using AWS CDK

  1. Check the newly created cluster:

    • Access the AWS console, navigate to ECS, and select Elastic Container Service.

    Architecture

  2. In the ECS interface, you should see a cluster named ECommerce that has been created.

    Architecture