skip to Main Content

I tried example code from the AWS CDK documentation, but it didn’t work as expected.

CDK version 2.62.2 in Typescript.
Everywhere (this, is standing there is is a declaration error. The argument of type "undefined" cannot be assigned to the parameter of type "Construct".

Code:

import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';

declare const vpc: ec2.Vpc;

// Create an ECS cluster
const cluster = new ecs.Cluster(this, 'Cluster', { vpc });

// Add capacity to it
cluster.addCapacity('DefaultAutoScalingGroupCapacity', {
  instanceType: new ec2.InstanceType("t2.xlarge"),
  desiredCapacity: 3,
});

const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');

taskDefinition.addContainer('DefaultContainer', {
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  memoryLimitMiB: 512,
});

// Instantiate an Amazon ECS Service
const ecsService = new ecs.Ec2Service(this, 'Service', {
  cluster,
  taskDefinition,
});

2

Answers


  1. On the part where you are trying to create a new ecs.Cluster you are passing along an "Undefined" VPC. As you are only declaring the const without setting any value.

    To create a new VPC you should modify the line from:

    declare const vpc: ec2.Vpc;
    

    To something like:

    const vpc = new ec2.Vpc(this, 'TheVPC')
    

    Documentation on this is found at https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.Vpc.html

    Login or Signup to reply.
  2. TL;DR The error is telling you that the this keyword is undefined. Move your instantiation code to a construct subclass constructor.


    A construct’s first argument is its scope, or parent construct. You are right to use the this keyword as the scope, but it is undefined as your code is currently written. The idomatic CDK way to to define constructs is inside the constructor of a construct subclass, typically a Stack. Inside the Stack’s constructor, this will refer to the Stack instance.

    The vpc variable is also undefined in your code. By convention, the CDK docs use Typescript variable declaration statements to keep the examples shorter. Strictly speaking it’s not causing an error, but it’s probably not the behaviour you are expecting. If you don’t want to use the default Vpc which will be created for you if the vpc prop is undefined, you need to instantiate a Vpc rather than just declare the vpc variable.

    class MyStack extends Stack {
      constructor(scope: App, id: string, props?: StackProps) {
        super(scope, id, props);
    
        const vpc = new ec2.Vpc(this, 'Vpc', { maxAzs: 2 });
    
        const cluster = new ecs.Cluster(this, 'Cluster', { vpc });
      }
    }
    

    The aws-samples/aws-cdk-examples repo has several complete working ECS examples for EC2.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search