【问题标题】:Terraform Multi Level MapsTerraform 多级地图
【发布时间】:2021-08-03 10:32:57
【问题描述】:

我在尝试使用多级地图时遇到“地形计划”错误。我无法在google_compute_instance 模块中使用地图。我的目标是使用单个google_compute_instance 模块启动多个具有不同属性的虚拟机。我请求您帮助我更正我的 main.tf 或建议我实现我的目标

变量.tf

variable "instance_config" {
  type    = list(map(string))
  default = []
}

.tfvars

instance_config = {
  test-vm1 = {
      instance_name  = "test-vm1"
      instance_image = "debian-cloud/debian-8"
      instance_type =  "n1-standard-4"
     },

  test-vm2 = {
      instance_name  = "test-vm2"
      instance_image = "debian-cloud/debian-9"
      instance_type =  "f1-micro"
     }
}

main.tf

resource "google_compute_instance" "vm_instance" {

 { for instance_name, instance_type, instance_image in var.instance_config :
  name         = instance_config.instance_name
  machine_type = instance_config.instance_type
  tags         = var.instance_tags
  boot_disk {
    initialize_params {
      image =  instance_config.instance_image
    }
  }
 }

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

【问题讨论】:

    标签: google-cloud-platform terraform terraform-provider-gcp


    【解决方案1】:

    for_each 的语法不正确,instance_config 的格式错误。应该是:

    variable "instance_config" {
    
      type = map(object({
            instance_name  = string
            instance_image = string
            instance_type  = string
           }))
      
      default = {
        test-vm1 = {
            instance_name  = "test-vm1"
            instance_image = "debian-cloud/debian-8"
            instance_type =  "n1-standard-4"
           },
    
        test-vm2 = {
            instance_name  = "test-vm2"
            instance_image = "debian-cloud/debian-9"
            instance_type =  "f1-micro"
           }
      }
    }
    
    resource "google_compute_instance" "vm_instance" {
    
      for_each     = var.instance_config
       
      name         = each.value.instance_name
      machine_type = each.value.instance_type
      tags         = var.instance_tags
    
      boot_disk {
        initialize_params {
          image = each.value.instance_image
        }
      }
    
      network_interface {
        network = var.gcp_network
      }
    }
    

    【讨论】:

    • 非常感谢它的工作,最后一个问题,我如何从.tfvars而不是variables.tf传递这些值
    • @Eva 您在问题中将它们分开。只要确保类型被保留,并且是default = {}
    • 我仍然收到任何错误。我创建了一个新的post,但出现错误,你能帮帮我吗!
    • Stackoverflow 不允许我创建新帖子,所以我必须在 serverfault 中创建它。请查看并评论issue
    猜你喜欢
    • 2021-08-05
    • 2021-10-15
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    相关资源
    最近更新 更多