logo

How to add existing vSphere tags in terraform – vSphere Provisioner

So I’ve been using terraform for quite sometime now for building-tearing down my kubernetes cluster. One thing that is missing on the provisioned Virtual Machine are tags which I exclusively use for my backup-schedule retention (Veeam).

Quick Introduction on Terraform:

Terraform lets you “codify” the desired state of your infrastructure. This is awesome as it can be tracked/ checked-in on your favorit git repo.

To continue, terraform’s website has a great resource/ examples on how to provision VirtualMachine resource in vSphere but for associating tags – it’s lacking the information. The public documentation explains clearly if you want to add a new TAG but lacks the data if you want to use an existing one. (it just says import :sad:)
https://www.terraform.io/docs/providers/vsphere/d/tag.html

Anyway, here’s how to do it:

  • In your main.tf, create an empty data block bot for TAG and TAG CATEGORY. note: do not create RESOURCE as we don’t want to create new tags/ category
Create data NOT resource before importing.
  • For the tag data, reference the tag_category ID
  • Import tag_category using the command: terraform import -var-file=<vsphere credentials-if-needed> vsphere_tag_category.category <category-name>
  • Import tag using the command: terraform import -var-file=<vsphere-cred-if-needed> vsphere_tag.tag ‘{“category_name”: “<category>”, “tag_name”: “<tag-name>”}’
  • In the VirtualMachine resource block, add the following: tags = [“${data.vsphere_tag.tag.id}”]

and that’s it.

Hope that helps 🙂

Leave a Reply

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.