I am using data resources (Terraform .12) to find the subnet_id within the vpc and finally create ec2 instance. The VPC is getting created succesfully but I get the following error :
Error: no matching subnet found for vpc with id vpc-03a71967237294efe
However, If execute again it works.
module.my_vpc.aws_vpc.primary_vpc: Creating...
module.my_vpc.aws_vpc.primary_vpc: Creation complete after 3s [id=vpc-03a71967237294efe]
Error: no matching subnet found for vpc with id vpc-03a71967237294efe
Main.tf
vpc.tf
public_subnet.tf
ec2.tf
Here is the reproducible code:
Main.tf
provider "aws" {
region = "us-east-1"
profile = "work"
shared_credentials_file=">>>>>>>>>>"
}
module "my_vpc" {
source = "../mod/vpc"
vpc_cidr = "10.0.0.0/16"
}
module "pub_sub" {
source = "../mod/pub_sub"
vpc_id = "${module.my_vpc.id}"
}
module "ec2" {
source = "../mod/instances"
vpc_id = "${module.my_vpc.id}"
}
public_subnet.tf
variable "sub_cdr" {
type="list"
default=["10.0.0.0/28", "10.0.0.16/28"]
}
variable "azs" {
type="list"
default=["us-east-1a","us-east-1b"]
}
data "aws_availability_zones" azs {}
variable "vpc_id" { }
resource aws_subnet "public_subnet"{
count=2
vpc_id=var.vpc_id
cidr_block=var.sub_cdr[count.index]
availability_zone=data.aws_availability_zones.azs.names[count.index]
tags= {Name = "pub-sub-${count.index + 1}"}
}
output "pub_sub_id" {
value = aws_subnet.public_subnet.*.id
}
ec2.tf
variable "vpc_id" { }
variable "instance_count" {
default=1
}
data "aws_subnet_ids" "public" {
vpc_id = var.vpc_id
tags = {
Name = "*pub-sub*"
}
}
resource "aws_security_group" "pub_sg" {
vpc_id = "${var.vpc_id}"
name = "public-sg"
ingress {
from_port = 22
protocol = "tcp"
to_port = 22
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
protocol = "-1"
to_port = 0
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_instance" "web-srvs" {
count=1
ami = "ami-035b3c7efe6d061d5"
instance_type = "t2.nano"
key_name="dell-dev"
subnet_id = element(tolist(data.aws_subnet_ids.public.ids), count.index)
vpc_security_group_ids = ["${aws_security_group.pub_sg.id}"]
associate_public_ip_address=true
tags = {
CountIndex = "${var.instance_count == "0" ? "" : format("%02d", count.index + 1)}"
}
}
Any help is highly appreciated.