Search code examples
amazon-web-servicesterraformamazon-ecsterraform-provider-awsamazon-vpc

Attach existing VPC while creating an ECS cluster


When I create an ECS cluster on the AWS UI, I have the option to select a VPC. But how do I select or attach an existing VPC while creating a cluster using Terraform?

resource "aws_ecs_cluster" "gtm" {
  name = "gtm"
  setting {
    name  = "containerInsights"
    value = "enabled"
  }
}

Solution

  • As @Mark mentioned, it is ECS service level. network_configuration.subnets helps to attach subnet. In the Terraform registry page (in Mark's link), there is no explicit sample for network configuration, so I added it below.

    Sample Code:

    resource "aws_ecs_service" "ecs_service" {
     name            = "my-ecs-service"
     cluster         = aws_ecs_cluster.gtm.id
     task_definition = aws_ecs_task_definition.ecs_task_definition.arn
    
     network_configuration {
       subnets         = [aws_subnet.subnet.id]
       security_groups = [aws_security_group.security_group.id]
     }
     ...
    }