【问题标题】:Run terraform modules conditionally有条件地运行 terraform 模块
【发布时间】:2021-09-06 21:58:33
【问题描述】:

我正在尝试有条件地运行模块。下面是代码。如果提供了值,它可以正常工作,但如果 var.accounts[*].vpc_ids 为空白,则无法说明 var.vpc_id 不能为空。但这基本上是模块应该运行的条件。如果 vpc_id 计数为 0,则模块不应运行。请帮忙。

resource "aws_ec2_transit_gateway_vpc_attachment" "this" {
   transit_gateway_id = var.transit_gateway_id
  vpc_id = var.vpc_id
  subnet_ids = var.subnet_ids
  dns_support                                     = "disable"
  ipv6_support                                    = "disable"
  transit_gateway_default_route_table_association = false
  transit_gateway_default_route_table_propagation = false
}

locals {
  create_tgw_attach = var.accounts[*].vpc_ids != "" ? true : false
}

module "tgw_peer2" {
  source = "../modules/tgw"
    count = length(var.accounts[2].vpc_ids)
  providers  = {
    aws = aws.accepter2
  }
  create_tgw_attach      = local.create_tgw_attach
  transit_gateway_id = aws_ec2_transit_gateway.this.id
  vpc_id = var.accounts[2].vpc_ids[count.index]
  subnet_ids = var.accounts[2].vpc_subnets[count.index].subnet_ids
  destination_cidr_block = var.destination_cidr_block_route

  share_tgw                             = true
  create_tgw                            = false
}

module "tgw_peer3" {
  source = "../modules/tgw"
  create_tgw_attach      = local.create_tgw_attach
  count = length(var.accounts[3].vpc_ids)
  providers  = {
    aws = aws.accepter3
  }
  transit_gateway_id = aws_ec2_transit_gateway.this.id
  vpc_id = var.accounts[3].vpc_ids[count.index]
  subnet_ids = var.accounts[3].vpc_subnets[count.index].subnet_ids

  share_tgw                             = true
  create_tgw                            = false  
}

【问题讨论】:

  • 在满足某些条件时在模块上添加count1,在所有其他情况下添加0
  • 我尝试了同样的方法,出于某种原因,即使计数为 0,它也在验证 vpc_id。我添加了以下计数。因为我希望模块运行那么多次。计数 = var.accounts[0].vpc_ids != [""] ?长度(var.accounts[0].vpc_ids):0
  • 你能分享一下真正的错误信息吗?另外,我希望这会因为 locals 块而失败,并且与条件模块声明无关。
  • 我在添加新的计数语句时删除了本地人。错误:\nSTDERR:\n错误:vpc_id 不能为空,在 ../modules/tgw/main.tf 第 39 行,资源 \"aws_ec2_transit_gateway_vpc_attachment\" \"this\":\n 39 中得到 \n\n: vpc_id = var.vpc_id
  • 这已经解决了。我修改了条件以检查 account_id 是否为 null 并且它有效。非常感谢@luk2302的帮助

标签: terraform terraform-provider-aws transit-gateway


【解决方案1】:

我试图将我使用的 vpc_id 的条件作为模块中的值。我修改了条件并且它起作用了。下面是代码。

module "tgw_peer1" {
  source = "./modules/tgw"
  providers  = {
    aws = aws.accepter1
  }
  count = var.accounts[1].account_id != "" ? length(var.accounts[1].vpc_ids) : 0
  transit_gateway_id = aws_ec2_transit_gateway.this.id
  vpc_id = var.accounts[1].vpc_ids[count.index]
  subnet_ids = var.accounts[1].vpc_subnets[count.index].subnet_ids
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-20
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    相关资源
    最近更新 更多