Terraform没有为所有实例分配公共IP

时间:2019-09-26 19:22:52

标签: terraform terraform-provider-aws

我有以下Terraform代码:

resource "aws_subnet" "public_subnet" {
  count  = "3"
  vpc_id = "${aws_vpc.vpc.id}"

  cidr_block              = "${cidrsubnet("${var.vpc_cidr}", 4, count.index)}" #count.index is 3 it creates 3 subnets
  availability_zone       = "${element(var.lst_azs, count.index)}"
  map_public_ip_on_launch = true
}

上面的代码创建3个子网,并将3个不同的实例附加到这3个子网。 但是只有第一个实例获得了公共IP。第二和第三没有获得公共IP。 我已经在网上查看并尝试了许多方法,但无法使其正常工作。

VM创建代码:

resource "aws_instance" "test" {
  instance_type        = "${var.micro}”

  network_interface {
    device_index         = 0
    network_interface_id = "${aws_network_interface.eth0.id}"
  }
}

resource "aws_network_interface" "eth0" {
  private_ips       = 10.0.0.1
  source_dest_check = "true"
  security_groups   = ["${aws_security_group.sg1.id}"]
  subnet_id = "${element(data.aws_subnet_ids.sub1.ids,0)}"
  lifecycle {
    ignore_changes = ["subnet_id"]
  }
}


resource "aws_subnet" "sub1" {
  count  = 3
  vpc_id = "${aws_vpc.test1.id}"
  cidr_block              = "${var.security_vpc_cidr_block}, count.index}"
  availability_zone       = "${element(var.lst_azs, count.index)}"
  map_public_ip_on_launch = true
}



data "aws_subnet_ids" "subnets1" {
  vpc_id = "${aws_vpc.test1.id}"
  depends_on = ["aws_subnet.subnets1"]
}

1 个答案:

答案 0 :(得分:0)

我在这里看到的主要问题是,您在提供的代码中创建的实例数不超过1个,因此仅创建了1个实例。它接收公共IP地址,因为它正在拾取已创建并与公共IP关联的网络接口。

Terraform 0.12.9中的工作示例:

Main.tf

batch.append(message)

Main.auto.tfvars

variable "cidr_blocks" {
  type        = list(string)
  description = "List of CIDR Blocks to use in VPC"
}
variable "availability_zones" {
  type        = list(string)
  description = "List of AZs to use"
}
variable "create_count" {
  type        = number
  description = "How many resources to create"
  default     = 1
}

resource "aws_instance" "servers" {
  count         = var.create_count
  instance_type = "t3.micro"
  ami           = "ami-047bb4163c506cd98"

  network_interface {
    device_index         = 0
    network_interface_id = aws_network_interface.eth0[count.index].id
  }

  tags = {
    Name = join("-", ["Test", count.index])
  }
}

resource "aws_vpc" "testing" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_subnet" "testing" {
  count                   = var.create_count
  vpc_id                  = aws_vpc.testing.id
  cidr_block              = var.cidr_blocks[count.index]
  availability_zone       = var.availability_zones[count.index]
  map_public_ip_on_launch = true
}

resource "aws_network_interface" "eth0" {
  count     = var.create_count
  subnet_id = aws_subnet.testing[count.index].id
}

output "instance_public_ips" {
  value = aws_instance.servers.*.public_ip
}

输出

cidr_blocks        = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
availability_zones = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]
create_count       = 3