【问题标题】:Terraform conditional for AWS route tablesAWS 路由表的 Terraform 条件
【发布时间】:2021-08-21 23:49:23
【问题描述】:

使用 Terraform,我需要为公共子网和私有子网创建路由表。 “公共”路由表的资源正在使用gateway_id

resource "aws_route_table" "rt-public" { 
    route {
        cidr_block = var.cidr_block      
        gateway_id = var.gateway_id
    }
 }

“私有”路由表正在使用nat_gateway_id:

resource "aws_route_table" "rt-private" { 
    route {
        cidr_block       =  var.cidr_block      
        nat_gateway_id   =  var.gateway_id
    }
 }

我从main.tf 文件中传递了一个变量var.tier,它指示我需要一个“公共”还是“私有”路由表。

我尝试了以下(在模块中):

resource "aws_route_table" "rt-public" { 
    count      = var.tier == "Public" ? 1 : 0

    route {
        cidr_block = var.cidr_block      
        gateway_id = var.gateway_id

    }
 } 

resource "aws_route_table" "rt-private" { 
    count      = var.tier == "Private" ? 1 : 0
    route {
        cidr_block      =   var.cidr_block      
        nat_gateway_id  =   var.gateway_id 
    }

 }

这行得通。但是在main.tf我还需要访问路由表id。所以我创建了一个outputs.tf 文件如下:

output "aws_rt_public_id" {
  value = aws_route_table.rt-public.id
}

output "aws_rt_private_id" {
  value = aws_route_table.rt-private.id
}

问题在于,当创建“公共”路由表时,“私有”输出为空。我收到错误消息:aws_route_table.rt-private is empty tuple. The given key does not identify an element in this collection value.

公开版本的类似错误消息。

如何使用条件来解决这个问题?

【问题讨论】:

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


    【解决方案1】:

    你也可以使用你的条件,只返回有效的输出:

    output "aws_rt_public_id" {
      value = var.tier == "Public" ? aws_route_table.rt-public[0].id : null 
    }
    
    output "aws_rt_private_id" {
      value = var.tier == "Private" ? aws_route_table.rt-private[0].id : null 
    }
    

    在上面的null时,在选择时,将导致删除给定的输出。

    【讨论】:

    • 谢谢。这适用于我需要添加索引的例外情况。 value = var.p4c-tier == "Public" ? aws_route_table.p4c-rt-public[0].id : null。如果您修改答案,我可以接受。
    猜你喜欢
    • 2020-05-14
    • 2017-10-02
    • 1970-01-01
    • 2021-12-04
    • 2020-09-06
    • 2020-08-31
    • 2021-12-27
    • 2019-01-21
    • 2021-02-25
    相关资源
    最近更新 更多