Terraform 中 for_each 循环的动态输出

时间:2021-02-23 14:44:17

标签: amazon-web-services loops terraform amazon-rds

我使用的是 0.14.2 Terraform 版本,我有一个动态创建资源的任务。接下来的任务是:

print(mylist[-1])
> test3

使用这个本地变量:

resource "aws_db_instance" "api-mariaDB" {
  for_each             = local.ob

  identifier           = "api-mariadb-${each.key}"
  allocated_storage    = "20"
  storage_type         = "gp2"
  engine               = "mariadb"
  engine_version       = "10.4.8"
  allow_major_version_upgrade = true
  auto_minor_version_upgrade = false
  instance_class       = "db.t2.micro"
  name                 = "ssapi"
  username             = "admin"
  password             = "Temporal123"
  db_subnet_group_name = aws_db_subnet_group.subnet-mariadb[each.value].name
  skip_final_snapshot  = true
  vpc_security_group_ids = [aws_security_group.rds_SG.id]
  tags = {
    Name        = "api-db-${each.key}"
  }
}

此资源使用下一个输出创建 2 个 RDS 实例:

locals {
    ob = toset([
     "es",
     "uk",
    ])
}

我想在两次迭代中访问 arn 以在舵图中使用 after.. 我尝试使用下一个语法但没有成功:

aws_db_instance.api-mariaDB["es"] will be created
  + resource "aws_db_instance" "api-mariaDB" {
      + address                               = (known after apply)
      + allocated_storage                     = 20
      + allow_major_version_upgrade           = true
      + apply_immediately                     = (known after apply)
      + arn                                   = (known after apply)
      .
      .
      .

有什么想法吗?

谢谢!

编辑

我也试过这个选项:

output "rds" {
   value = {
     endpoint = "aws_db_instance.api-mariaDB[each.value].arn"
}

但是我收到了这个错误:

output "rds" {
  value = {
    endpoint = aws_db_instance.api-mariaDB[*].arn
  }
}

1 个答案:

答案 0 :(得分:2)

`*` 运算符将让您从列表中的每个项目中获取一个值。

为每个创建一个映射,所以你需要遍历键:

output "rds" {
  value = {
    endpoint = [for o in local.ob: aws_db_instance.api-mariaDB[o]].arn
  }
}