繁体   English   中英

Terraform - For_each - 您提供了一个对象类型列表的值

[英]Terraform - For_each - You have provided a value of type list of object

尝试 for_each (它是一种对象列表)时出现以下错误,但同样的事情在动态块中工作正常。

这是错误:

The given "for_each" argument value is unsuitable: the "for_each" argument must be a map, or set of strings, and you have provided a value of type list of object.

这是我收到错误的模块

      vpc_subnets = [
        {name: "public_test_a", cidr_block: "10.0.0.0/28", map_public_ip_on_launch: true,  availability_zone: "ap-south-1a"},
        {name: "public_test_b", cidr_block: "10.0.0.16/28", map_public_ip_on_launch: true,  availability_zone: "ap-south-1b"},
        {name: "private_test_a", cidr_block: "10.0.0.32/28", map_public_ip_on_launch: false,  availability_zone: "ap-south-1a"},
        {name: "private_test_b", cidr_block: "10.0.0.48/28", map_public_ip_on_launch: false,  availability_zone: "ap-south-1b"}
      ]

# Create Subnets
resource "aws_subnet" "subnets" {
    for_each = var.vpc_subnets

    vpc_id = aws_vpc.vpc.id
    cidr_block = each.value.cidr_block
    map_public_ip_on_launch = each.value.map_public_ip_on_launch
    availability_zone = each.value.availability

    tags = merge({
      Name = each.value.name
    }, var.subnet_tags)
}

但在另一个模块中,它工作正常。 唯一的区别是它在一个动态块中。

  ingress_rules = [
    {description: "Port 3306", cidr_blocks: ["10.0.0.0/24", "10.0.4.0/24"], port: 3306, protocol: "tcp"},
    {description: "Port 22",   cidr_blocks: ["0.0.0.0/0"], port: 22, protocol: "tcp"},
    {description: "port 80",   cidr_blocks: ["0.0.0.0/0"], port: 80, protocol: "tcp"}
  ]

resource "aws_security_group" "security_group" {
  name = var.name

  dynamic "ingress" {
    for_each = var.ingress_rules

    content {
      description = ingress.value.description
      cidr_blocks = ingress.value.cidr_blocks
      from_port   = ingress.value.port
      to_port     = ingress.value.port
      protocol    = ingress.value.protocol
    }
  }
 }

它不起作用,因为for_each在用于创建资源时仅接受一个映射或一组字符串,并且您正在传递一个映射列表。

因此,您必须修改它以仅使用地图:

# Create Subnets
resource "aws_subnet" "subnets" {

    for_each = {for idx, subnet in var.vpc_subnets: idx => subnet}

    vpc_id = aws_vpc.vpc.id
    cidr_block = each.value.cidr_block
    map_public_ip_on_launch = each.value.map_public_ip_on_launch
    availability_zone = each.value.availability

    tags = merge({
      Name = each.value.name
    }, var.subnet_tags)
}

动态块中使用的for_each没有这样的限制,因此您可以迭代您的地图列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM