如何通过 Terraform 0.12 中的列表(对象)进行 for_each [英] How to for_each through a list(objects) in Terraform 0.12

查看:17
本文介绍了如何通过 Terraform 0.12 中的列表(对象)进行 for_each的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要部署 GCP 计算实例列表.如何通过vms"循环 for_each?在这样的对象列表中:

I need to deploy a list of GCP compute instances. How do I loop for_each through the "vms" in a list of objects like this:

    "gcp_zone": "us-central1-a",
    "image_name": "centos-cloud/centos-7",
    "vms": [
      {
        "hostname": "test1-srfe",
        "cpu": 1,
        "ram": 4,
        "hdd": 15,
        "log_drive": 300,
        "template": "Template-New",
        "service_types": [
          "sql",
          "db01",
          "db02"
        ]
      },
      {
        "hostname": "test1-second",
        "cpu": 1,
        "ram": 4,
        "hdd": 15,
        "template": "APPs-Template",
        "service_types": [
          "configs"
        ]
      }
    ]    
}

推荐答案

好像我找到了该做什么.如果你传递的不是地图的地图而是地图列表,你可以使用这样的代码

Seem's like I found what to do. If you pass not the maps of maps but the list of maps you can use such code

resource "google_compute_instance" "node" {
    for_each = {for vm in var.vms:  vm.hostname => vm}

    name         = "${each.value.hostname}"
    machine_type = "custom-${each.value.cpu}-${each.value.ram*1024}"
    zone         = "${var.gcp_zone}"

    boot_disk {
        initialize_params {
        image = "${var.image_name}"
        size = "${each.value.hdd}"
        }
    }

    network_interface {
        network = "${var.network}"
    }

    metadata = {
        env_id = "${var.env_id}"
        service_types = "${join(",",each.value.service_types)}"
  }
}

它将创建实际数量的实例,并且当您删除例如三个中间的一个(如果您创建三个:)),terraform 将删除我们要求的内容.

It will create actual number of instance and when you remove for example middle one of three(if you create three:)), terraform will remove what we asked.

这篇关于如何通过 Terraform 0.12 中的列表(对象)进行 for_each的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆