Terraform:如何使 VPC 子网可变

Terraform:如何使 VPC 子网可变

我想在两个子网中配置 2 个域控制器实例。VPC、子网和其他网络部分已创建。

主文件

  resource "aws_instance" "PerformanceDC01" {
  count         = var.instance_count
  ami           = var.aws_ami
  ebs_optimized = true
  instance_type = var.aws_instance_type
  subnet_id     = var.pvtsub_a
  key_name      = var.aws_key_name
  vpc_security_group_ids = [
    var.base_sg,
    var.perfdc_sg
  ]
  root_block_device {
    volume_type = "gp2"
    volume_size = "80"
    encrypted   = true
    kms_key_id  = "10c07c9d-ede7-43d5-b633-75a2482848aa"
  }
  tags = {
    Name = "PerformanceDC0-${count.index + 1}"
  }
} 

变量.tf

variable "aws_region" {}
variable "aws_profile" {}
variable "instance_count" {}
variable "aws_vpc" {}
variable "pvtsub_a" {}
variable "pvtsub_b" {}
variable "pvtsub_c" {}
variable "pubsub_a" {}
variable "pubsub_b" {}
variable "pubsub_c" {}
variable "aws_ami" {}
variable "aws_instance_type" {}
variable "aws_key_name" {
  description = "Key Name"
  default     = "Performance_B_KP"
}
variable "base_sg" {}
variable "perfdc_sg" {}

性能.tfvars

.
.
instance_count    = "2"
.
.

问题: 我如何可变化子网 ID例如DC01已配置普特苏巴DC02已配置上传者:pvtsub_b

答案1

像这样使用for_each而不是:count

resource "aws_instance" "PerformanceDC" {
  for_each         = var.instances
  ami              = each.value.ami
  subnet_id        = each.value.subnet_id
  ...
  tags = {
    Name = "PerformanceDC0-${each.key + 1}"
  }
}

tfvars:

instances = [
  {
    ami       = "brad",
    subnet_id = "sg1",
  },
  {
    ami       = "pitt",
    subnet_id = "sg2",
  } 
]

这使您可以将其中一个实例迁移到新的 AMI。

相关内容