Skip to content
Permalink
Browse files

Simple interface

  • Loading branch information
marco-buratto committed Oct 11, 2019
1 parent beaf522 commit 2d2e3c42d9c012df9223c6676a1207685620ec42
@@ -0,0 +1,4 @@
/.idea
ansible.log
*.pyc
*.swp
@@ -0,0 +1,12 @@
[defaults]
#interpreter_python = auto

log_path = /tmp/ansible.log
host_key_checking = false
retry_files_enabled = False
deprecation_warnings = False
gathering = explicit
[paramiko_connection]
host_key_auto_add = True


@@ -0,0 +1,7 @@
---

- hosts: localhost

roles:
- role: browse_folders

@@ -0,0 +1,7 @@
---

- hosts: localhost

roles:
- role: deploy_template

@@ -0,0 +1,102 @@
def simplifyPgclusterStructure(o):
cluster = dict()

for v in o:
cluster[v['cluster']] = []

for portgroup in v['portgroup']:
for portgroupValue in portgroup['value']:
portgroupValueName = portgroupValue['portgroup']
portgroupValueVlanId = portgroupValue['vlan_id']

save = True # if not portgroupValueName in cluster[v['cluster']] for all inner objects:
for ccluster in cluster[v['cluster']]:
if ccluster['portgroup'] == portgroupValueName:
save = False

if save:
cluster[v['cluster']].append({
'portgroup': portgroupValueName,
'vlanId': portgroupValueVlanId
})

return cluster



def buildFolderTree(o):
tree = dict()

def treeAttach(parent, child):
ret = dict()
for d in o:
if d['name'] == parent:
ret['parent'] = d['parent']
ret['name'] = parent + '/' + child

return ret

for f in o:
name = f['name']
parent = f['parent']

# mind folders with the same name
el = name
n = 1
while el in tree:
el = name + '_' + str(n)
n += 1

# put datacenter name as parent for 'vm' folder
if name == 'vm':
tree[el] = parent + '/' + name
else:
tree[el] = name
rTree = ''

while parent != 'vm':
rTree = treeAttach(parent, tree[el])
parent = rTree['parent']
tree[el] = rTree['name']
tree[el] = parent + '/' + tree[el]

return tree



def vsphereListTemplates(o):
from pyVmomi import vim
from pyVim import connect
import ssl

templatesList = []

def get_vim_objects(content, vim_type):
'''Get vim objects of a given type.'''
return [item for item in content.viewManager.CreateContainerView(
content.rootFolder, [vim_type], recursive=True).view]

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_NONE
si = connect.SmartConnect(host=o["VMWARE_HOST"], user=o["VMWARE_USER"], pwd=o["VMWARE_PASSWORD"],
port=443, sslContext=context)
content = si.RetrieveContent()
for vm in get_vim_objects(content, vim.VirtualMachine):
if vm.config.template:
templatesList.append({
"guest_name": vm.name
})

return templatesList



class FilterModule(object):

def filters(self):
return {
"simplify_pgcluster_structure": simplifyPgclusterStructure,
"buildFolderTree": buildFolderTree,
"vsphere_list_templates": vsphereListTemplates
}

@@ -0,0 +1 @@
validate_certs: no
@@ -0,0 +1,118 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright: (c) 2017, Tim Rightnour <thegarbledone@gmail.com>
# Copyright: (c) 2018, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}

DOCUMENTATION = '''
---
module: vmware_datacenter_facts
short_description: Gather datacenters list in given vCenter
description:
- This module can be used to gather the list of the datacenters in VMWare infrastructure.
- All values and VMware object names are case sensitive.
notes:
- Tested on 6.5 and 6.7
requirements:
- "python >= 2.6"
- PyVmomi
extends_documentation_fragment: vmware.documentation
'''

EXAMPLES = '''
- name: Gather datacenter list
vmware_datacenter_list:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
delegate_to: localhost
register: facts
'''

RETURN = """
datacenters:
description: name of all the available datacenters
returned: always
type: list
sample: [
{
"name": "datacenter2",
},
]
"""

try:
from pyVmomi import vim
except ImportError:
pass

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import (PyVmomi, vmware_argument_spec, get_all_objs)


class PyVmomiCache(object):
""" This class caches references to objects which are requested multiples times but not modified """
def __init__(self, content):
self.content = content

def get_all_objs(self, content, types):
objects = get_all_objs(content, types)
return objects


class PyVmomiHelper(PyVmomi):
def __init__(self, module):
super(PyVmomiHelper, self).__init__(module)
self.cache = PyVmomiCache(self.content)

def lookup_datacenter(self):
datacenter = self.cache.get_all_objs(self.content, [vim.Datacenter])
return datacenter


def main():
argument_spec = vmware_argument_spec()
argument_spec.update(
name=dict(type='str'),
datacenter=dict(type='str'),
)
module = AnsibleModule(argument_spec=argument_spec)
result = dict(changed=False)

pyv = PyVmomiHelper(module)

dxs = pyv.lookup_datacenter()

datacenters = list()
for ds in dxs:
dds = dict()
dds['name'] = ds.name
datacenters.extend([dds])

result['datacenters'] = datacenters

# found a datacenter
if datacenters:
module.exit_json(**result)
else:
msg = "Unable to gather datastore facts"
if module.params['name']:
msg += " for %(name)s" % module.params
msg += " in datacenter %(datacenter)s" % module.params
module.fail_json(msg=msg)


if __name__ == '__main__':
main()

0 comments on commit 2d2e3c4

Please sign in to comment.
You can’t perform that action at this time.