Monday, October 15, 2012

Using PowerCLI to retrieve IP from VM annotations

In our environment, we have a lot of VMs on NAT’d addresses. On occassion, I need acccess to their public IP - eg, for pinging to verify guests are still running if we put a host into maintenance mode. Grabbing the address from the internal system for each VM is time consuming and somewhat annoying. vSphere reports the private IP in the GUI which isn’t what I want. You can extract the info from the VM with PowerCLI, but again, it’s a little awkward (for my skill level). And we don’t label the VMs by their DNS name, it’s more an internal system, which again, makes identifying a particular machine harder than I would like, but that’s the way the system is.

Luckily, when we create VMs, we add annotations. One of which contains the public IP (or it should if people fill in the details :-)

That allows a way to grab the public IP with a one liner (here the assumption is the annotation field is called Public IP).

For VM called “foo” :

get-vm  foo|  get-annotation | where-object {$_.name -eq "Public IP"}

For all VMs in a VC :

get-vm | get-annotation | where-object {$_.name -eq "Public IP"}

Or, if we want just the powered on VMs :

get-vm | where-object {$_.powerstate -eq "PoweredOn"} | get-annotation | where-object {$_.name -eq "Public IP"}

I export them to .csv, and now have a more manageable way of quickly being able to call upon the relevant IPs