Terraform创建Compute Engine实例时标签类型不匹配错误修复求助
Terraform GCE实例标签类型错误修复方案
问题描述
使用Terraform创建Google Compute Engine实例时,执行tf plan触发类型错误:
Error: Incorrect attribute value type
on ..\modules\compute_engine\main.tf line 14, in resource "google_compute_instance" "generic_instance":
14: labels = var.labelsInappropriate value for attribute "labels": map of string required.
错误核心是google_compute_instance资源的labels属性要求传入string类型的键值对map,但当前代码传入的是list(object)类型,类型不匹配导致报错。
修复步骤
1. 修改根模块的变量定义
将compute_engine_instances变量中的labels类型从list(object(...))改为map(string),对齐GCE资源的要求:
variable "compute_engine_instances" { type = map(object({ instance_name = string machine_type = string zone = string tags = list(string) image_name = string image_project = string labels = map(string) # 调整为map(string)类型 })) }
2. 调整tfvars配置文件
移除labels外层的数组包裹,直接写成键值对结构,同时将数字类型的app_id转为字符串(GCE标签值必须为字符串):
compute_engine_instances = { "test-adi" = { instance_name = "test-vm" machine_type = "n1-standard-1" zone = "us-east4-b" tags = ["foo", "bar"] image_name = "centos-7" image_project = "cc-devtools" labels = { # 去掉数组,直接使用map结构 app_id = "6" # 数字转为字符串 cost_center = "0156" owner = "ops" email = "ps" } } }
3. 修正模块中的labels变量定义
将模块内的labels变量类型从any改为map(string),增强类型检查的严谨性,提前拦截类型错误:
variable "labels" { type = map(string) description = "A map of labels for this VM" # 更新描述匹配类型 }
4. 模块调用无需修改
原有的模块调用代码保持不变即可,此时each.value.labels已经是符合要求的map(string)类型:
module "compute_engines" { source = "../modules/compute_engine" for_each = var.compute_engine_instances project_id = var.project_id instance_name = each.value.instance_name machine_type = each.value.machine_type tags = each.value.tags labels = each.value.labels subnetwork = var.subnetwork zone = each.value.zone image_name = each.value.image_name image_project = each.value.image_project }
内容的提问来源于stack exchange,提问作者addy
相关产品推荐
相关产品推荐

