My EC2 instance resource code
resource "aws_instance" "my-sample-webapp-ec2" {
availability_zone = var.availability_zone
subnet_id = var.subnet_id
key_name = var.ec2_instance_name
instance_initiated_shutdown_behavior = "stop"
disable_api_termination = false
# vpc_security_group_ids = var.vpc_security_group_ids
launch_template {
id = var.launch_template_id
version = "$Latest"
}
tags = {
"Name" = var.ec2_instance_name
}
root_block_device {
delete_on_termination = true
}
}
My launch template already exists in AWS region - checked
My Module import for the above EC2 resource
module "aws_ec2_machines" {
source = "./modules/ec2_machines"
count = length(local.availability_zones)
launch_template_id = var.launch_template_id
launch_template_ver = var.launch_template_ver
ec2_instance_name = "${var.ec2_instance_name}-${count.index + 1}"
availability_zone = local.availability_zones[count.index]
}
what I want to do is below
Specify my launch template and launch EC2 instance(s)
Subnet association should happen based on availability_zone
Currently, I have only 3 subnets (1 per availability zone), but they are not default. Also, the VPC under which the subnets are created is also not the default VPC.
The error I am getting
│ Error: Error launching source instance: InvalidParameterValue: Value (us-east-2b) for parameter availabilityZone is invalid. Subnet 'subnet-xxxxxx' is in the availability zone us-east-2a
│ status code: 400, request id: 75a126cb-59eb-40fe-9fa5-579ed908edbd
│
│ with module.aws_ec2_machines[1].aws_instance.my-sample-webapp-ec2,
│ on modules\ec2_machines\main.tf line 7, in resource "aws_instance" "my-sample-webapp-ec2":
│ 7: resource "aws_instance" "my-sample-webapp-ec2" {
│
╵
What am I doing wrong?
OK - I figured out to problem (pen and pencil writing)
Launch Template ID does not need to have any subnet defined
But any VPC should have subnets created and (good practice) assigned to a different AZ
a. e.g. subnet-2a should be with AZ 1, subnet-2b should be with AZ 2 etc.
Now, with the below resource/module invocation - it all worked well
And the subsequent module call in
main.tf