Skip to content

Instantly share code, notes, and snippets.

@beejhuff
Forked from phips/wip.py
Created October 26, 2016 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beejhuff/7add755c15b44de75ded104f9e0012f2 to your computer and use it in GitHub Desktop.
Save beejhuff/7add755c15b44de75ded104f9e0012f2 to your computer and use it in GitHub Desktop.
VMware Fusion Ansible dynamic inventory
#!/usr/bin/env python
import sys
import subprocess
import re
import string
try:
import json
except:
import simplejson as json
def get_vm_ip(vmxfile):
''' Return the IP of a running VM '''
vmrun = '/Applications/VMware Fusion.app/Contents/Library/vmrun'
try:
ip = subprocess.check_output([vmrun, 'getGuestIPAddress', vmxfile]).strip()
return ip
except Exception, error:
return None
def list_running_vms():
''' List the running VMs '''
vmrun = "/Applications/VMware Fusion.app/Contents/Library/vmrun"
output = subprocess.check_output( [vmrun, "list"]).split('\n')
vms = []
for line in output:
matcher = re.search("\.vmx$", line)
if matcher:
vms.append(matcher.string)
return vms
if __name__ == "__main__":
if len(sys.argv) < 2:
print "Usage:"
print sys.argv[0], " --list"
sys.exit(1)
vmname = re.compile(".+ / (.+) \.vmx",re.X)
hosts = { 'fusion': [] }
vms = list_running_vms()
for vm in vms:
name = vmname.match(vm).group(1)
hosts['fusion'].append(get_vm_ip(vm))
print json.dumps(hosts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment