我有以下地形代码:
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。第 2 和第 3 个没有获得公共 IP。 我在网上看过并尝试了很多东西,但无法使其工作。
虚拟机创建代码:
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 个实例,因此只创建了 1 个实例。它接收公共 IP 地址,因为它正在选取创建并与公共 IP 关联的网络接口。
地形 0.12.9 中的工作示例:
Main.tf
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
}
Main.auto.tfvars
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
输出
Apply complete! Resources: 10 added, 0 changed, 0 destroyed.
Releasing state lock. This may take a few moments...
Outputs:
instance_public_ips = [
"34.244.18.5",
"52.213.153.230",
"34.244.69.143",
]