Terraform-AWS Multiple Subnets问题

时间:2019-07-18 12:20:01

标签: terraform terraform-provider-aws

我正在尝试部署多个ec2实例,其中每个Web Server ec2实例在不同的子网中,而Application Server实例在特定的子网中。

使用count参数时,每个Web服务器都可以正确部署在不同的子网中,但是应用程序实例可以部署在同一子网中,而不是我在“应用程序资源” 部分中指定的两个子网中如下。

如何指定要在特定子网中创建的应用程序服务器,该子网使用以下“公共子网资源” 部分中指定的count参数创建。

变量声明:

variable "subnet_private_cidr" {
type = "list"
default = ["10.10.1.0/24", "10.10.2.0/24", "10.10.3.0/24", "10.10.4.0/24"]
}
variable "subnet_public_cidr" {
type = "list"
default = ["10.10.0.0/24", "10.10.5.0/24", "10.10.6.0/24", "10.10.7.0/24"] 
}
variable "azs" {
type = "list"
default = ["us-east-1a", "us-east-1b", "us-east-1c", "us-east-1d"]
}

公共子网资源:

resource "aws_subnet" "qasubnet_public" {
count = "${length(var.subnet_public_cidr)}"
vpc_id = "${aws_vpc.qa_vpc.id}"
cidr_block = "${element(var.subnet_public_cidr,count.index)}"
availability_zone = "${element(var.azs,count.index)}"
tags {
       Name = "QASUBNET_PUBLIC-${count.index+1}"
}
}

私有子网资源:

resource "aws_subnet" "qasubnet_private" {
count = "${length(var.subnet_private_cidr)}"
vpc_id = "${aws_vpc.qa_vpc.id}"
cidr_block = "${element(var.subnet_private_cidr,count.index)}"
availability_zone = "${element(var.azs,count.index)}"
tags { 
       Name = "QASUBNET_PRIVATE-${count.index+1}"
}
}

网络服务器资源:

resource "aws_instance" "webserver" {
count = "${length(var.subnet_public_cidr)}"
ami = "${var.webserver_ami}"
instance_type = "t2.medium"
vpc_security_group_ids = ["${aws_security_group.webserver.id}"]
key_name = "${var.aws_key_name}"
subnet_id = "${element(aws_subnet.qasubnet_public.*.id,count.index)}"
}

应用程序资源:

resource "aws_instance" "appserver" {
count = 2
ami = "${var.appserver_ami}"
instance_type = "t2.medium"
vpc_security_group_ids = ["${aws_security_group.appserver.id}"]
key_name = "${var.aws_key_name}"
subnet_id = "${element(aws_subnet.qasubnet_private.*.id,0)}"
subnet_id = "${element(aws_subnet.qasubnet_private.*.id,1)}"
}

1 个答案:

答案 0 :(得分:0)

我不确定您打算怎么做:

  subnet_id              = "${element(aws_subnet.qasubnet_private.*.id,0)}"
  subnet_id              = "${element(aws_subnet.qasubnet_private.*.id,1)}"`

在您的资源“ aws_instance.appserver”中,它应该只是一个 subnet_id 参考:

  subnet_id              = "${element(aws_subnet.qasubnet_private.*.id,count.index)}"

使用count语句,每个子网将为您提供一个实例。