使用带有 for_each 的数据部分进行 terraform

问题描述 投票:0回答:2

我尝试通过传递 json 中的配置来创建资源,并在 json 上进行资源循环。然而,同一 json 的一部分包含需要在数据部分中使用的值。

[
{
  "username": "administrator",
  "password": "password",
  "domain_name": "test.io",
  "dns": "[10.10.1.6]",
  "vpc_name": "Sandbox*",
  "subnet_name": "*private*",
  "org_unit": "OU=test,DC=awstest,DC=io"
},
{
  "domain": "awstest.io",
  "username": "administrator",
  "password": "password2"
}
]

我拥有的地形是

locals {
  DirectoryServices = jsondecode(var.json)
}

data "aws_vpc" "this" {
  for_each = local.DirectoryServices
  filter {
    name   = "tag:Name"
    values = [each.value.vpc_name]
  }
}

data "aws_subnets" "this" {
  for_each = local.DirectoryServices
  filter {
    name   = "tag:Name"
    values = [each.value.subnet_name]
  }
  filter {
    name   = "vpc-id"
    values = [data.aws_vpc.this.id]
  }
}

locals {
  subnets = slice(data.aws_subnets.this.ids, 0, 2)
}

resource "aws_directory_service_directory" "connector" {
  for_each = local.DirectoryServices

  name     = each.value.domain_name
  password = each.value.password
  size     = each.value.size
  type     = "ADConnector"

  connect_settings {
    customer_dns_ips  = each.value.dns
    customer_username = each.value.username
    subnet_ids        = data.aws_subnets.this.ids
    vpc_id            = data.aws_vpc.this.id
  }
}

有没有办法使用 json 中的值并在数据部分过滤器中使用它们,然后引用从数据部分返回的正确 vpc 和子网项目?

我已经为此摸不着头脑很久了,任何关于如何做到这一点的指示都会非常感激。

谢谢

amazon-web-services terraform
2个回答
0
投票

结束,因为我需要重写问题!


0
投票

for_each
在Terraform中确实相当棘手

  • 使用时不需要括号
    each
  • 寻址其他资源时,使用
    each.key
    作为数组索引
  • slice
    中添加
    [*]
    以接收子网数组

这似乎提供了有效的地形:

variable "json" {
  type = string
}

locals {
  DirectoryServices = jsondecode(var.json)
}

data "aws_vpc" "this" {
  for_each = local.DirectoryServices
  filter {
    name   = "tag:Name"
    values = each.value.vpc_name
  }
}

data "aws_subnets" "this" {
  for_each = local.DirectoryServices
  filter {
    name   = "tag:Name"
    values = each.value.subnet_name
  }
  filter {
    name   = "vpc-id"
    values = data.aws_vpc.this[each.key].id
  }
}

locals {
  subnets = slice(data.aws_subnets.this[*].ids, 0, 2)
}

resource "aws_directory_service_directory" "connector" {
  for_each = local.DirectoryServices

  name     = each.value.domain_name
  password = each.value.password
  size     = each.value.size
  type     = "ADConnector"

  connect_settings {
    customer_dns_ips  = each.value.dns
    customer_username = each.value.username
    subnet_ids        = data.aws_subnets.this[each.key].ids
    vpc_id            = data.aws_vpc.this[each.key].id
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.