简体   繁体   English

如何在 Terraform 中创建迭代循环

[英]How to create Iterative Loop in Terraform

I have around 50 resources that I create in a Terraform script.我在 Terraform 脚本中创建了大约 50 个资源。 I need now to add diagnostic logging for each resource.我现在需要为每个资源添加诊断日志记录。

The following code is what I use:以下代码是我使用的:


data "azurerm_monitor_diagnostic_categories" "vnet-spoke01" {
  resource_id = module.MOD-VNET-SPOKE01.id
}

resource "azurerm_monitor_diagnostic_setting" "vnet-spoke01" {
  name                       = "diag-${module.MOD-VNET-SPOKE01.vnetName}"
  target_resource_id         = module.MOD-VNET-SPOKE01.id
  log_analytics_workspace_id = module.MOD-LOG-ANALYTICS-WORKSPACE.id

  dynamic "log" {
    for_each = data.azurerm_monitor_diagnostic_categories.vnet-spoke01.logs
    content {
      category = log.value
      retention_policy {
        days    = 0
        enabled = false
      }
    }
  }

  dynamic "metric" {
    for_each = data.azurerm_monitor_diagnostic_categories.vnet-spoke01.metrics
    content {
      category = metric.value
      retention_policy {
        days    = 0
        enabled = false
      }
    }
  }
}

As you can see, I'm adding .NET of spoke-1 diagnostic settings.如您所见,我添加了 .NET 的 spoke-1 诊断设置。 Can someone kindly guide me as to how I can add a for-loop so it goes through each resource (that I'd put in an array or list) and run through it?有人可以指导我如何添加 for 循环以便它遍历每个资源(我将其放入数组或列表中)并运行它吗?

e.g. 

variable "myResources" {

type = list(string)
default = ["module.MOD-VNET-SPOKE01", "module.MOD-VNET-SPOKE02" etc...]
}

for a in myResources
{

.... execute diagnostic routine

}

How could I do this?我怎么能这样做?

Many thanks非常感谢

Sadly you can't do that.遗憾的是你不能那样做。 You can't dynamically resolve strings (eg "module.MOD-.NET-SPOKE01" ) into resource identifiers (eg module.MOD-.NET-SPOKE01.id .您不能将字符串(例如"module.MOD-.NET-SPOKE01" )动态解析为资源标识符(例如module.MOD-.NET-SPOKE01.id )。

Your variable would already have to contain all ids for your loop to work:您的变量必须已经包含所有 id 才能让您的循环工作:

variable "myResources" {
   type = list(string)
   default = ["<id-SPOKE01>", "<id-SPOKE02>", etc...]
}

or through locals :或通过locals

locals {
   myResources  = [module.MOD-VNET-SPOKE01.id, module.MOD-VNET-SPOKE02.id etc...]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM