Search code examples
amazon-web-servicesterraformamazon-ecs

How to create an ec2 instance through terraform in my case?


I am trying to create ec2 instance through auto_scaling_group on terraform

I have something like:

resource "aws_ecs_cluster" "my_cluster" {
    name = "my-cluster"
}

resource "aws_autoscaling_group" "my_instances" {
    name = "my-instances"

    min_size = 1
    max_size = 2
    availability_zones = ["us-east-1a"]
    launch_configuration = "${aws_launch_configuration.my_ecs_instance.id}"

}

resource "aws_launch_configuration" "my_ecs_instance" {
    name_prefix = "my-ecs-instance"
    instance_type = "t2.micro"
    image_id = "ami-19e8cc0e"
}

Terraform plan -var-file=mykey.tfvars

works fine but

Terraform apply -var-file=mykey.tfvars

will stock in creating the instance like

aws_autoscaling_group.my_instances: Still creating... (9m20s elapsed)
aws_autoscaling_group.my_instances: Still creating... (9m30s elapsed)
aws_autoscaling_group.my_instances: Still creating... (9m40s elapsed)

eventually time out and saying

aws_autoscaling_group.my_instances: "my-instances"
Waiting up to 10m0s: Need at least 1 healthy instances in ASG, have 0. Most recent activity:
..more..
StatusMessage: "No default VPC for this user. Launching EC2 instance failed."

I think I need to specify vpc id but I don't find auto_scaling_group has vpc_id attribute.

I am not sure how to fix this, can someone help me about it? Thanks a lot!


Solution

  • This wait is because the autoscalling group is waiting for at least one ec2 instance to up and running as defined in the auto scaling group but there is none. This resulted in the error which mentioned the root cause "No default VPC for this user". So basically, there is no ec2 up and runing because there is no VPC, subnet and/or VPC identifier associated with the autoscaling group.

    To resolve:

    • First if you haven't done this, you will need to create a VPC with the vpc resource "aws_vpc"
    • Next create a subnet with the subnet resources "aws_subnet"
    • Next associate the VPC identifier "vpc_zone_identifier" with the auto scaling group in "aws_autoscaling_group" resource area

    The identifier should look like below where "aws_subnet.main-public-1" is the subnet ID created in step 2

    vpc_zone_identifier  = ["${aws_subnet.main-public-1.id}"
    

    I hope that helps