Terraform - 为 EC2 实例分配多个子网

Terraform - assign multiple subnets to EC2 instance

我有 2 个子网(每个可用区 1 个)

resource "aws_subnet" "infrastructure_services" {
  count                   = "${var.enable_infrastructure_services_subnet ? 2 : 0}"
  vpc_id                  = "${aws_vpc.this.id}"
  cidr_block              = "${cidrsubnet(var.cidr_block,5,count.index + 6)}"
  availability_zone       = "${element(var.availability_zones, count.index)}"
  map_public_ip_on_launch = false

  tags = "${
    merge( map("Name", format("%s %s %s", var.env_name, count.index == 0 ? "Infrastructure Services A" : "Infrastructure Services B", "Subnet")), 
    var.global_tags, 
    var.vpc_tags)}"
}

我想将这 2 个子网添加到 EC2 实例:

resource "aws_instance" "this" {
  count                   = "${length(var.instance_names)}"
  ami                     = "${var.ami}"
  instance_type           = "${element(var.instance_type, count.index)}"
  availability_zone       = "${element(var.availability_zones, count.index)}"
  disable_api_termination = "${var.disable_api_termination}"
  key_name                = "${var.key_name}"
  ebs_optimized           = "${var.ebs_optimized}"
  subnet_id="${element(aws_subnet.infrastructure_services.id,count.index)}"

  vpc_security_group_ids=["${aws_security_group.infrastructure_services.id}"]

但得到:

aws_instance.this[0]: Resource 'aws_subnet.infrastructure_services' not found for variable 'aws_subnet.infrastructure_services.id'
* aws_instance.this[1]: Resource 'aws_subnet.infrastructure_services' not found for variable 'aws_subnet.infrastructure_services.id'

您的列表中缺少 * splat 运算符语法。相反,您应该使用 aws_subnet.infrastructure_services.*.id 来引用资源列表。

所以您的实例资源应该如下所示:

resource "aws_instance" "this" {
  count                   = "${length(var.instance_names)}"
  ami                     = "${var.ami}"
  instance_type           = "${element(var.instance_type, count.index)}"
  availability_zone       = "${element(var.availability_zones, count.index)}"
  disable_api_termination = "${var.disable_api_termination}"
  key_name                = "${var.key_name}"
  ebs_optimized           = "${var.ebs_optimized}"
  subnet_id               = "${element(aws_subnet.infrastructure_services.*id, count.index)}"
  vpc_security_group_ids  = ["${aws_security_group.infrastructure_services.id}"]
}

可能还值得注意的是,除非您需要使用列表长度的模数循环返回列表,否则您可以使用更简单的 list[index] 语法而不是 element(list, index])

resource "aws_instance" "this" {
  count                   = "${length(var.instance_names)}"
  ami                     = "${var.ami}"
  instance_type           = "${var.instance_type[count.index]}"
  availability_zone       = "${var.availability_zones[count.index])}"
  disable_api_termination = "${var.disable_api_termination}"
  key_name                = "${var.key_name}"
  ebs_optimized           = "${var.ebs_optimized}"
  subnet_id               = "${aws_subnet.infrastructure_services.*id[count.index])}"
  vpc_security_group_ids  = ["${aws_security_group.infrastructure_services.id}"]
}