Skip to content

Instantly share code, notes, and snippets.

@phips
Last active June 19, 2017 14:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save phips/30c8eceaf82288577c93 to your computer and use it in GitHub Desktop.
Save phips/30c8eceaf82288577c93 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