Bringing Cloud Director resources under the control of Terraform
This week I was busy creating some virtual datacenters in VMware Cloud Director with Hashicorp Terraform. Everything was fine until a colleague made some manual changes in the environment. Now, the state file of Terraform was no longer up-to-date and I had to come up with a way to get it in sync again.
For this, I could use the terraform import command. But this command has some limitations:
- you can only import one resource at a time
- you have to manually write the matching code for that resource
- the state file is immediately modified
But as of version 1.5, Terraform introduced a new way of importing existing resources. See https://www.hashicorp.com/blog/terraform-1-5-brings-config-driven-import-and-checks for details.
This new way means that resources can be imported in bulk and it is a plan operation instead of a state operation. So there is no risk of unexpected state modification.
But the best part is that Terraform 1.5 introduces automatic code generation for imported resources. So how does this work?
In the import block, you use two parameters: the ID of the resource that you want to import and the HCL address of the new resource. I put this code in a separate import.tf file.
In this example, I want to import a VMware Cloud Director organization and for the ID I use the name of that organization. Now when you run terraform plan you can add the new parameter -generate-config-out. The complete command looks like this:
terraform plan -generate-config-out="generated-config.tf"
The file generated-config.tf now contains the generated code for the organization resource. When the generated code looks okay you can perform the import by running terraform apply. What I did was copy the contents of the generated-config.tf to my main.tf and delete the generated-config.tf file. Now I can add other resources to the import.tf file and import other resources to my configuration.