typescriptamazon-ecsaws-cdkaws-event-bridge

AWS CDK EventBridge ECS task cannot assign public IP address even though subnet is public


I'm creating a ECS task to run when triggered by an EventBridge event, but I cannot assign a public IP address to the task, which is required to access ECS to get the task. The VPC I'm using only has public subnets.

This is the relevant code:

const cluster = new ecs.Cluster(this, "default-cluster", {
  vpc,
  clusterName: `xxxxx`,
  enableFargateCapacityProviders: true,
});

const taskDefinition = new ecs.FargateTaskDefinition(
  this,
  `${process.type}-task`,
  {
    memoryLimitMiB: 512,
    cpu: 256,
    runtimePlatform: {
      cpuArchitecture: ecs.CpuArchitecture.X86_64,
      operatingSystemFamily: ecs.OperatingSystemFamily.LINUX,
    },
  }
);

taskDefinition
  .addContainer(`xxxxxxxx`, {
    image: ecs.ContainerImage.fromEcrRepository(repo, props.imageTag),
    containerName: `xxxxxx`,
  })
  .addPortMappings({
    containerPort: 3000,
  });

const releaseTask = new eventBridgeTargets.EcsTask({
  cluster,
  taskDefinition,
  taskCount: 1,
  launchType: ecs.LaunchType.FARGATE,
  subnetSelection: vpc.selectSubnets({
    subnetType: SubnetType.PUBLIC,
  }),
  assignPublicIp: true,
});

The error I receive is: Error: assignPublicIp should be set to true only for PUBLIC subnets

What am I doing wrong?


Solution

  • The subnetSelection prop expects a SubnetSelection object, and you are passing in the result of the Vpc.selectSubets function, which takes a SubnetSelection and returns an instance of SelectedSubnets.

    Instead, pass the SubnetSelection object directly:

    subnetSelection: {
        subnetType: SubnetType.PUBLIC,
    },
    

    I would suggest configuring your IDE / language server properly - it should highlight type errors such as this one for you.