Import vsphere_host causes recreation of host on apply

Imported existing hosts from on-premises vSphere infrastructure.

Import successful!
The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.

Look for vsphere_host resource block in state file but none there - only data blocks for vsphere_datacenter and vsphere_compute_cluster.

Open terraform console and try to look at contents of vsphere_host resource block.

PS C:\RM_LocalRepos\terraform\vsphere\licenses> terraform console
(known after apply)

Run terraform apply and get error that host already exists

 Error: host addition failed. The name '' already exists.

   on line 49, in resource "vsphere_host" "host":
   49: resource "vsphere_host" "host" {

I suspect this may be due to a mismatch of index in the resource map (using a for_each to handle multiple hosts) with the index of the input map (local)


  1. Why don’t the imported objects appear in the state file immediately after the import? When the resource block is coded for a single object (no for_each loop) it appears right away.

  2. What is the syntax to import a host and assign the hostname as the index to the resource block? I have only been successful using numeric indexes.

terraform import[21] host-7056

This is the resource block into which the import is placing data:

resource "vsphere_host" "host" {
  depends_on = [ vsphere_license.licensekey ]  
  for_each = {for entry in local.hostkeys : => entry}
    hostname = 
    username = var.vsphere_host_user 
    password = var.vsphere_password
    license  = each.value.licensekey  
    cluster  = each.value.clusterid
    force    = false

Continued doing some research and found a similar post suggesting that escaping the literal would do the trick:

So I edited the index ([""] ) and tried again - - - no luck!

PS C:\RM_LocalRepos\terraform\test66> terraform import[\"\"] host-7125

β”‚ Error: Invalid character
β”‚   on <import-address> line 1:
β”‚    1:[\\]
β”‚ This character is not used within the language.

Back to the drawing board.

Continued to investigate and found an article at:

The article stated:
Quoting resources that have indexed keys can be tricky. The best approach appears to be using a single quote around the entire resource and then escaping the double quotes in the index. For example:

actions = [ "mv docker_container.nginx 'docker_container.nginx[\"This is an example\"]'", ]

Interesting, there seem to be variations depending on the language being used.
What I took away was to revise my import statement as follows:

terraform import['\"\"']

This proved successful and the hosts were imported to the state file as expected.

Issue resolved