首页 > 解决方案 > 用于 aws 安全组的 Terraform 中的变量值

问题描述

我是 terraform 的新手,正在尝试使用入口和出口规则创建 AWS 安全组。我没有对值进行硬编码并创建多个入口和出口块,而是尝试使用 terraformlookup函数。

main.tf文件如下所示:

provider "aws" {
  version                 = "~> 2.0"
  region                  = var.region
  profile                 = var.profile
}

resource "aws_security_group" "this" {
  name = "test-sg"
  description = "test security group"

  dynamic "ingress" {
    for_each = var.ingress_rules
    content {
      description      = lookup(ingress.value, "description", null)
      from_port        = lookup(ingress.value, "from_port", null)
      to_port          = lookup(ingress.value, "to_port", null)
      protocol         = lookup(ingress.value, "protocol", null)
      cidr_blocks      = lookup(ingress.value, "cidr_blocks", null)
    }
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "test-sg"
  }
}

variables.tf文件看起来像这样

variable "ingress_rules" {
  default     = {
    "description" = ["For HTTP", "For SSH"]
    "from_port"   = ["80", "22"]
    "to_port"     = ["80", "22"]
    "protocol"    = ["tcp", "tcp"]
    "cidr_blocks" = ["0.0.0.0/0", "0.0.0.0/0"]
  }
  type        = map(list(string))
  description = "Security group rules"
}

运行terraform validate时显示配置有效,但运行terraform plan时显示以下错误:

 ingress.value is list of string with 2 elements
 
 Invalid value for "inputMap" parameter: lookup() requires a map as the first
 argument.

仍然花了很长时间之后,我无法弄清楚如何解决这个错误。将查找值传递给variables.tf文件的正确方法是什么?

标签: amazon-web-servicesterraformterraform-provider-aws

解决方案


我将按如下方式实现它:

resource "aws_security_group" "test_security_group" {
  name = "test-sg"
  description = "test security group"

  dynamic "ingress" {
    for_each = var.sg_ingress_rules
    content {
      from_port   = ingress.value.from_port
      to_port     = ingress.value.to_port
      protocol    = ingress.value.protocol
      cidr_blocks = ingress.value.cidr_blocks
      description = ingress.value.description
    }
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "test security group"
  }
}

变量.tf

variable "sg_ingress_rules" {
  description = "Ingress security group rules"
  type        = map
}

my_vars.tfvars

sg_ingress_rules = {
  "1" = {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
    description = "HTTP"
  },
  "2" = {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["<my_private_ip>/32"]
    description = "SSH"
  }
}

希望对进一步理解有所帮助!


推荐阅读