Terraform 将变量分配给点亮的块

Terraform assign variable to a lit block

我使用 aws 提供商。对于每个安全组,我都为 ssh 指定了相同的规则。如何将其提取到变量并分配给 aws_security_group.ingress 列表?

我期待什么:

variable "ssh_ingress" {
  default = {
    from_port = 22
    protocol = "tcp"
    to_port = 22
    description = "SSH for administration."
  }
}
resource "aws_security_group" "main" {
  ingress += var.ssh_ingress // That not work.

  ingress {
    from_port = 0
    protocol = "-1"
    to_port = 0
    self = true
  }

}

您可以使用 aws_security_group_rule 向现有安全组添加规​​则。

例如:

variable "ssh_ingress" {
  default = {
    from_port = 22
    protocol = "tcp"
    to_port = 22
    description = "SSH for administration."
  }
}

resource "aws_security_group" "main" {
  name        = "allow_tls"
  description = "Allow TLS inbound traffic"
  vpc_id      = data.aws_vpc.main.id
}

resource "aws_security_group_rule" "default" {
  type              = "ingress"
  from_port         = 0
  to_port           = 0
  protocol          = -1
  self              = true
  security_group_id = aws_security_group.main.id
}

resource "aws_security_group_rule" "example" {
  type              = "ingress"
  from_port         = var.ssh_ingress.from_port
  to_port           = var.ssh_ingress.to_port
  protocol          = var.ssh_ingress.protocol
  cidr_blocks       = ["10.0.0.0/11"]
  security_group_id = aws_security_group.main.id
}

替代多个内联入口规则

resource "aws_security_group" "main" {
  name        = "allow_tls"
  description = "Allow TLS inbound traffic"
  vpc_id      = data.aws_vpc.main.id
  
  ingress {
    from_port = 0
    protocol = "-1"
    to_port = 0
    self = true
  }
  
 ingress {
   from_port         = var.ssh_ingress.from_port
   to_port           = var.ssh_ingress.to_port
   protocol          = var.ssh_ingress.protocol
   cidr_blocks       = ["10.0.0.0/11"]
  }
  
}

您可以编写一个 ingress 块来引用您的变量的属性:

variable "ssh_ingress" {
  type = object({
    from_port   = number
    to_port     = number
    protocol    = string
    description = string
  })

  default = {
    from_port = 22
    protocol = "tcp"
    to_port = 22
    description = "SSH for administration."
  }
}

resource "aws_security_group" "main" {
  ingress {
    from_port   = var.ssh_ingress.from_port
    protocol    = var.ssh_ingress.protocol
    to_port     = var.ssh_ingress.to_port
    description = var.ssh_ingress.description
  }
}

ingress块本身是一个静态结构而不是一个值。您可以使用动态值填充其参数,但不能动态生成参数本身。 Terraform 在认为配置有效之前验证是否存在所有预期参数。

但是,Terraform 认为像这样的块中的值 null 等同于省略参数,因此如果您的模块的调用者要设置 description = null,例如,那么AWS 提供商将以与完全省略 description 参数完全相同的方式看到这一点。