Created
October 26, 2016 00:16
-
-
Save beejhuff/7add755c15b44de75ded104f9e0012f2 to your computer and use it in GitHub Desktop.
VMware Fusion Ansible dynamic inventory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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