【问题标题】:How to set nat_gateway_id in aws_route_table如何在 aws_route_table 中设置 nat_gateway_id
【发布时间】:2022-02-06 19:23:04
【问题描述】:

main.tf

module "vpc" {
  source = "../modules/aws/vpc"

  env_prefix  = "prod"
  environment = "production"
  env_name    = "test"
  vpc_cidr    = "10.1.0.0/16"

  public_subnet_cidrs = {
    test-prod-nat = {
      subnet = "10.1.15.0/24"
      name   = "test-prod-nat"
      az     = "ap-northeast-1a"
    }
  }
}

nat.tf

resource "aws_nat_gateway" "private" {
  for_each = var.public_subnet_cidrs

  allocation_id = aws_eip.nat_gateway.id
  subnet_id     = aws_subnet.public[each.key].id

  tags = merge(
    local.tags,
    {
      Name = format("%s_%s_%s", var.env_prefix, var.env_name, "nat-gateway")
    }
  )

  lifecycle {
    prevent_destroy = false
  }
}

route_table.tf

/**
 * for private subnet
 */
resource "aws_route_table" "private" {
  vpc_id = aws_vpc.dandori.id

  tags = merge(
    local.tags,
    {
      Name = format("%s_%s", var.env_prefix, var.env_name)
    }
  )

  route {
    cidr_block = "0.0.0.0/0"
    nat_gateway_id = [
      for v in aws_nat_gateway.private : v.id
    ]
  }
  
  lifecycle {
    prevent_destroy = false
  }
}

当我在创建上述 tf 文件后运行 terraform plan 时,我收到以下错误

【错误】

╷
│ Error: Incorrect attribute value type
│ 
│   on ../modules/aws/vpc/route_table.tf line 55, in resource "aws_route_table" "private":
│   55:     nat_gateway_id = [
│   56:       for v in aws_nat_gateway.private : v.id
│   57:     ]
│     ├────────────────
│     │ aws_nat_gateway.private is object with 1 attribute "test-prod-nat"
│ 
│ Inappropriate value for attribute "nat_gateway_id": string required.

route_table.tf 和 nat.tf 将是模块中的文件 我正在尝试使用 for 循环方法在 route_table.tf 中设置 nat_gateway_id,但无法正确设置,如错误消息中所示。

我应该怎么做才能解决这个问题? 请给我一些建议。

【问题讨论】:

    标签: amazon-web-services terraform terraform-provider-aws


    【解决方案1】:

    如果要为每个aws_nat_gateway.private创建一个路由表,那么应该是:

    resource "aws_route_table" "private" {
    
    
      for_each = aws_nat_gateway.private
    
    
      vpc_id = aws_vpc.dandori.id
    
      tags = merge(
        local.tags,
        {
          Name = format("%s_%s", var.env_prefix, var.env_name)
        }
      )
    
      route {
        cidr_block = "0.0.0.0/0"
        nat_gateway_id = each.value["id"]
      }
      
      lifecycle {
        prevent_destroy = false
      }
    }
    

    【讨论】:

    • 非常感谢。我能够解决这个问题。是否无法使用我为 nat_gateway_id 设置的以下语句设置 nat_gateway_id nat_gateway_id = [ for v in aws_nat_gateway.private : v.id ]
    猜你喜欢
    • 2021-03-27
    • 2018-02-07
    • 2018-07-29
    • 2019-05-26
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    相关资源
    最近更新 更多