def __init__(self, adminProxyHostname, user, hostname, adminProxyProtocol='https', adminProxyPort=443, adminProxyApplianceShortName=False): self.logger = logging.getLogger(__name__) self.logger.debug('Creating an ISDSAppliance over AdminProxy') self.adminProxyProtocol = adminProxyProtocol self.adminProxyHostname = adminProxyHostname # Type checking and tranformation to safely reuse this variable later on if isinstance(adminProxyPort, basestring): self.adminProxyPort = int(adminProxyPort) else: self.adminProxyPort = adminProxyPort self.adminProxyApplianceShortName = adminProxyApplianceShortName ISDSAppliance.__init__(self, hostname, user)
}, 'requests.packages.urllib3.connectionpool': { 'level': 'ERROR', 'handlers': ['default'], 'propagate': True } } } logging.config.dictConfig(DEFAULT_LOGGING) # Function to pretty print JSON data and in YAML format def p(jdata): pp = pprint.PrettyPrinter(indent=2) pp.pprint(jdata) print(yaml.safe_dump(jdata, encoding='utf-8', allow_unicode=True)) # Create a user credential for ISDS appliance u = ISDSApplianceUser(username="******", password="******") # Create an ISDS appliance with above credential isds_server = ISDSAppliance(hostname="192.168.198.100", user=u, lmi_port=443) # Get the current SNMP monitoring setup details p(ibmsecurity.isds.snmp_monitoring.get(isdsAppliance=isds_server)) # Set the V2 SNMP monitoring p( ibmsecurity.isds.snmp_monitoring.set_v1v2(isdsAppliance=isds_server, community="IBM")) # Commit or Deploy the changes p(ibmsecurity.isds.appliance.commit(isamAppliance=isds_server))
def main(): module = AnsibleModule( argument_spec=dict( log=dict(required=False, default='INFO', choices=['DEBUG', 'INFO', 'ERROR', 'CRITICAL']), appliance=dict(required=True), lmi_port=dict(required=False, default=443, type='int'), action=dict(required=True), force=dict(required=False, default=False, type='bool'), username=dict(required=False), password=dict(required=True), isdsapi=dict(required=False, type='dict'), adminProxyProtocol=dict(required=False, default='https', choices=['http','https']), adminProxyHostname=dict(required=False), adminProxyPort=dict(required=False, default=443, type='int'), adminProxyApplianceShortName=dict(required=False, default=False, type='bool'), omitAdminProxy=dict(required=False, default=False, type='bool') ), supports_check_mode=True ) module.debug('Started isds module') # Process all Arguments logLevel = module.params['log'] force = module.params['force'] action = module.params['action'] appliance = module.params['appliance'] lmi_port = module.params['lmi_port'] username = module.params['username'] password = module.params['password'] adminProxyProtocol = module.params['adminProxyProtocol'] adminProxyHostname = module.params['adminProxyHostname'] adminProxyPort = module.params['adminProxyPort'] adminProxyApplianceShortName = module.params['adminProxyApplianceShortName'] omitAdminProxy = module.params['omitAdminProxy'] # Setup logging for format, set log level and redirect to string strlog = StringIO() DEFAULT_LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '[%(asctime)s] [PID:%(process)d TID:%(thread)d] [%(levelname)s] [%(name)s] [%(funcName)s():%(lineno)s] %(message)s' }, }, 'handlers': { 'default': { 'level': logLevel, 'formatter': 'standard', 'class': 'logging.StreamHandler', 'stream': strlog }, }, 'loggers': { '': { 'handlers': ['default'], 'level': logLevel, 'propagate': True }, 'requests.packages.urllib3.connectionpool': { 'handlers': ['default'], 'level': 'ERROR', 'propagate': True } } } logging.config.dictConfig(DEFAULT_LOGGING) # Create appliance object to be used for all calls if username == '' or username is None: u = ApplianceUser(password=password) else: u = ApplianceUser(username=username, password=password) # Create appliance object to be used for all calls # if adminProxy hostname is set, use the ISDSApplianceAdminProxy if adminProxyHostname == '' or adminProxyHostname is None or omitAdminProxy: isds_server = ISDSAppliance(hostname=appliance, user=u, lmi_port=lmi_port) else: isds_server = ISDSApplianceAdminProxy(adminProxyHostname=adminProxyHostname, user=u, hostname=appliance, adminProxyProtocol=adminProxyProtocol, adminProxyPort=adminProxyPort, adminProxyApplianceShortName=adminProxyApplianceShortName) # Create options string to pass to action method options = 'isdsAppliance=isds_server, force=' + str(force) if module.check_mode is True: options = options + ', check_mode=True' if isinstance(module.params['isdsapi'], dict): try: basestring except NameError: basestring = (str, bytes) try: for key, value in module.params['isdsapi'].iteritems(): if isinstance(value, basestring): options = options + ', ' + key + '="' + value + '"' else: options = options + ', ' + key + '=' + str(value) except AttributeError: for key, value in module.params['isdsapi'].items(): if isinstance(value, basestring): options = options + ', ' + key + '="' + value + '"' else: options = options + ', ' + key + '=' + str(value) module.debug('Option to be passed to action: ' + options) # Dynamically process the action to be invoked # Simple check to restrict calls to just "isds" ones for safety if action.startswith('ibmsecurity.isds.'): try: module_name, method_name = action.rsplit('.', 1) module.debug('Action method to be imported from module: ' + module_name) module.debug('Action method name is: ' + method_name) mod = importlib.import_module(module_name) func_ptr = getattr(mod, method_name) # Convert action to actual function pointer func_call = 'func_ptr(' + options + ')' startd = datetime.datetime.now() # Execute requested 'action' ret_obj = eval(func_call) endd = datetime.datetime.now() delta = endd - startd ret_obj['stdout'] = strlog.getvalue() ret_obj['stdout_lines'] = strlog.getvalue().split() ret_obj['start'] = str(startd) ret_obj['end'] = str(endd) ret_obj['delta'] = str(delta) ret_obj['cmd'] = action + "(" + options + ")" ret_obj['ansible_facts'] = isds_server.facts module.exit_json(**ret_obj) except ImportError: module.fail_json(name=action, msg='Error> action belongs to a module that is not found!', log=strlog.getvalue()) except AttributeError: module.fail_json(name=action, msg='Error> invalid action was specified, method not found in module!', log=strlog.getvalue()) except TypeError: module.fail_json(name=action, msg='Error> action does not have the right set of arguments or there is a code bug! Options: ' + options, log=strlog.getvalue()) except IBMError as e: module.fail_json(name=action, msg=str(e), log=strlog.getvalue()) else: module.fail_json(name=action, msg='Error> invalid action specified, needs to be isds!', log=strlog.getvalue())
# Function to pretty print JSON data def p(jdata): pp = pprint.PrettyPrinter(indent=2) pp.pprint(jdata) if __name__ == "__main__": """ This test program should not execute when imported, which would otherwise cause problems when generating the documentation. """ # Create a user credential for ISDS appliance u = ApplianceUser(username="******", password="******") # Create an ISDS appliance with above credential isds_server = ISDSAppliance(hostname="192.168.203.116", user=u, lmi_port=443) ################ ACTIVE TEST ################ p(ibmsecurity.isds.host_records.get(isdsAppliance=isds_server)) ################ ACTIVE TEST ################ # # Successfully tested # # Any changes needed to the isam code that this is based on is documented, # or new functions added that will flow to the isam code; # see lines starting with "Note:". # # Lines starting with "TBD:" are work not done yet. # ####
'propagate': True } } } logging.config.dictConfig(DEFAULT_LOGGING) def p(jdata): pp = pprint.PrettyPrinter(indent=2) pp.pprint(jdata) print(yaml.safe_dump(jdata, encoding='utf-8', allow_unicode=True)) u = ISDSApplianceUser(username="******", password="******") # isds_server = ISDSAppliance(hostname="isds8otech", user=u, lmi_port=443) isds_server = ISDSAppliance(hostname="isds81dz", user=u, lmi_port=443) isds_server2 = ISDSAppliance(hostname="isds8otech", user=u, lmi_port=443) ################ ACTIVE TEST ################ p( ibmsecurity.isds.snapshots.apply(isdsAppliance=isds_server, id="24b4b8f1f71bd6b5a07e0e2cc43e93db")) ################ ACTIVE TEST ################ # # Successfully tested # # Any changes needed to the isam code that this is based on is documented, # or new functions added that will flow to the isam code; # see lines starting with "Note:". #