创建ecs.LoadBalancedFargateService时如何指定子网

时间:2019-03-25 10:51:09

标签: aws-cdk

我正在尝试在现有VPC上创建Fargate ECS服务,但是在运行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;

已正确导入vpc,并且根据cloudformation日志成功创建了ecs集群。创建负载均衡器时会发生故障

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),
    })

我希望负载均衡器能够使用VPC定义中指定的子网,但这似乎没有发生。 我是否需要在LoadBalancedFargateService定义中的某处定义要使用的子网?

1 个答案:

答案 0 :(得分:1)

默认情况下,LoadBalancedFargateService创建一个面向Internet的应用程序负载平衡器,但您未在导入中指定公共子网。

此外,在导入VPC时,privateSubnetIds / publicSubnetIds必须在长度和顺序上完全匹配可用区。

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']
});

另一种解决方案是使用importFromContext,它将进行API调用以收集有关您的VPC的正确信息:

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