Fix remaining python3 compile problems

pull/18777/head
Toshio Kuratomi 8 years ago committed by Matt Clay
parent 3901fe72d3
commit ea05c56a41

@ -117,7 +117,6 @@ VIRT_FAILED = 1
VIRT_SUCCESS = 0 VIRT_SUCCESS = 0
VIRT_UNAVAILABLE=2 VIRT_UNAVAILABLE=2
import sys
try: try:
import libvirt import libvirt
@ -133,6 +132,9 @@ except ImportError:
else: else:
HAS_XML = True HAS_XML = True
from ansible.module_utils.basic import AnsibleModule
ALL_COMMANDS = [] ALL_COMMANDS = []
ENTRY_COMMANDS = ['create', 'status', 'start', 'stop', ENTRY_COMMANDS = ['create', 'status', 'start', 'stop',
'undefine', 'destroy', 'get_xml', 'define', 'undefine', 'destroy', 'get_xml', 'define',
@ -345,7 +347,7 @@ class LibvirtConnection(object):
return self.conn.networkDefineXML(xml) return self.conn.networkDefineXML(xml)
else: else:
try: try:
state = self.find_entry(entryid) self.find_entry(entryid)
except: except:
return self.module.exit_json(changed=True) return self.module.exit_json(changed=True)
@ -428,17 +430,17 @@ class VirtNetwork(object):
try: try:
results[entry]["forward_mode"] = self.conn.get_forward(entry) results[entry]["forward_mode"] = self.conn.get_forward(entry)
except ValueError as e: except ValueError:
pass pass
try: try:
results[entry]["domain"] = self.conn.get_domain(entry) results[entry]["domain"] = self.conn.get_domain(entry)
except ValueError as e: except ValueError:
pass pass
try: try:
results[entry]["macaddress"] = self.conn.get_macaddress(entry) results[entry]["macaddress"] = self.conn.get_macaddress(entry)
except ValueError as e: except ValueError:
pass pass
facts = dict() facts = dict()
@ -532,7 +534,7 @@ def core(module):
return VIRT_SUCCESS, res return VIRT_SUCCESS, res
else: else:
module.fail_json(msg="Command %s not recognized" % basecmd) module.fail_json(msg="Command %s not recognized" % command)
if autostart is not None: if autostart is not None:
if not name: if not name:
@ -580,7 +582,7 @@ def main():
rc = VIRT_SUCCESS rc = VIRT_SUCCESS
try: try:
rc, result = core(module) rc, result = core(module)
except Exception, e: except Exception as e:
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
if rc != 0: # something went wrong emit the msg if rc != 0: # something went wrong emit the msg
@ -589,6 +591,5 @@ def main():
module.exit_json(**result) module.exit_json(**result)
# import module snippets if __name__ == '__main__':
from ansible.module_utils.basic import * main()
main()

@ -128,8 +128,6 @@ VIRT_FAILED = 1
VIRT_SUCCESS = 0 VIRT_SUCCESS = 0
VIRT_UNAVAILABLE=2 VIRT_UNAVAILABLE=2
import sys
try: try:
import libvirt import libvirt
except ImportError: except ImportError:
@ -144,6 +142,9 @@ except ImportError:
else: else:
HAS_XML = True HAS_XML = True
from ansible.module_utils.basic import AnsibleModule
ALL_COMMANDS = [] ALL_COMMANDS = []
ENTRY_COMMANDS = ['create', 'status', 'start', 'stop', 'build', 'delete', ENTRY_COMMANDS = ['create', 'status', 'start', 'stop', 'build', 'delete',
'undefine', 'destroy', 'get_xml', 'define', 'refresh'] 'undefine', 'destroy', 'get_xml', 'define', 'refresh']
@ -397,7 +398,7 @@ class LibvirtConnection(object):
return self.conn.storagePoolDefineXML(xml) return self.conn.storagePoolDefineXML(xml)
else: else:
try: try:
state = self.find_entry(entryid) self.find_entry(entryid)
except: except:
return self.module.exit_json(changed=True) return self.module.exit_json(changed=True)
@ -514,23 +515,23 @@ class VirtStoragePool(object):
try: try:
results[entry]["host"] = self.conn.get_host(entry) results[entry]["host"] = self.conn.get_host(entry)
except ValueError as e: except ValueError:
pass pass
try: try:
results[entry]["source_path"] = self.conn.get_source_path(entry) results[entry]["source_path"] = self.conn.get_source_path(entry)
except ValueError as e: except ValueError:
pass pass
try: try:
results[entry]["format"] = self.conn.get_format(entry) results[entry]["format"] = self.conn.get_format(entry)
except ValueError as e: except ValueError:
pass pass
try: try:
devices = self.conn.get_devices(entry) devices = self.conn.get_devices(entry)
results[entry]["devices"] = devices results[entry]["devices"] = devices
except ValueError as e: except ValueError:
pass pass
else: else:
@ -642,7 +643,7 @@ def core(module):
return VIRT_SUCCESS, res return VIRT_SUCCESS, res
else: else:
module.fail_json(msg="Command %s not recognized" % basecmd) module.fail_json(msg="Command %s not recognized" % command)
if autostart is not None: if autostart is not None:
if not name: if not name:
@ -691,7 +692,7 @@ def main():
rc = VIRT_SUCCESS rc = VIRT_SUCCESS
try: try:
rc, result = core(module) rc, result = core(module)
except Exception, e: except Exception as e:
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
if rc != 0: # something went wrong emit the msg if rc != 0: # something went wrong emit the msg
@ -700,6 +701,5 @@ def main():
module.exit_json(**result) module.exit_json(**result)
# import module snippets if __name__ == '__main__':
from ansible.module_utils.basic import * main()
main()

@ -206,6 +206,10 @@ try:
except ImportError: except ImportError:
HAS_PB_SDK = False HAS_PB_SDK = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
LOCATIONS = ['us/las', LOCATIONS = ['us/las',
'de/fra', 'de/fra',
'de/fkb'] 'de/fkb']
@ -325,7 +329,7 @@ def _startstop_machine(module, profitbricks, datacenter_id, server_id):
return True return True
except Exception as e: except Exception as e:
module.fail_json(msg="failed to start or stop the virtual machine %s: %s" % (name, str(e))) module.fail_json(msg="failed to start or stop the virtual machine %s at %s: %s" % (server_id, datacenter_id, str(e)))
def _create_datacenter(module, profitbricks): def _create_datacenter(module, profitbricks):
@ -390,7 +394,8 @@ def create_virtual_machine(module, profitbricks):
try: try:
name % 0 name % 0
except TypeError, e: except TypeError:
e = get_exception()
if e.message.startswith('not all'): if e.message.startswith('not all'):
name = '%s%%d' % name name = '%s%%d' % name
else: else:
@ -475,7 +480,8 @@ def remove_virtual_machine(module, profitbricks):
# Remove the server # Remove the server
try: try:
server_response = profitbricks.delete_server(datacenter_id, server_id) server_response = profitbricks.delete_server(datacenter_id, server_id)
except Exception as e: except Exception:
e = get_exception()
module.fail_json(msg="failed to terminate the virtual server: %s" % str(e)) module.fail_json(msg="failed to terminate the virtual server: %s" % str(e))
else: else:
changed = True changed = True
@ -491,7 +497,8 @@ def _remove_boot_volume(module, profitbricks, datacenter_id, server_id):
server = profitbricks.get_server(datacenter_id, server_id) server = profitbricks.get_server(datacenter_id, server_id)
volume_id = server['properties']['bootVolume']['id'] volume_id = server['properties']['bootVolume']['id']
volume_response = profitbricks.delete_volume(datacenter_id, volume_id) volume_response = profitbricks.delete_volume(datacenter_id, volume_id)
except Exception as e: except Exception:
e = get_exception()
module.fail_json(msg="failed to remove the server's boot volume: %s" % str(e)) module.fail_json(msg="failed to remove the server's boot volume: %s" % str(e))
@ -609,8 +616,6 @@ def main():
subscription_user = module.params.get('subscription_user') subscription_user = module.params.get('subscription_user')
subscription_password = module.params.get('subscription_password') subscription_password = module.params.get('subscription_password')
wait = module.params.get('wait')
wait_timeout = module.params.get('wait_timeout')
profitbricks = ProfitBricksService( profitbricks = ProfitBricksService(
username=subscription_user, username=subscription_user,
@ -626,7 +631,8 @@ def main():
try: try:
(changed) = remove_virtual_machine(module, profitbricks) (changed) = remove_virtual_machine(module, profitbricks)
module.exit_json(changed=changed) module.exit_json(changed=changed)
except Exception as e: except Exception:
e = get_exception()
module.fail_json(msg='failed to set instance state: %s' % str(e)) module.fail_json(msg='failed to set instance state: %s' % str(e))
elif state in ('running', 'stopped'): elif state in ('running', 'stopped'):
@ -636,7 +642,8 @@ def main():
try: try:
(changed) = startstop_machine(module, profitbricks, state) (changed) = startstop_machine(module, profitbricks, state)
module.exit_json(changed=changed) module.exit_json(changed=changed)
except Exception as e: except Exception:
e = get_exception()
module.fail_json(msg='failed to set instance state: %s' % str(e)) module.fail_json(msg='failed to set instance state: %s' % str(e))
elif state == 'present': elif state == 'present':
@ -654,9 +661,10 @@ def main():
try: try:
(machine_dict_array) = create_virtual_machine(module, profitbricks) (machine_dict_array) = create_virtual_machine(module, profitbricks)
module.exit_json(**machine_dict_array) module.exit_json(**machine_dict_array)
except Exception as e: except Exception:
e = get_exception()
module.fail_json(msg='failed to set instance state: %s' % str(e)) module.fail_json(msg='failed to set instance state: %s' % str(e))
from ansible.module_utils.basic import *
main() if __name__ == '__main__':
main()

@ -135,7 +135,6 @@ EXAMPLES = '''
''' '''
import re import re
import uuid
import time import time
HAS_PB_SDK = True HAS_PB_SDK = True
@ -145,6 +144,10 @@ try:
except ImportError: except ImportError:
HAS_PB_SDK = False HAS_PB_SDK = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
uuid_match = re.compile( uuid_match = re.compile(
'[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12}', re.I) '[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12}', re.I)
@ -253,7 +256,8 @@ def create_volume(module, profitbricks):
try: try:
name % 0 name % 0
except TypeError, e: except TypeError:
e = get_exception()
if e.message.startswith('not all'): if e.message.startswith('not all'):
name = '%s%%d' % name name = '%s%%d' % name
else: else:
@ -354,7 +358,8 @@ def _attach_volume(module, profitbricks, datacenter, volume):
try: try:
return profitbricks.attach_volume(datacenter, server, volume) return profitbricks.attach_volume(datacenter, server, volume)
except Exception as e: except Exception:
e = get_exception()
module.fail_json(msg='failed to attach volume: %s' % str(e)) module.fail_json(msg='failed to attach volume: %s' % str(e))
@ -403,7 +408,8 @@ def main():
try: try:
(changed) = delete_volume(module, profitbricks) (changed) = delete_volume(module, profitbricks)
module.exit_json(changed=changed) module.exit_json(changed=changed)
except Exception as e: except Exception:
e = get_exception()
module.fail_json(msg='failed to set volume state: %s' % str(e)) module.fail_json(msg='failed to set volume state: %s' % str(e))
elif state == 'present': elif state == 'present':
@ -415,9 +421,10 @@ def main():
try: try:
(volume_dict_array) = create_volume(module, profitbricks) (volume_dict_array) = create_volume(module, profitbricks)
module.exit_json(**volume_dict_array) module.exit_json(**volume_dict_array)
except Exception as e: except Exception:
e = get_exception()
module.fail_json(msg='failed to set volume state: %s' % str(e)) module.fail_json(msg='failed to set volume state: %s' % str(e))
from ansible.module_utils.basic import *
main() if __name__ == '__main__':
main()

@ -125,6 +125,10 @@ except ImportError:
else: else:
mysqldb_found = True mysqldb_found = True
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.mysql import mysql_connect
from ansible.module_utils.pycompat24 import get_exception
def get_master_status(cursor): def get_master_status(cursor):
cursor.execute("SHOW MASTER STATUS") cursor.execute("SHOW MASTER STATUS")
@ -212,10 +216,6 @@ def main():
ssl_ca=dict(default=None), ssl_ca=dict(default=None),
) )
) )
user = module.params["login_user"]
password = module.params["login_password"]
host = module.params["login_host"]
port = module.params["login_port"]
mode = module.params["mode"] mode = module.params["mode"]
master_host = module.params["master_host"] master_host = module.params["master_host"]
master_user = module.params["master_user"] master_user = module.params["master_user"]
@ -250,7 +250,8 @@ def main():
try: try:
cursor = mysql_connect(module, login_user, login_password, config_file, ssl_cert, ssl_key, ssl_ca, None, 'MySQLdb.cursors.DictCursor', cursor = mysql_connect(module, login_user, login_password, config_file, ssl_cert, ssl_key, ssl_ca, None, 'MySQLdb.cursors.DictCursor',
connect_timeout=connect_timeout) connect_timeout=connect_timeout)
except Exception, e: except Exception:
e = get_exception()
if os.path.exists(config_file): if os.path.exists(config_file):
module.fail_json(msg="unable to connect to database, check login_user and login_password are correct or %s has the credentials. Exception message: %s" % (config_file, e)) module.fail_json(msg="unable to connect to database, check login_user and login_password are correct or %s has the credentials. Exception message: %s" % (config_file, e))
else: else:
@ -324,9 +325,11 @@ def main():
chm.append("MASTER_AUTO_POSITION = 1") chm.append("MASTER_AUTO_POSITION = 1")
try: try:
changemaster(cursor, chm, chm_params) changemaster(cursor, chm, chm_params)
except MySQLdb.Warning, e: except MySQLdb.Warning:
e = get_exception()
result['warning'] = str(e) result['warning'] = str(e)
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg='%s. Query == CHANGE MASTER TO %s' % (e, chm)) module.fail_json(msg='%s. Query == CHANGE MASTER TO %s' % (e, chm))
result['changed']=True result['changed']=True
module.exit_json(**result) module.exit_json(**result)
@ -355,8 +358,7 @@ def main():
else: else:
module.exit_json(msg="Slave already reset", changed=False) module.exit_json(msg="Slave already reset", changed=False)
# import module snippets
from ansible.module_utils.basic import * if __name__ == '__main__':
from ansible.module_utils.mysql import * main()
main() warnings.simplefilter("ignore")
warnings.simplefilter("ignore")

@ -82,6 +82,10 @@ except ImportError:
else: else:
pyodbc_found = True pyodbc_found = True
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
class NotSupportedError(Exception): class NotSupportedError(Exception):
pass pass
@ -164,7 +168,8 @@ def main():
module.params['login_user'], module.params['login_password'], 'true') module.params['login_user'], module.params['login_password'], 'true')
db_conn = pyodbc.connect(dsn, autocommit=True) db_conn = pyodbc.connect(dsn, autocommit=True)
cursor = db_conn.cursor() cursor = db_conn.cursor()
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg="Unable to connect to database: {0}.".format(e)) module.fail_json(msg="Unable to connect to database: {0}.".format(e))
try: try:
@ -174,21 +179,24 @@ def main():
else: else:
try: try:
changed = present(configuration_facts, cursor, parameter_name, current_value) changed = present(configuration_facts, cursor, parameter_name, current_value)
except pyodbc.Error, e: except pyodbc.Error:
e = get_exception()
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
except NotSupportedError, e: except NotSupportedError:
e = get_exception()
module.fail_json(msg=str(e), ansible_facts={'vertica_configuration': configuration_facts}) module.fail_json(msg=str(e), ansible_facts={'vertica_configuration': configuration_facts})
except CannotDropError, e: except CannotDropError:
e = get_exception()
module.fail_json(msg=str(e), ansible_facts={'vertica_configuration': configuration_facts}) module.fail_json(msg=str(e), ansible_facts={'vertica_configuration': configuration_facts})
except SystemExit: except SystemExit:
# avoid catching this on python 2.4 # avoid catching this on python 2.4
raise raise
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg=e) module.fail_json(msg=e)
module.exit_json(changed=changed, parameter=parameter_name, ansible_facts={'vertica_configuration': configuration_facts}) module.exit_json(changed=changed, parameter=parameter_name, ansible_facts={'vertica_configuration': configuration_facts})
# import ansible utilities
from ansible.module_utils.basic import *
if __name__ == '__main__': if __name__ == '__main__':
main() main()

@ -74,6 +74,10 @@ except ImportError:
else: else:
pyodbc_found = True pyodbc_found = True
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
class NotSupportedError(Exception): class NotSupportedError(Exception):
pass pass
@ -232,23 +236,22 @@ def main():
if module.params['db']: if module.params['db']:
db = module.params['db'] db = module.params['db']
changed = False
try: try:
dsn = ( dsn = (
"Driver=Vertica;" "Driver=Vertica;"
"Server={0};" "Server=%s;"
"Port={1};" "Port=%s;"
"Database={2};" "Database=%s;"
"User={3};" "User=%s;"
"Password={4};" "Password=%s;"
"ConnectionLoadBalance={5}" "ConnectionLoadBalance=%s"
).format(module.params['cluster'], module.params['port'], db, ) % (module.params['cluster'], module.params['port'], db,
module.params['login_user'], module.params['login_password'], 'true') module.params['login_user'], module.params['login_password'], 'true')
db_conn = pyodbc.connect(dsn, autocommit=True) db_conn = pyodbc.connect(dsn, autocommit=True)
cursor = db_conn.cursor() cursor = db_conn.cursor()
except Exception, e: except Exception:
module.fail_json(msg="Unable to connect to database: {0}.".format(e)) e = get_exception()
module.fail_json(msg="Unable to connect to database: %s." % str(e))
try: try:
schema_facts = get_schema_facts(cursor) schema_facts = get_schema_facts(cursor)
@ -262,15 +265,16 @@ def main():
'vertica_roles': role_facts, 'vertica_roles': role_facts,
'vertica_configuration': configuration_facts, 'vertica_configuration': configuration_facts,
'vertica_nodes': node_facts}) 'vertica_nodes': node_facts})
except NotSupportedError, e: except NotSupportedError:
e = get_exception()
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
except SystemExit: except SystemExit:
# avoid catching this on python 2.4 # avoid catching this on python 2.4
raise raise
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg=e) module.fail_json(msg=e)
# import ansible utilities
from ansible.module_utils.basic import *
if __name__ == '__main__': if __name__ == '__main__':
main() main()

@ -93,6 +93,10 @@ except ImportError:
else: else:
pyodbc_found = True pyodbc_found = True
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
class NotSupportedError(Exception): class NotSupportedError(Exception):
pass pass
@ -208,7 +212,8 @@ def main():
module.params['login_user'], module.params['login_password'], 'true') module.params['login_user'], module.params['login_password'], 'true')
db_conn = pyodbc.connect(dsn, autocommit=True) db_conn = pyodbc.connect(dsn, autocommit=True)
cursor = db_conn.cursor() cursor = db_conn.cursor()
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg="Unable to connect to database: {0}.".format(e)) module.fail_json(msg="Unable to connect to database: {0}.".format(e))
try: try:
@ -218,26 +223,30 @@ def main():
elif state == 'absent': elif state == 'absent':
try: try:
changed = absent(role_facts, cursor, role, assigned_roles) changed = absent(role_facts, cursor, role, assigned_roles)
except pyodbc.Error, e: except pyodbc.Error:
e = get_exception()
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
elif state == 'present': elif state == 'present':
try: try:
changed = present(role_facts, cursor, role, assigned_roles) changed = present(role_facts, cursor, role, assigned_roles)
except pyodbc.Error, e: except pyodbc.Error:
e = get_exception()
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
except NotSupportedError, e: except NotSupportedError:
e = get_exception()
module.fail_json(msg=str(e), ansible_facts={'vertica_roles': role_facts}) module.fail_json(msg=str(e), ansible_facts={'vertica_roles': role_facts})
except CannotDropError, e: except CannotDropError:
e = get_exception()
module.fail_json(msg=str(e), ansible_facts={'vertica_roles': role_facts}) module.fail_json(msg=str(e), ansible_facts={'vertica_roles': role_facts})
except SystemExit: except SystemExit:
# avoid catching this on python 2.4 # avoid catching this on python 2.4
raise raise
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg=e) module.fail_json(msg=e)
module.exit_json(changed=changed, role=role, ansible_facts={'vertica_roles': role_facts}) module.exit_json(changed=changed, role=role, ansible_facts={'vertica_roles': role_facts})
# import ansible utilities
from ansible.module_utils.basic import *
if __name__ == '__main__': if __name__ == '__main__':
main() main()

@ -117,6 +117,10 @@ except ImportError:
else: else:
pyodbc_found = True pyodbc_found = True
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
class NotSupportedError(Exception): class NotSupportedError(Exception):
pass pass
@ -282,7 +286,8 @@ def main():
module.params['login_user'], module.params['login_password'], 'true') module.params['login_user'], module.params['login_password'], 'true')
db_conn = pyodbc.connect(dsn, autocommit=True) db_conn = pyodbc.connect(dsn, autocommit=True)
cursor = db_conn.cursor() cursor = db_conn.cursor()
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg="Unable to connect to database: {0}.".format(e)) module.fail_json(msg="Unable to connect to database: {0}.".format(e))
try: try:
@ -292,26 +297,30 @@ def main():
elif state == 'absent': elif state == 'absent':
try: try:
changed = absent(schema_facts, cursor, schema, usage_roles, create_roles) changed = absent(schema_facts, cursor, schema, usage_roles, create_roles)
except pyodbc.Error, e: except pyodbc.Error:
e = get_exception()
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
elif state == 'present': elif state == 'present':
try: try:
changed = present(schema_facts, cursor, schema, usage_roles, create_roles, owner) changed = present(schema_facts, cursor, schema, usage_roles, create_roles, owner)
except pyodbc.Error, e: except pyodbc.Error:
e = get_exception()
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
except NotSupportedError, e: except NotSupportedError:
e = get_exception()
module.fail_json(msg=str(e), ansible_facts={'vertica_schemas': schema_facts}) module.fail_json(msg=str(e), ansible_facts={'vertica_schemas': schema_facts})
except CannotDropError, e: except CannotDropError:
e = get_exception()
module.fail_json(msg=str(e), ansible_facts={'vertica_schemas': schema_facts}) module.fail_json(msg=str(e), ansible_facts={'vertica_schemas': schema_facts})
except SystemExit: except SystemExit:
# avoid catching this on python 2.4 # avoid catching this on python 2.4
raise raise
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg=e) module.fail_json(msg=e)
module.exit_json(changed=changed, schema=schema, ansible_facts={'vertica_schemas': schema_facts}) module.exit_json(changed=changed, schema=schema, ansible_facts={'vertica_schemas': schema_facts})
# import ansible utilities
from ansible.module_utils.basic import *
if __name__ == '__main__': if __name__ == '__main__':
main() main()

@ -130,6 +130,10 @@ except ImportError:
else: else:
pyodbc_found = True pyodbc_found = True
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
class NotSupportedError(Exception): class NotSupportedError(Exception):
pass pass
@ -351,7 +355,8 @@ def main():
module.params['login_user'], module.params['login_password'], 'true') module.params['login_user'], module.params['login_password'], 'true')
db_conn = pyodbc.connect(dsn, autocommit=True) db_conn = pyodbc.connect(dsn, autocommit=True)
cursor = db_conn.cursor() cursor = db_conn.cursor()
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg="Unable to connect to database: {0}.".format(e)) module.fail_json(msg="Unable to connect to database: {0}.".format(e))
try: try:
@ -362,27 +367,31 @@ def main():
elif state == 'absent': elif state == 'absent':
try: try:
changed = absent(user_facts, cursor, user, roles) changed = absent(user_facts, cursor, user, roles)
except pyodbc.Error, e: except pyodbc.Error:
e = get_exception()
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
elif state in ['present', 'locked']: elif state in ['present', 'locked']:
try: try:
changed = present(user_facts, cursor, user, profile, resource_pool, changed = present(user_facts, cursor, user, profile, resource_pool,
locked, password, expired, ldap, roles) locked, password, expired, ldap, roles)
except pyodbc.Error, e: except pyodbc.Error:
e = get_exception()
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
except NotSupportedError, e: except NotSupportedError:
e = get_exception()
module.fail_json(msg=str(e), ansible_facts={'vertica_users': user_facts}) module.fail_json(msg=str(e), ansible_facts={'vertica_users': user_facts})
except CannotDropError, e: except CannotDropError:
e = get_exception()
module.fail_json(msg=str(e), ansible_facts={'vertica_users': user_facts}) module.fail_json(msg=str(e), ansible_facts={'vertica_users': user_facts})
except SystemExit: except SystemExit:
# avoid catching this on python 2.4 # avoid catching this on python 2.4
raise raise
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg=e) module.fail_json(msg=e)
module.exit_json(changed=changed, user=user, ansible_facts={'vertica_users': user_facts}) module.exit_json(changed=changed, user=user, ansible_facts={'vertica_users': user_facts})
# import ansible utilities
from ansible.module_utils.basic import *
if __name__ == '__main__': if __name__ == '__main__':
main() main()

@ -22,19 +22,6 @@ You should have received a copy of the GNU General Public License
along with Ansible. If not, see <http://www.gnu.org/licenses/>. along with Ansible. If not, see <http://www.gnu.org/licenses/>.
""" """
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
# Let snippet from module_utils/basic.py return a proper error in this case
pass
import datetime
import base64
import os
DOCUMENTATION = ''' DOCUMENTATION = '''
module: boundary_meter module: boundary_meter
@ -88,15 +75,33 @@ EXAMPLES='''
''' '''
import base64
import os
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
# Let snippet from module_utils/basic.py return a proper error in this case
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_url
api_host = "api.boundary.com" api_host = "api.boundary.com"
config_directory = "/etc/bprobe" config_directory = "/etc/bprobe"
# "resource" like thing or apikey? # "resource" like thing or apikey?
def auth_encode(apikey): def auth_encode(apikey):
auth = base64.standard_b64encode(apikey) auth = base64.standard_b64encode(apikey)
auth.replace("\n", "") auth.replace("\n", "")
return auth return auth
def build_url(name, apiid, action, meter_id=None, cert_type=None): def build_url(name, apiid, action, meter_id=None, cert_type=None):
if action == "create": if action == "create":
return 'https://%s/%s/meters' % (api_host, apiid) return 'https://%s/%s/meters' % (api_host, apiid)
@ -198,7 +203,7 @@ def delete_meter(module, name, apiid, apikey):
try: try:
cert_file = '%s/%s.pem' % (config_directory,cert_type) cert_file = '%s/%s.pem' % (config_directory,cert_type)
os.remove(cert_file) os.remove(cert_file)
except OSError, e: except OSError:
module.fail_json("Failed to remove " + cert_type + ".pem file") module.fail_json("Failed to remove " + cert_type + ".pem file")
return 0, "Meter " + name + " deleted" return 0, "Meter " + name + " deleted"
@ -256,9 +261,7 @@ def main():
module.exit_json(status=result,changed=True) module.exit_json(status=result,changed=True)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.urls import *
if __name__ == '__main__': if __name__ == '__main__':
main() main()

@ -17,9 +17,6 @@
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import requests
import time
import json
DOCUMENTATION = ''' DOCUMENTATION = '''
--- ---
@ -86,6 +83,15 @@ EXAMPLES = '''
start_time: 1395940006 start_time: 1395940006
end_time: 1395954407 end_time: 1395954407
''' '''
import json
import time
import requests
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
def post_annotation(annotation, api_key): def post_annotation(annotation, api_key):
''' Takes annotation dict and api_key string''' ''' Takes annotation dict and api_key string'''
base_url = 'https://api.circonus.com/v2' base_url = 'https://api.circonus.com/v2'
@ -95,6 +101,7 @@ def post_annotation(annotation, api_key):
resp.raise_for_status() resp.raise_for_status()
return resp return resp
def create_annotation(module): def create_annotation(module):
''' Takes ansible module object ''' ''' Takes ansible module object '''
annotation = {} annotation = {}
@ -116,6 +123,8 @@ def create_annotation(module):
annotation['description'] = module.params['description'] annotation['description'] = module.params['description']
annotation['title'] = module.params['title'] annotation['title'] = module.params['title']
return annotation return annotation
def build_headers(api_token): def build_headers(api_token):
'''Takes api token, returns headers with it included.''' '''Takes api token, returns headers with it included.'''
headers = {'X-Circonus-App-Name': 'ansible', headers = {'X-Circonus-App-Name': 'ansible',
@ -123,6 +132,7 @@ def build_headers(api_token):
'Accept': 'application/json'} 'Accept': 'application/json'}
return headers return headers
def main(): def main():
'''Main function, dispatches logic''' '''Main function, dispatches logic'''
module = AnsibleModule( module = AnsibleModule(
@ -139,9 +149,11 @@ def main():
annotation = create_annotation(module) annotation = create_annotation(module)
try: try:
resp = post_annotation(annotation, module.params['api_key']) resp = post_annotation(annotation, module.params['api_key'])
except requests.exceptions.RequestException, err_str: except requests.exceptions.RequestException:
err_str = get_exception()
module.fail_json(msg='Request Failed', reason=err_str) module.fail_json(msg='Request Failed', reason=err_str)
module.exit_json(changed=True, annotation=resp.json()) module.exit_json(changed=True, annotation=resp.json())
from ansible.module_utils.basic import *
main() if __name__ == '__main__':
main()

@ -19,13 +19,6 @@
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# import module snippets # import module snippets
# Import Datadog
try:
from datadog import initialize, api
HAS_DATADOG = True
except:
HAS_DATADOG = False
DOCUMENTATION = ''' DOCUMENTATION = '''
--- ---
module: datadog_monitor module: datadog_monitor
@ -144,6 +137,16 @@ datadog_monitor:
app_key: "87ce4a24b5553d2e482ea8a8500e71b8ad4554ff" app_key: "87ce4a24b5553d2e482ea8a8500e71b8ad4554ff"
''' '''
# Import Datadog
try:
from datadog import initialize, api
HAS_DATADOG = True
except:
HAS_DATADOG = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
def main(): def main():
module = AnsibleModule( module = AnsibleModule(
@ -211,7 +214,8 @@ def _post_monitor(module, options):
module.fail_json(msg=str(msg['errors'])) module.fail_json(msg=str(msg['errors']))
else: else:
module.exit_json(changed=True, msg=msg) module.exit_json(changed=True, msg=msg)
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
def _equal_dicts(a, b, ignore_keys): def _equal_dicts(a, b, ignore_keys):
@ -234,7 +238,8 @@ def _update_monitor(module, monitor, options):
module.exit_json(changed=False, msg=msg) module.exit_json(changed=False, msg=msg)
else: else:
module.exit_json(changed=True, msg=msg) module.exit_json(changed=True, msg=msg)
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
@ -269,7 +274,8 @@ def delete_monitor(module):
try: try:
msg = api.Monitor.delete(monitor['id']) msg = api.Monitor.delete(monitor['id'])
module.exit_json(changed=True, msg=msg) module.exit_json(changed=True, msg=msg)
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
@ -288,7 +294,8 @@ def mute_monitor(module):
else: else:
msg = api.Monitor.mute(id=monitor['id'], silenced=module.params['silenced']) msg = api.Monitor.mute(id=monitor['id'], silenced=module.params['silenced'])
module.exit_json(changed=True, msg=msg) module.exit_json(changed=True, msg=msg)
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
@ -301,10 +308,10 @@ def unmute_monitor(module):
try: try:
msg = api.Monitor.unmute(monitor['id']) msg = api.Monitor.unmute(monitor['id'])
module.exit_json(changed=True, msg=msg) module.exit_json(changed=True, msg=msg)
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
from ansible.module_utils.basic import * if __name__ == '__main__':
from ansible.module_utils.urls import * main()
main()

@ -78,6 +78,11 @@ EXAMPLES = '''
import urllib import urllib
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.urls import fetch_url
def main(): def main():
module = AnsibleModule( module = AnsibleModule(
@ -120,7 +125,8 @@ def main():
try: try:
data = urllib.urlencode(params) data = urllib.urlencode(params)
response, info = fetch_url(module, url, data=data) response, info = fetch_url(module, url, data=data)
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg='Unable to notify Rollbar: %s' % e) module.fail_json(msg='Unable to notify Rollbar: %s' % e)
else: else:
if info['status'] == 200: if info['status'] == 200:
@ -128,7 +134,6 @@ def main():
else: else:
module.fail_json(msg='HTTP result code: %d connecting to %s' % (info['status'], url)) module.fail_json(msg='HTTP result code: %d connecting to %s' % (info['status'], url))
from ansible.module_utils.basic import *
from ansible.module_utils.urls import *
main() if __name__ == '__main__':
main()

@ -102,6 +102,10 @@ except ImportError:
# Let snippet from module_utils/basic.py return a proper error in this case # Let snippet from module_utils/basic.py return a proper error in this case
pass pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.urls import fetch_url
def send_deploy_event(module, key, revision_id, deployed_by='Ansible', deployed_to=None, repository=None): def send_deploy_event(module, key, revision_id, deployed_by='Ansible', deployed_to=None, repository=None):
"""Send a deploy event to Stackdriver""" """Send a deploy event to Stackdriver"""
@ -195,7 +199,8 @@ def main():
module.fail_json(msg="revision_id required for deploy events") module.fail_json(msg="revision_id required for deploy events")
try: try:
send_deploy_event(module, key, revision_id, deployed_by, deployed_to, repository) send_deploy_event(module, key, revision_id, deployed_by, deployed_to, repository)
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg="unable to sent deploy event: %s" % e) module.fail_json(msg="unable to sent deploy event: %s" % e)
if event == 'annotation': if event == 'annotation':
@ -203,14 +208,13 @@ def main():
module.fail_json(msg="msg required for annotation events") module.fail_json(msg="msg required for annotation events")
try: try:
send_annotation_event(module, key, msg, annotated_by, level, instance_id, event_epoch) send_annotation_event(module, key, msg, annotated_by, level, instance_id, event_epoch)
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg="unable to sent annotation event: %s" % e) module.fail_json(msg="unable to sent annotation event: %s" % e)
changed = True changed = True
module.exit_json(changed=changed, deployed_by=deployed_by) module.exit_json(changed=changed, deployed_by=deployed_by)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.urls import *
main() if __name__ == '__main__':
main()

@ -18,16 +18,6 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
# Let snippet from module_utils/basic.py return a proper error in this case
pass
import urllib
DOCUMENTATION = ''' DOCUMENTATION = '''
--- ---
module: cloudflare_dns module: cloudflare_dns
@ -269,6 +259,22 @@ record:
sample: sample.com sample: sample.com
''' '''
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
# Let snippet from module_utils/basic.py return a proper error in this case
pass
import urllib
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.urls import fetch_url
class CloudflareAPI(object): class CloudflareAPI(object):
cf_api_endpoint = 'https://api.cloudflare.com/client/v4' cf_api_endpoint = 'https://api.cloudflare.com/client/v4'
@ -315,8 +321,9 @@ class CloudflareAPI(object):
if payload: if payload:
try: try:
data = json.dumps(payload) data = json.dumps(payload)
except Exception, e: except Exception:
self.module.fail_json(msg="Failed to encode payload as JSON: {0}".format(e)) e = get_exception()
self.module.fail_json(msg="Failed to encode payload as JSON: %s " % str(e))
resp, info = fetch_url(self.module, resp, info = fetch_url(self.module,
self.cf_api_endpoint + api_call, self.cf_api_endpoint + api_call,
@ -636,9 +643,6 @@ def main():
changed = cf_api.delete_dns_records(solo=False) changed = cf_api.delete_dns_records(solo=False)
module.exit_json(changed=changed) module.exit_json(changed=changed)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.urls import *
if __name__ == '__main__': if __name__ == '__main__':
main() main()

@ -86,6 +86,10 @@ except ImportError:
else: else:
bigsuds_found = True bigsuds_found = True
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.f5 import bigip_api, f5_argument_spec
def server_exists(api, server): def server_exists(api, server):
# hack to determine if virtual server exists # hack to determine if virtual server exists
@ -93,7 +97,8 @@ def server_exists(api, server):
try: try:
api.GlobalLB.Server.get_object_status([server]) api.GlobalLB.Server.get_object_status([server])
result = True result = True
except bigsuds.OperationFailed, e: except bigsuds.OperationFailed:
e = get_exception()
if "was not found" in str(e): if "was not found" in str(e):
result = False result = False
else: else:
@ -109,7 +114,8 @@ def virtual_server_exists(api, name, server):
virtual_server_id = {'name': name, 'server': server} virtual_server_id = {'name': name, 'server': server}
api.GlobalLB.VirtualServerV2.get_object_status([virtual_server_id]) api.GlobalLB.VirtualServerV2.get_object_status([virtual_server_id])
result = True result = True
except bigsuds.OperationFailed, e: except bigsuds.OperationFailed:
e = get_exception()
if "was not found" in str(e): if "was not found" in str(e):
result = False result = False
else: else:
@ -222,14 +228,12 @@ def main():
else: else:
result = {'changed': True} result = {'changed': True}
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg="received exception: %s" % e) module.fail_json(msg="received exception: %s" % e)
module.exit_json(**result) module.exit_json(**result)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.f5 import *
if __name__ == '__main__': if __name__ == '__main__':
main() main()

@ -71,6 +71,11 @@ except ImportError:
else: else:
bigsuds_found = True bigsuds_found = True
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.f5 import bigip_api, f5_argument_spec
def get_wide_ip_lb_method(api, wide_ip): def get_wide_ip_lb_method(api, wide_ip):
lb_method = api.GlobalLB.WideIP.get_lb_method(wide_ips=[wide_ip])[0] lb_method = api.GlobalLB.WideIP.get_lb_method(wide_ips=[wide_ip])[0]
lb_method = lb_method.strip().replace('LB_METHOD_', '').lower() lb_method = lb_method.strip().replace('LB_METHOD_', '').lower()
@ -79,8 +84,9 @@ def get_wide_ip_lb_method(api, wide_ip):
def get_wide_ip_pools(api, wide_ip): def get_wide_ip_pools(api, wide_ip):
try: try:
return api.GlobalLB.WideIP.get_wideip_pool([wide_ip]) return api.GlobalLB.WideIP.get_wideip_pool([wide_ip])
except Exception, e: except Exception:
print e e = get_exception()
print(e)
def wide_ip_exists(api, wide_ip): def wide_ip_exists(api, wide_ip):
# hack to determine if wide_ip exists # hack to determine if wide_ip exists
@ -88,7 +94,8 @@ def wide_ip_exists(api, wide_ip):
try: try:
api.GlobalLB.WideIP.get_object_status(wide_ips=[wide_ip]) api.GlobalLB.WideIP.get_object_status(wide_ips=[wide_ip])
result = True result = True
except bigsuds.OperationFailed, e: except bigsuds.OperationFailed:
e = get_exception()
if "was not found" in str(e): if "was not found" in str(e):
result = False result = False
else: else:
@ -145,14 +152,12 @@ def main():
else: else:
result = {'changed': True} result = {'changed': True}
except Exception, e: except Exception:
e = get_exception()
module.fail_json(msg="received exception: %s" % e) module.fail_json(msg="received exception: %s" % e)
module.exit_json(**result) module.exit_json(**result)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.f5 import *
if __name__ == '__main__': if __name__ == '__main__':
main() main()

@ -1,18 +0,0 @@
/cloud/misc/virt_net.py
/cloud/misc/virt_pool.py
/cloud/profitbricks/profitbricks.py
/cloud/profitbricks/profitbricks_volume.py
/database/mysql/mysql_replication.py
/database/vertica/vertica_configuration.py
/database/vertica/vertica_facts.py
/database/vertica/vertica_role.py
/database/vertica/vertica_schema.py
/database/vertica/vertica_user.py
/monitoring/boundary_meter.py
/monitoring/circonus_annotation.py
/monitoring/datadog_monitor.py
/monitoring/rollbar_deployment.py
/monitoring/stackdriver.py
/network/cloudflare_dns.py
/network/f5/bigip_gtm_virtual_server.py
/network/f5/bigip_gtm_wide_ip.py
Loading…
Cancel
Save