Avnish Desai
Avnish Desai

Reputation: 1

How to specify subnets when creating an ecs.LoadBalancedFargateService

I am trying to create a Fargate ECS service on an existing VPC but get the following error after running cdk deploy

CREATE_FAILED | AWS::ElasticLoadBalancingV2::LoadBalancer | exms-service/LB (exmsserviceLB259DA1C7) At least two subnets in two different Availability Zones must be specified (Service: AmazonElasticLoadBalancingV2; Status Code: 400; Error Code: ValidationError;

The vpc is imported correctly and the ecs cluster creates successfully according to the cloudformation logs. the failure occurs when the load balanceer is being created

const vpc = ec2.VpcNetwork.import(this, "TB-DEV", {
      vpcId: 'vpc-xxxxxx',
      availabilityZones: ['eu-west-1G', 'eu-west-1b', 'eu-west-1c'],
      privateSubnetIds: ['subnet-xxxxxxx', 'subnet-xxxxx', 'subnet-xxxx', 'subnet-xxxxx', 'subnet-xxxxx', 'subnet-xxxxx']
//this is a list of 1 private and 1 public subnet on each of the specified availability zones
    })

const cluster = new ecs.Cluster(this, "TB-ECS-DEV", {
      clusterName: "TB-DEV",
      vpc: vpc,

    })

const repo = ecr.Repository.import(this, 'EXMS-REPO', {
      repositoryName: "expense-type-mapper-dev"
    })

new ecs.LoadBalancedFargateService(this, "EXMS", {
      cluster: cluster,
      image:ecs.ContainerImage.fromEcrRepository(repo),
    })

I expected the load balancer to make use of the subnets specified in the VPC definition but that does not seem to be happening. Do I need to define which subnets to use somewhere in the LoadBalancedFargateService definition?

Upvotes: 0

Views: 1782

Answers (1)

jogold
jogold

Reputation: 7397

By default the LoadBalancedFargateService creates an internet facing application load balancer but you are not specifying public subnets in your import.

Also, when importing a VPC the privateSubnetIds/publicSubnetIds must exactly match the availability zones in length and order.

const vpc = ec2.VpcNetwork.import(this, "TB-DEV", {
  vpcId: 'vpc-xxxxxx',
  availabilityZones: ['eu-west-1a', 'eu-west-1b', 'eu-west-1c'],
  publicSubnetIds: ['subnet-xxxxx', 'subnet-xxxxx', 'subnet-xxxxx'],
  privateSubnetIds: ['subnet-xxxxxxx', 'subnet-xxxxx', 'subnet-xxxx']
});

Another solution is to use importFromContext which will make an API call to collect the correct information for your VPC:

const vpc = ec2.VpcNetwork.importFromContext(this, "TB-DEV", {
  vpcId: 'vpc-xxxxxx'
});

Upvotes: 1

Related Questions