找不到ID为vpc的vpc的匹配子网

时间:2019-09-24 19:54:11

标签: amazon-web-services resources terraform subnet vpc

我正在使用数据资源(Terraform .12)在vpc中查找subnet_id,并最终创建ec2实例。 VPC已成功创建,但出现以下错误:

错误:找不到ID为vpc-03a71967237294efe的vpc的匹配子网

但是,如果再次执行,它将起作用。

module.my_vpc.aws_vpc.primary_vpc:正在创建...

module.my_vpc.aws_vpc.primary_vpc:创建3秒后完成[id = vpc-03a71967237294efe]

错误:找不到ID为vpc-03a71967237294efe的vpc的匹配子网

Main.tf
   vpc.tf
   public_subnet.tf
   ec2.tf

以下是可复制的代码:

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

我们非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,发现在 aws aws_subnet_ids 数据组件中添加一个depends_on 子句可以为我解决这个问题。