这就是我目前使用它们的方式:
# terraform.tfvars
vsphere_tag_name ="Name"
vsphere_tag_category ="Category"
# var.tf
variable "vsphere_tag_name" {
type = string
description = "Tag name for the vSphere virtual machines"
}
variable "vsphere_tag_category" {
type = string
description = "Tag category for the vSphere virtual machines"
}
# main.tf data
data "vsphere_tag_category" "category" {
name = "${var.vsphere_tag_category}"
}
data "vsphere_tag" "tag" {
name = "${var.vsphere_tag_name}"
category_id = "${data.vsphere_tag_category.category.id}"
}
# main.tf resource
tags = ["${data.vsphere_tag.tag.id}"]
对于一个标签来说效果很好,但如何提供多个现有标签?
我不确定确切的用例是什么,特别是因为标记数据源所需的参数相当严格,但这是可以做到的。
示例:
# terraform.tfvars
vsphere_tag_name = ["Name1", "Name2", "Name3"]
vsphere_tag_category = "Category"
# var.tf
variable "vsphere_tag_name" {
type = list
description = "List of tag names for the vSphere virtual machines"
}
variable "vsphere_tag_category" {
type = string
description = "Tag category for the vSphere virtual machines"
}
# main.tf data
data "vsphere_tag_category" "category" {
name = "${var.vsphere_tag_category}"
}
data "vsphere_tag" "tag" {
for_each = var.vsphere_tag_name
name = "${each.value}"
category_id = "${data.vsphere_tag_category.category.id}"
}
# main.tf resource
tags = ["${data.vsphere_tag.tag[0].id}", "${data.vsphere_tag.tag[1].id}", "${data.vsphere_tag.tag[2].id}"]
然后,如果您必须切换 vSphere 标记类别,则会出现完全不同的复杂程度。
感谢所有参与人员的帮助,这就是答案
# terraform.tfvars
tags = {
TagCategory1 = "TagName1"
TagCategory2 = "TagName2"
}
# var.tf
variable "tags" {
type = map(any)
}
variable "tag_ids" {
type = list(any)
}
# main.tf data
data "vsphere_tag_category" "category" {
count = length(var.tags)
name = keys(var.tags)[count.index]
}
data "vsphere_tag" "tag" {
count = length(var.tags)
name = var.tags[keys(var.tags)[count.index]]
category_id = data.vsphere_tag_category.category[count.index].id
}
# main.tf resource
tags = var.tag_ids:data.vsphere_tag.tag[*].id
找到了这个帖子,它很有帮助,谢谢。这是我们提出的有效解决方案。
#terraform.auto.tfvars
tag_categories = {
"Environment" = {
name = "Environment"
tags = ["dev", "test", "prod"]
}
"OS" = {
name = "OS"
tags = ["linux", "windows"]
}
}
#variables.tf
variable "tag_categories" {
description = "Multiple tags / categories"
type = map(object({
name = string
tags = list(string)
}))
}
#main.tf
locals {
categories = merge([for c in var.tag_categories : {
for t in c.tags : "${c.name}-${t}" => {
tag = t
category = c.name
}
}]...)
}
resource "vsphere_tag_category" "category" {
for_each = { for k, v in var.tag_categories : k => k }
name = each.key
cardinality = "SINGLE"
description = "Managed by Terraform"
associable_types = [
"VirtualMachine",
"Datastore",
]
}
resource "vsphere_tag" "tag" {
for_each = local.categories
category_id = vsphere_tag_category.category[each.value.category].id
name = each.value.tag
description = "Managed by Terraform"
}
resource "vsphere_virtual_machine" "tag_test" {
# ... other configuration ...
tags = ${for t in vsphere_tag.tag : t.id}
}