def main(): try: # Arguments/parameters that a user can pass to the module module_args = dict( state=dict(type='str', choices=['present', 'absent', 'restored'], default='present'), # Checkpoint state idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True), # IDG connection domain=dict(type='str', required=True), # Domain name=dict(type='str', required=True) # Checkpoint ) # AnsibleModule instantiation module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) # Validates the dependence of the utility module if not HAS_IDG_DEPS: module.fail_json(msg="The IDG utils modules is required") # Parse arguments to dict idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) # Status & domain state = module.params['state'] domain_name = module.params['domain'] chkpoint_name = module.params['name'] # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format( idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) # Action messages: # Save checkpoint save_act_msg = {"SaveCheckpoint": {"ChkName": chkpoint_name}} # Rollback checkpoint rollback_act_msg = {"RollbackCheckpoint": {"ChkName": chkpoint_name}} # Remove checkpoint remove_act_msg = {"RemoveCheckpoint": {"ChkName": chkpoint_name}} # # Here the action begins # # Variable to store the status of the action action_result = '' # Intermediate values for result tmp_result = { "name": chkpoint_name, "domain": domain_name, "msg": None, "changed": None, "failed": None } # List of configured domains chk_code, chk_msg, chk_data = idg_mgmt.api_call(IDGApi.URI_DOMAIN_LIST, method='GET') if chk_code == 200 and chk_msg == 'OK': # If the answer is correct if isinstance(chk_data['domain'], dict): # if has only default domain configured_domains = [chk_data['domain']['name']] else: configured_domains = [d['name'] for d in chk_data['domain']] if domain_name in configured_domains: # Domain EXIST. # pdb.set_trace() if state == 'present': # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module, result) # pdb.set_trace() create_code, create_msg, create_data = idg_mgmt.api_call( IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(save_act_msg)) if create_code == 202 and create_msg == 'Accepted': # Asynchronous actions save accepted. Wait for complete action_result = idg_mgmt.wait_for_action_end( IDGApi.URI_ACTION.format(domain_name), href=create_data['_links']['location']['href'], state=state) # Create checkpoint completed. Get result dcr_code, dcr_msg, dcr_data = idg_mgmt.api_call( create_data['_links']['location']['href'], method='GET') if dcr_code == 200 and dcr_msg == 'OK': if dcr_data['status'] == 'error': # pdb.set_trace() tmp_result['changed'] = False if ("Configuration Checkpoint '" + chkpoint_name + "' already exists." ) in dcr_data['error']: tmp_result[ 'msg'] = IDGUtils.IMMUTABLE_MESSAGE else: tmp_result[ 'msg'] = IDGApi.GENERAL_ERROR.format( __MODULE_FULLNAME, state, domain_name) + str( ErrorHandler( dcr_data['error'])) tmp_result['failed'] = True else: tmp_result['msg'] = dcr_data[ 'status'].capitalize() tmp_result['changed'] = True else: # Can't retrieve the create checkpoint result module.fail_json( msg=IDGApi.ERROR_RETRIEVING_RESULT.format( state, domain_name)) elif create_code == 200 and create_msg == 'OK': # Successfully processed synchronized action tmp_result['msg'] = idg_mgmt.status_text( create_data['SaveCheckpoint']) tmp_result['changed'] = True else: # Create checkpoint not accepted module.fail_json( msg=IDGApi.ERROR_ACCEPTING_ACTION.format( state, domain_name)) elif state == 'absent': # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module, result) # pdb.set_trace() rm_code, rm_msg, rm_data = idg_mgmt.api_call( IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(remove_act_msg)) if rm_code == 202 and rm_msg == 'Accepted': # Asynchronous actions remove accepted. Wait for complete action_result = idg_mgmt.wait_for_action_end( IDGApi.URI_ACTION.format(domain_name), href=rm_data['_links']['location']['href'], state=state) # Remove checkpoint completed. Get result drm_code, drm_msg, drm_data = idg_mgmt.api_call( rm_data['_links']['location']['href'], method='GET') if drm_code == 200 and drm_msg == 'OK': if drm_data['status'] == 'error': # pdb.set_trace() tmp_result[ 'msg'] = IDGApi.GENERAL_ERROR.format( __MODULE_FULLNAME, state, domain_name) + str( ErrorHandler(drm_data['error'])) tmp_result['changed'] = False tmp_result['failed'] = True else: tmp_result['msg'] = drm_data[ 'status'].capitalize() tmp_result['changed'] = True else: # Can't retrieve the create checkpoint result module.fail_json( msg=IDGApi.ERROR_RETRIEVING_RESULT.format( state, domain_name)) elif rm_code == 200 and rm_msg == 'OK': # Successfully processed synchronized action tmp_result['msg'] = idg_mgmt.status_text( rm_data['RemoveCheckpoint']) tmp_result['changed'] = True elif rm_code == 400 and rm_msg == 'Bad Request': # Wrong request, maybe there simply is no checkpoint if ("Cannot find Configuration Checkpoint '" + chkpoint_name + "'.") in rm_data['error']: tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE else: tmp_result['msg'] = IDGApi.GENERAL_ERROR.format( __MODULE_FULLNAME, state, domain_name) + str( ErrorHandler(rm_data['error'])) tmp_result['failed'] = True else: # Create checkpoint not accepted module.fail_json( msg=IDGApi.ERROR_ACCEPTING_ACTION.format( state, domain_name)) elif state == 'restored': # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module, result) # pdb.set_trace() bak_code, bak_msg, bak_data = idg_mgmt.api_call( IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(rollback_act_msg)) if bak_code == 202 and bak_msg == 'Accepted': # Asynchronous actions remove accepted. Wait for complete action_result = idg_mgmt.wait_for_action_end( IDGApi.URI_ACTION.format(domain_name), href=bak_data['_links']['location']['href'], state=state) # Remove checkpoint completed. Get result dbak_code, dbak_msg, dbak_data = idg_mgmt.api_call( bak_data['_links']['location']['href'], method='GET') if dbak_code == 200 and dbak_msg == 'OK': if dbak_data['status'] == 'error': # pdb.set_trace() tmp_result[ 'msg'] = IDGApi.GENERAL_ERROR.format( __MODULE_FULLNAME, state, domain_name) + str( ErrorHandler(dbak_data['error'])) tmp_result['changed'] = False tmp_result['failed'] = True else: tmp_result['msg'] = dbak_data[ 'status'].capitalize() tmp_result['changed'] = True else: # Can't retrieve the create checkpoint result module.fail_json( msg=IDGApi.ERROR_RETRIEVING_RESULT.format( state, domain_name)) elif bak_code == 200 and bak_msg == 'OK': # Successfully processed synchronized action tmp_result['msg'] = idg_mgmt.status_text( bak_data['RollbackCheckpoint']) tmp_result['changed'] = True else: # Create checkpoint not accepted module.fail_json( msg=IDGApi.ERROR_ACCEPTING_ACTION.format( state, domain_name)) else: # Domain NOT EXIST. # Can't work the configuration of non-existent domain module.fail_json( msg=(IDGApi.ERROR_REACH_STATE + " " + IDGApi.ERROR_NOT_DOMAIN).format(state, domain_name)) else: # Can't read domain's lists module.fail_json(msg=IDGApi.ERROR_GET_DOMAIN_LIST) # # Finish # # Update for k, v in tmp_result.items(): if v != None: result[k] = v except (NameError, UnboundLocalError) as e: # Very early error module_except = AnsibleModule(argument_spec={}) module_except.fail_json(msg=to_native(e)) except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)
def main(): # Validates the dependence of the utility module if HAS_IDG_DEPS: module_args = dict( filter=dict(type='str', required=False, default=None), # Service to search ignore_case=dict(type='bool', required=False, default=True), # # Case-insensitive matching domain=dict(type='str', required=True), # Domain name idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True) # IDG connection ) # AnsibleModule instantiation module = AnsibleModule( argument_spec=module_args, supports_check_mode=True, # Interaction between parameters required_if=[['ignore_case', False, ['filter']]] ) else: # Failure AnsibleModule instance module = AnsibleModule( argument_spec={}, check_invalid_arguments=False ) module.fail_json(msg="The IDG utils modules is required") # Parse arguments to dict idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) # Service to search service_filter = module.params['filter'] filter_flags = re.IGNORECASE if module.params['ignore_case'] else 0 domain_name = module.params['domain'] # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format(idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) # Intermediate values for result tmp_result = {"msg": IDGUtils.COMPLETED_MESSAGE, "domain": domain_name, "service_status": []} # # Here the action begins # # pdb.set_trace() try: # List of configured domains and their status idg_mgmt.api_call(IDGApi.URI_STATUS.format(domain_name) + "/ServicesStatus", method='GET', id="list_configured_domains") if idg_mgmt.is_ok(idg_mgmt.last_call()): # If the answer is correct # List of existing services if "ServicesStatus" in idg_mgmt.last_call()["data"].keys(): if service_filter is not None: active_services = [s for s in AbstractListDict(idg_mgmt.last_call()["data"]['ServicesStatus']).raw_data() if re.match(service_filter, s['ServiceName'], filter_flags)] else: active_services = idg_mgmt.last_call()["data"]['ServicesStatus'] tmp_result['service_status'] = active_services else: tmp_result['msg'] = idg_mgmt.last_call()["data"]['result'] else: # Can't read service's status module.fail_json(msg=IDGApi.GENERAL_STATELESS_ERROR.format(__MODULE_FULLNAME, domain_name) + str(ErrorHandler(idg_mgmt.last_call()["data"]['error']))) # # Finish # # Customize del result['name'] # Update for k, v in tmp_result.items(): if v is not None: result[k] = v except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)
def main(): # Validates the dependence of the utility module if HAS_IDG_DEPS: module_args = dict( state=dict(type='str', required=False, default='directory', choices=['absent', 'directory', 'move', 'show']), # State alternatives path=dict(type='str', required=True), # Path to resource source=dict( type='str', required=False), # Source. Only valid when state = move overwrite=dict( type='bool', required=False, default=False), # overwrite target. Valid when state = move domain=dict(type='str', required=True), # Domain name idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True) # IDG connection ) # AnsibleModule instantiation module = AnsibleModule( argument_spec=module_args, supports_check_mode=True, required_if=[["state", "move", ["source", "overwrite"]]]) else: # Failure AnsibleModule instance module = AnsibleModule(argument_spec={}, check_invalid_arguments=False) module.fail_json(msg="The IDG utils modules is required") # Parse arguments to dict idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) path = module.params['path'] state = module.params['state'] domain_name = module.params['domain'] # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format( idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) # Intermediate values for result tmp_result = { "domain": domain_name, "msg": None, "path": None, "changed": None, "output": None } # # Here the action begins # pdb.set_trace() try: # Do request parse = urlparse(path) ldir = parse.scheme # Local directory rpath = parse.path # Relative path path_as_list = [d for d in rpath.split('/') if d.strip() != ''] td = '/'.join([IDGApi.URI_FILESTORE.format(domain_name), ldir]) # Path prefix if state == 'directory': # Create directory recursively for d in path_as_list: idg_mgmt.api_call(td, method='GET', id="get_remote_directory") if idg_mgmt.is_ok(idg_mgmt.last_call()): td = '/'.join([td, d]) tmp_result['path'] = idg_mgmt.apifilestore_uri2path(td) if 'directory' in idg_mgmt.last_call( )["data"]['filestore']['location'].keys(): filestore_abst = AbstractListDict( idg_mgmt.last_call()["data"]['filestore'] ['location']['directory']) # Get directories else: filestore_abst = AbstractListDict( {}) # Not contain directories if ('href' in filestore_abst.keys()) and ( td in filestore_abst.values( key='href')): # if directory exist tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE else: # Not exist, create it # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module) create_dir_msg = {"directory": {"name": d}} idg_mgmt.api_call(td, method='PUT', data=json.dumps(create_dir_msg), id="create_directory") if idg_mgmt.is_created(idg_mgmt.last_call()): tmp_result['msg'] = idg_mgmt.last_call( )["data"]['result'] tmp_result['changed'] = True else: module.fail_json( msg=IDGApi.ERROR_REACH_STATE.format( state, domain_name) + str( ErrorHandler(idg_mgmt.last_call() ["data"]['error']))) else: module.fail_json(msg=IDGApi.GENERAL_ERROR.format( __MODULE_FULLNAME, state, domain_name) + str( ErrorHandler( idg_mgmt.call_by_id("get_remote_directory") ["data"]['error']))) elif state == 'move': # Move remote files # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module) move_file_msg = { "MoveFile": { "sURL": module.params['source'].strip('/'), "dURL": path.strip('/'), "Overwrite": IDGUtils.str_on_off(module.params['overwrite']) } } tmp_result['path'] = move_file_msg['MoveFile']['dURL'] idg_mgmt.api_call(IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(move_file_msg), id="move_file") if idg_mgmt.is_ok(idg_mgmt.last_call()): tmp_result['msg'] = idg_mgmt.last_call()["data"]['MoveFile'] tmp_result['changed'] = True else: module.fail_json( msg=IDGApi.ERROR_REACH_STATE.format(state, domain_name) + str(ErrorHandler(idg_mgmt.last_call()["data"]['error']))) elif state == 'show': # Show details of file or content of directories # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module) list_target = '/'.join([td] + path_as_list) idg_mgmt.api_call(list_target, method='GET', id="get_remote_target") if idg_mgmt.is_ok(idg_mgmt.last_call()): output = {} if 'filestore' in idg_mgmt.last_call()["data"].keys( ): # is directory if 'directory' in idg_mgmt.last_call( )["data"]['filestore']['location'].keys(): output['directory'] = [{ "name": i["name"] } for i in AbstractListDict( idg_mgmt.last_call()["data"]['filestore'] ['location']['directory']).raw_data()] if 'file' in idg_mgmt.last_call( )["data"]['filestore']['location'].keys(): output['file'] = [{ "name": i["name"], "size": i["size"], "modified": i["modified"] } for i in AbstractListDict(idg_mgmt.last_call( )["data"]['filestore']['location']['file']).raw_data()] else: idg_mgmt.api_call('/'.join([td] + path_as_list[:-1]), method='GET', id="get_file_detail") if idg_mgmt.is_ok(idg_mgmt.last_call()): output = [{ "name": i["name"], "size": i["size"], "modified": i["modified"] } for i in idg_mgmt.last_call()["data"]['filestore'] ['location']['file'] if i['name'] == path_as_list[-1]] else: module.fail_json(msg=IDGApi.ERROR_REACH_STATE.format( state, domain_name) + str( ErrorHandler(idg_mgmt.last_call()["data"] ['error']))) tmp_result['msg'] = IDGUtils.COMPLETED_MESSAGE tmp_result['path'] = idg_mgmt.apifilestore_uri2path( list_target) tmp_result['output'] = output else: module.fail_json(msg=IDGApi.GENERAL_ERROR.format( __MODULE_FULLNAME, state, domain_name) + str( ErrorHandler( idg_mgmt.call_by_id("get_remote_target")["data"] ['error']))) else: # Remove # Remove directory recursively # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module) td = '/'.join([td] + path_as_list) idg_mgmt.api_call(td, method='DELETE', id="remove_remote_target") tmp_result['path'] = idg_mgmt.apifilestore_uri2path(td) if idg_mgmt.is_ok(idg_mgmt.last_call()): tmp_result['msg'] = idg_mgmt.last_call()["data"]['result'] tmp_result['changed'] = True elif idg_mgmt.is_notfound(idg_mgmt.last_call()): tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE else: module.fail_json( msg=IDGApi.ERROR_REACH_STATE.format(state, domain_name) + str(ErrorHandler(idg_mgmt.last_call()["data"]['error']))) # # Finish # # Customize del result['name'] # Update for k, v in tmp_result.items(): if v is not None: result[k] = v except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)
def main(): # Validates the dependence of the utility module if HAS_IDG_DEPS: # Arguments/parameters that a user can pass to the module module_args = dict( time_zone=dict(type='str', choices=["HST10", "AKST9AKDT", "PST8PDT", "MST7MDT", "CST6CDT", "EST5EDT", "AST4ADT", "UTC", "GMT0BST", "CET-1CEST", "EET-2EEST", "MSK-3MSD", "AST-3", "KRT-5", "IST-5:30", "NOVST-6NOVDT", "CST-8", "WST-8", "JST-9", "CST-9:30CDT", "EST-10EDT", "EST-10"]), # Time zone date=dict(type='str'), time=dict(type='str'), idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True) # IDG connection ) # AnsibleModule instantiation module = AnsibleModule( argument_spec=module_args, supports_check_mode=True ) else: # Failure AnsibleModule instance module = AnsibleModule( argument_spec={}, check_invalid_arguments=False ) module.fail_json(msg="The IDG utils modules is required") # Parameters time_zone = module.params['time_zone'] date = module.params['date'] time = module.params['time'] domain_name = "default" # System's level configurations are always do in default domain # Parse arguments to dict idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format(idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) # Quiesce timezone_msg = { "LocalTimeZone": time_zone } # Intermediate values for result tmp_result = {"msg": None, "changed": False, "failed": None} # # Here the action begins # pdb.set_trace() try: # Get time settings idg_mgmt.api_call(IDGApi.URI_STATUS.format(domain_name) + "/DateTimeStatus", method='GET', id="get_datetime_status") if idg_mgmt.is_ok(idg_mgmt.last_call()): # If the answer is correct configured_timezone = idg_mgmt.last_call()["data"]["DateTimeStatus"]["tzspec"].split(',')[0] if (time_zone is not None) and (configured_timezone != time_zone): # Need change de time zone # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module) idg_mgmt.api_call(IDGApi.URI_CONFIG.format(domain_name) + "/TimeSettings/Time/LocalTimeZone", method='PUT', data=json.dumps(timezone_msg), id="set_local_timezone") if idg_mgmt.is_ok(idg_mgmt.last_call()): tmp_result["changed"]=True tmp_result["msg"] = idg_mgmt.last_call()["data"]["LocalTimeZone"] if date or time: # New Date/Time values configured_datetime = datetime.strptime(idg_mgmt.call_by_id("get_datetime_status")["data"]["DateTimeStatus"]["time"], "%a %b %d %H:%M:%S %Y") datetime_msg = {"SetTimeAndDate":{}} if date: ndate = datetime.strptime(date, "%Y-%m-%d") if configured_datetime.date() != ndate.date(): datetime_msg["SetTimeAndDate"].update({"Date": date}) if time: ntime = datetime.strptime(time, "%H:%M:%S") if configured_datetime.time() != ntime.time(): datetime_msg["SetTimeAndDate"].update({"Time": time}) if ("Date" in datetime_msg["SetTimeAndDate"].keys()) or ("Time" in datetime_msg["SetTimeAndDate"].keys()): idg_mgmt.api_call(IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(datetime_msg), id="set_datetime") if idg_mgmt.is_ok(idg_mgmt.last_call()): tmp_result["changed"]=True tmp_result["msg"] = idg_mgmt.last_call()["data"]["SetTimeAndDate"] else: module.fail_json(msg=IDGApi.GENERAL_STATELESS_ERROR.format(__MODULE_FULLNAME, domain_name) + str(ErrorHandler(idg_mgmt.last_call()["data"]['error']))) if not tmp_result["changed"]: # The current configuration is identical to the new configuration, there is nothing to do tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE else: # Can't read the settings module.fail_json(msg="Could not be read the current time settings") # # Finish # # Customize del result['name'] # Update for k, v in tmp_result.items(): if v is not None: result[k] = v except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)
def main(): # Validates the dependence of the utility module if HAS_IDG_DEPS: # Arguments/parameters that a user can pass to the module module_args = dict( state=dict(type='str', choices=['present', 'absent', 'restored'], default='present'), # Checkpoint state idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True), # IDG connection domain=dict(type='str', required=True), # Domain name=dict(type='str', required=True) # Checkpoint ) # AnsibleModule instantiation module = AnsibleModule( argument_spec=module_args, supports_check_mode=True ) else: # Failure AnsibleModule instance module = AnsibleModule( argument_spec={}, check_invalid_arguments=False ) module.fail_json(msg="The IDG utils modules is required") # Parse arguments to dict idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) # Status & domain state = module.params['state'] domain_name = module.params['domain'] chkpoint_name = module.params['name'] # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format(idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) # Action messages: CHKPOINT_STATUS="DomainCheckpointStatus" # Save checkpoint save_act_msg = {"SaveCheckpoint": {"ChkName": chkpoint_name}} # Rollback checkpoint rollback_act_msg = {"RollbackCheckpoint": {"ChkName": chkpoint_name}} # Remove checkpoint remove_act_msg = {"RemoveCheckpoint": {"ChkName": chkpoint_name}} # Variable to store the status of the action action_result = '' # Intermediate values for result tmp_result = {"name": chkpoint_name, "domain": domain_name, "msg": None, "changed": None, "failed": None} # # Here the action begins # pdb.set_trace() try: # List of configured domains idg_mgmt.api_call(IDGApi.URI_DOMAIN_LIST, method='GET', id="list_domains") if idg_mgmt.is_ok(idg_mgmt.last_call()): # If the answer is correct # List of existing domains configured_domains = IDGUtils.domains_list(idg_mgmt.last_call()["data"]['domain']) if domain_name in configured_domains: # Domain EXIST. idg_mgmt.api_call(IDGApi.URI_STATUS.format(domain_name) + "/" + CHKPOINT_STATUS, method='GET', id="list_chkpoints") if idg_mgmt.is_ok(idg_mgmt.last_call()): chkpoints = AbstractListDict(idg_mgmt.last_call()["data"][CHKPOINT_STATUS]) else: module.fail_json(msg=IDGApi.ERROR_REACH_STATE.format(state, domain_name) + " Unable to get " + CHKPOINT_STATUS) if state == 'present': if chkpoint_name not in chkpoints.values(key="ChkName"): # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module) idg_mgmt.api_call(IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(save_act_msg), id="create_chkpoint") if idg_mgmt.is_accepted(idg_mgmt.last_call()): # Asynchronous actions save accepted. Wait for complete idg_mgmt.api_event_sink(IDGApi.URI_ACTION.format(domain_name), href=idg_mgmt.last_call()["data"]['_links']['location']['href'], state=state) if idg_mgmt.is_ok(idg_mgmt.last_call()): if idg_mgmt.last_call()["data"]["status"] == 'error': module.fail_json(msg=IDGApi.GENERAL_ERROR.format(__MODULE_FULLNAME, state, domain_name) + str(ErrorHandler(idg_mgmt.last_call()["data"]['error']))) else: tmp_result['msg'] = idg_mgmt.last_call()["data"]["status"].capitalize() tmp_result['changed'] = True else: # Can't retrieve the create checkpoint result module.fail_json(msg=IDGApi.ERROR_RETRIEVING_RESULT.format(state, domain_name)) else: # Create checkpoint not accepted module.fail_json(msg=IDGApi.ERROR_ACCEPTING_ACTION.format(state, domain_name)) else: tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE elif state == 'absent': if chkpoint_name in chkpoints.values(key="ChkName"): # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module) # pdb.set_trace() idg_mgmt.api_call(IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(remove_act_msg), id="remove_chkpoint") if idg_mgmt.is_ok(idg_mgmt.last_call()): # Successfully processed synchronized action tmp_result['msg'] = idg_mgmt.status_text(idg_mgmt.last_call()["data"]['RemoveCheckpoint']) tmp_result['changed'] = True else: # Create checkpoint not accepted module.fail_json(msg=IDGApi.ERROR_ACCEPTING_ACTION.format(state, domain_name)) else: tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE elif state == 'restored': if chkpoint_name in chkpoints.values(key="ChkName"): # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module) idg_mgmt.api_call(IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(rollback_act_msg), id="restore_from_chkpoint") if idg_mgmt.is_accepted(idg_mgmt.last_call()): # Asynchronous actions remove accepted. Wait for complete idg_mgmt.api_event_sink(IDGApi.URI_ACTION.format(domain_name), href=idg_mgmt.last_call()["data"]['_links']['location']['href'], state=state) if idg_mgmt.is_ok(idg_mgmt.last_call()): if idg_mgmt.last_call()["data"]['status'] == 'error': module.fail_json(msg=IDGApi.GENERAL_ERROR.format(__MODULE_FULLNAME, state, domain_name) + str(ErrorHandler(idg_mgmt.last_call()["data"]['error']))) else: tmp_result['msg'] = idg_mgmt.last_call()["data"]['status'].capitalize() tmp_result['changed'] = True else: # Can't retrieve the create checkpoint result module.fail_json(msg=IDGApi.ERROR_RETRIEVING_RESULT.format(state, domain_name)) else: # Create checkpoint not accepted module.fail_json(msg=IDGApi.ERROR_ACCEPTING_ACTION.format(state, domain_name)) else: # Can't work the configuration of non-existent checkpoint module.fail_json(msg=(IDGApi.ERROR_REACH_STATE).format(state, domain_name) + " CheckPoint not exist.") else: # Domain NOT EXIST. # Can't work the configuration of non-existent domain module.fail_json(msg=(IDGApi.ERROR_REACH_STATE + " " + IDGApi.ERROR_NOT_DOMAIN).format(state, domain_name)) else: # Can't read domain's lists module.fail_json(msg=IDGApi.ERROR_GET_DOMAIN_LIST) # # Finish # # Update for k, v in tmp_result.items(): if v is not None: result[k] = v except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)
def main(): try: # Arguments/parameters that a user can pass to the module module_args = dict( state=dict(type='str', choices=['exported', 'imported', 'reseted', 'saved'], default='saved'), # Domain's operational state idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True), # IDG connection name=dict(type='str', required=True), # Domain to work # for Export user_summary=dict(type='str'), # Backup comment all_files=dict( type='bool', default=False ), # Include all files in the local: directory for the domain persisted=dict(type='bool', default=False ), # Export from persisted or running configuration internal_files=dict( type='bool', default=True), # Export internal configuration file # for Import input_file=dict(type='str', required=False, no_log=True), # The base64-encoded BLOB to import overwrite_files=dict(type='bool', default=False), # Overwrite files that exist overwrite_objects=dict( type='bool', default=False), # Overwrite objects that exist dry_run=dict( type='bool', default=False ), # Import package (on) or validate the import operation without importing (off). rewrite_local_ip=dict( type='bool', default=False ) # The local address binding to their equivalent interfaces in appliance # TODO !!! # DeploymentPolicy ) # AnsibleModule instantiation module = AnsibleModule( argument_spec=module_args, supports_check_mode=True, # Interaction between parameters required_if=[['state', 'imported', ['input_file']]]) # Validates the dependence of the utility module if not HAS_IDG_DEPS: module.fail_json(msg="The IDG utils modules is required") # Parse arguments to dict idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) # Status & domain state = module.params['state'] domain_name = module.params['name'] # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format( idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) # Variable to store the status of the action action_result = '' # Configuration template for the domain export_action_msg = { "Export": { "Format": "ZIP", "UserComment": module.params['user_summary'], "AllFiles": IDGUtils.str_on_off(module.params['all_files']), "Persisted": IDGUtils.str_on_off(module.params['persisted']), "IncludeInternalFiles": IDGUtils.str_on_off(module.params['internal_files']) # TODO # "DeploymentPolicy":"" } } import_action_msg = { "Import": { "Format": "ZIP", "InputFile": module.params['input_file'], "OverwriteFiles": IDGUtils.str_on_off(module.params['overwrite_files']), "OverwriteObjects": IDGUtils.str_on_off(module.params['overwrite_objects']), "DryRun": IDGUtils.str_on_off(module.params['dry_run']), "RewriteLocalIP": IDGUtils.str_on_off(module.params['rewrite_local_ip']) # TODO # "DeploymentPolicy": "name", # "DeploymentPolicyParams": "name", } } # Action messages # Reset reset_act_msg = {"ResetThisDomain": {}} # Save save_act_msg = {"SaveConfig": {}} # # Here the action begins # # Intermediate values for result tmp_result = { "name": domain_name, "msg": None, "file": None, "changed": None, "failed": None } # List of configured domains chk_code, chk_msg, chk_data = idg_mgmt.api_call(IDGApi.URI_DOMAIN_LIST, method='GET') if chk_code == 200 and chk_msg == 'OK': # If the answer is correct if isinstance(chk_data['domain'], dict): # if has only default domain configured_domains = [chk_data['domain']['name']] else: configured_domains = [d['name'] for d in chk_data['domain']] if domain_name in configured_domains: # Domain EXIST. # pdb.set_trace() if state == 'exported': # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module, result) # export and finish # pdb.set_trace() exp_code, exp_msg, exp_data = idg_mgmt.api_call( IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(export_action_msg)) if exp_code == 202 and exp_msg == 'Accepted': # Asynchronous actions export accepted. Wait for complete action_result = idg_mgmt.wait_for_action_end( IDGApi.URI_ACTION.format(domain_name), href=exp_data['_links']['location']['href'], state=state) # Export completed. Get result doex_code, doex_msg, doex_data = idg_mgmt.api_call( exp_data['_links']['location']['href'], method='GET') if doex_code == 200 and doex_msg == 'OK': # Export ok tmp_result['file'] = doex_data['result']['file'] tmp_result['msg'] = action_result tmp_result['changed'] = True else: # Can't retrieve the export module.fail_json( msg=IDGApi.ERROR_RETRIEVING_RESULT.format( state, domain_name)) elif exp_code == 200 and exp_msg == 'OK': # Successfully processed synchronized action tmp_result['msg'] = idg_mgmt.status_text( exp_data['Export']) tmp_result['changed'] = True else: # Export not accepted module.fail_json( msg=IDGApi.ERROR_ACCEPTING_ACTION.format( state, domain_name)) elif state == 'reseted': # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module, result) # Reseted domain reset_code, reset_msg, reset_data = idg_mgmt.api_call( IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(reset_act_msg)) # pdb.set_trace() if reset_code == 202 and reset_msg == 'Accepted': # Asynchronous actions reset accepted. Wait for complete action_result = idg_mgmt.wait_for_action_end( IDGApi.URI_ACTION.format(domain_name), href=reset_data['_links']['location']['href'], state=state) # Reseted completed dore_code, dore_msg, dore_data = idg_mgmt.api_call( reset_data['_links']['location']['href'], method='GET') if dore_code == 200 and dore_msg == 'OK': # Reseted successfully tmp_result['msg'] = dore_data['status'].capitalize( ) tmp_result['changed'] = True else: # Can't retrieve the reset result module.fail_json( msg=IDGApi.ERROR_RETRIEVING_RESULT.format( state, domain_name)) elif reset_code == 200 and reset_msg == 'OK': # Successfully processed synchronized action tmp_result['msg'] = idg_mgmt.status_text( reset_data['ResetThisDomain']) tmp_result['changed'] = True else: # Reseted not accepted module.fail_json( msg=IDGApi.ERROR_ACCEPTING_ACTION.format( state, domain_name)) elif state == 'saved': qds_code, qds_msg, qds_data = idg_mgmt.api_call( IDGApi.URI_DOMAIN_STATUS, method='GET') # pdb.set_trace() if qds_code == 200 and qds_msg == 'OK': if isinstance(qds_data['DomainStatus'], dict): domain_save_needed = qds_data['DomainStatus'][ 'SaveNeeded'] else: domain_save_needed = [ d['SaveNeeded'] for d in qds_data['DomainStatus'] if d['Domain'] == domain_name ][0] # Saved domain if domain_save_needed != 'off': # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module, result) save_code, save_msg, save_data = idg_mgmt.api_call( IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(save_act_msg)) # pdb.set_trace() if save_code == 202 and save_msg == 'Accepted': # Asynchronous actions save accepted. Wait for complete action_result = idg_mgmt.wait_for_action_end( IDGApi.URI_ACTION.format(domain_name), href=save_data['_links']['location'] ['href'], state=state) # Save ready dosv_code, dosv_msg, dosv_data = idg_mgmt.api_call( save_data['_links']['location']['href'], method='GET') if dosv_code == 200 and dosv_msg == 'OK': # Save completed tmp_result['msg'] = action_result tmp_result['changed'] = True else: # Can't retrieve the save result module.fail_json( msg=IDGApi.ERROR_RETRIEVING_RESULT. format(state, domain_name)) elif save_code == 200 and save_msg == 'OK': # Successfully processed synchronized action save tmp_result['msg'] = idg_mgmt.status_text( save_data['SaveConfig']) tmp_result['changed'] = True else: # Can't saved module.fail_json( msg=IDGApi.ERROR_RETRIEVING_RESULT.format( state, domain_name)) else: # Domain is save tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE elif state == 'imported': # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module, result) # Import # pdb.set_trace() imp_code, imp_msg, imp_data = idg_mgmt.api_call( IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(import_action_msg)) if imp_code == 202 and imp_msg == 'Accepted': # Asynchronous actions import accepted. Wait for complete action_result = idg_mgmt.wait_for_action_end( IDGApi.URI_ACTION.format(domain_name), href=imp_data['_links']['location']['href'], state=state) # Import ready doim_code, doim_msg, doim_data = idg_mgmt.api_call( imp_data['_links']['location']['href'], method='GET') if doim_code == 200 and doim_msg == 'OK': # Export completed import_results = doim_data['result']['Import'][ 'import-results'] if import_results['detected-errors'] != 'false': # Import failed # pdb.set_trace() tmp_result[ 'msg'] = 'Import failed with error code: "' + import_results[ 'detected-errors']['error'] + '"' tmp_result['changed'] = False tmp_result['failed'] = True else: # Import success tmp_result.update({"results": []}) # Update to result tmp_result['results'].append({ "export-details": import_results['export-details'] }) # EXEC-SCRIPT-RESULTS try: exec_script_results = import_results[ 'exec-script-results'] try: if isinstance( exec_script_results[ 'cfg-result'], list): tmp_result['results'].append({ "exec-script-results": { "summary": { "total": len(exec_script_results[ 'cfg-result']), "status": get_status_summary( exec_script_results[ 'cfg-result']) }, "detail": exec_script_results[ 'cfg-result'] } }) else: tmp_result['results'].append({ "exec-script-results": exec_script_results[ 'cfg-result'] }) except Exception as e: tmp_result['results'].append({ "exec-script-results": exec_script_results }) except Exception as e: pass try: tmp_result['results'].append({ "file-copy-log": import_results['file-copy-log'] ['file-result'] }) except Exception as e: pass try: tmp_result['results'].append({ "imported-debug": import_results['imported-debug'] }) except Exception as e: pass # IMPORTED-FILES try: imported_files = import_results[ 'imported-files'] try: if isinstance(imported_files['file'], list): tmp_result['results'].append({ "imported-files": { "summary": { "total": len(imported_files[ 'file']), "status": get_status_summary( imported_files[ 'file']) }, "detail": imported_files['file'] } }) else: tmp_result['results'].append({ "imported-files": imported_files['file'] }) except Exception as e: tmp_result['results'].append( {"imported-files": imported_files}) except Exception as e: pass # IMPORTED-OBJECTS try: imported_objects = import_results[ 'imported-objects'] try: if isinstance( imported_objects['object'], list): tmp_result['results'].append({ "imported-objects": { "summary": { "total": len(imported_objects[ 'object']), "status": get_status_summary( imported_objects[ 'object']) }, "detail": imported_objects['object'] } }) else: tmp_result['results'].append({ "imported-objects": imported_objects['object'] }) except Exception as e: tmp_result['results'].append({ "imported-objects": imported_objects }) except Exception as e: pass tmp_result['msg'] = doim_data[ 'status'].capitalize() tmp_result['changed'] = True else: # Can't retrieve the import result module.fail_json( msg=IDGApi.ERROR_RETRIEVING_RESULT.format( state, domain_name)) elif imp_code == 200 and imp_msg == 'OK': # Successfully processed synchronized action tmp_result['msg'] = idg_mgmt.status_text( imp_data['Import']) tmp_result['changed'] = True else: # Imported not accepted module.fail_json( msg=IDGApi.ERROR_ACCEPTING_ACTION.format( state, domain_name)) else: # Domain NOT EXIST. # pdb.set_trace() # Opps can't work the configuration of non-existent domain module.fail_json( msg=(IDGApi.ERROR_REACH_STATE + " " + IDGApi.ERROR_NOT_DOMAIN).format(state, domain_name)) else: # Can't read domain's lists module.fail_json(msg=IDGApi.ERROR_GET_DOMAIN_LIST) # # Finish # # Update for k, v in tmp_result.items(): if v != None: result[k] = v except (NameError, UnboundLocalError) as e: # Very early error module_except = AnsibleModule(argument_spec={}) module_except.fail_json(msg=to_native(e)) except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)
def main(): # Validates the dependence of the utility module if HAS_IDG_DEPS: module_args = dict( method=dict(type='str', required=False, default='GET', choices=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']), # HTTP methods uri=dict(type='str', required=True), # URI of the request payload=dict(type='raw', required=False), # Payload idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True) # IDG connection ) # AnsibleModule instantiation module = AnsibleModule( argument_spec=module_args, supports_check_mode=True ) else: # Failure AnsibleModule instance module = AnsibleModule( argument_spec={}, check_invalid_arguments=False ) module.fail_json(msg="The IDG utils modules is required") # Parse arguments to dict idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) payload = json.dumps(module.params['payload']) if module.params['payload'] else None result.update({"http_code": None, "http_phrase": None, "payload": None}) # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format(idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) # # Here the action begins # # pdb.set_trace() try: # Do request idg_mgmt.api_call(module.params['uri'], method=module.params['method'], data=payload, id="rest_management_call") result['http_code'] = idg_mgmt.last_call()["code"] result['http_phrase'] = idg_mgmt.last_call()["msg"] result['payload'] = idg_mgmt.last_call()["data"] # # Finish # # Customize the result del result['name'] # Update result['msg'] = IDGUtils.COMPLETED_MESSAGE result['changed'] = True result['failed'] = True if result['http_code'] >= 400 else False except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)
def main(): # Validates the dependence of the utility module if HAS_IDG_DEPS: certificate_spec = { "country": dict(type='str'), "state": dict(type='str'), "locality": dict(type='str'), "organization": dict(type='str'), "organizational_unit": dict(type='str'), "organizational_unit1": dict(type='str'), "organizational_unit2": dict(type='str'), "organizational_unit3": dict(type='str'), "common_name": dict(type='str', required=True), "days": dict(type='int', default=365) } # Arguments/parameters that a user can pass to the module module_args = dict( idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True), # IDG connection certificate_data=dict(type='dict', options=certificate_spec, required=True), # Certificate data ldap_reverse_order=dict(type='bool', default=False), domain=dict(type='str', required=True), # Domain prefix_name=dict( type='str', required=False ), # prefix for the generated private key, CSR, and certificate password_alias=dict(type='str'), key_type=dict(type='str', choices=['RSA', 'ECDSA'], default='RSA'), key_length=dict(type='int', choices=[1024, 2048, 4096], default=2048), digest=dict(type='str', choices=['sha1', 'sha256'], default='sha256'), ecdsa_curve=dict( type='str', choices=[ "sect163k1", "sect163r1", "sect163r2", "sect193r1", "sect193r2", "sect233k1", "sect233r1", "sect239k1", "sect283k1", "sect283r1", "sect409k1", "sect409r1", "sect571k1", "sect571r1", "secp160k1", "secp160r1", "secp160r2", "secp192k1", "secp192r1", "secp224k1", "secp224r1", "secp256k1", "secp256r1", "secp384r1", "secp521r1", "brainpoolP256r1", "brainpoolP384r1", "brainpoolP512r1" ], default='secp256r1'), using_key=dict(type='str'), export_key=dict(type='bool', default=False), export_sscert=dict(type='bool', default=False), gen_sscert=dict(type='bool', default=True), gen_object=dict(type='bool', default=True), # Validate relation HSM/Object OJO hsm=dict(type='bool', default=False), ) # AnsibleModule instantiation module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) else: # Failure AnsibleModule instance module = AnsibleModule(argument_spec={}, check_invalid_arguments=False) module.fail_json(msg="The IDG utils modules is required") # Parse arguments to dict idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) certificate_data = IDGUtils.parse_to_dict( module, module.params['certificate_data'], 'CertificateData', IDGUtils.ANSIBLE_VERSION) domain_name = module.params['domain'] CRYPTO_FORMAT_EXT = "pem" # Cryptographic file extension CSR_EXT = "csr" CRYPTO_KEY_POSTFIX = "privkey" CRYPTO_SSC_POSTFIX = "sscert" TMP_DIR = "temporary:/" CERT_DIR = "cert:/" # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format( idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) # Create create_tpl = { "Keygen": { "LDAPOrder": IDGUtils.str_on_off(module.params['ldap_reverse_order']), "C": certificate_data['country'], "ST": certificate_data['state'], "L": certificate_data['locality'], "O": certificate_data['organization'], "OU": certificate_data['organizational_unit'], "OU1": certificate_data['organizational_unit1'], "OU2": certificate_data['organizational_unit2'], "OU3": certificate_data['organizational_unit3'], "CN": certificate_data['common_name'], "Days": certificate_data['days'], "KeyType": module.params['key_type'], "KeyLength": module.params['key_length'], "Digest": module.params['digest'], "ECDSACurve": module.params['ecdsa_curve'], "FileName": module.params['prefix_name'], "PasswordAlias": module.params['password_alias'], "ExportKey": IDGUtils.str_on_off(module.params['export_key']), "ExportSSCert": IDGUtils.str_on_off(module.params['export_sscert']), "GenSSCert": IDGUtils.str_on_off(module.params['gen_sscert']), "HSM": IDGUtils.str_on_off(module.params['hsm']), "UsingKey": module.params['using_key'] } } create_msg = copy.deepcopy(create_tpl) for k, v in create_tpl['Keygen'].items(): if v is None: del create_msg['Keygen'][k] URI_KEYGEN = IDGApi.URI_ACTION.format(domain_name) # Intermediate values for result tmp_result = { "domain": domain_name, "msg": None, "changed": None, "key-file": None, "sscert-file": None, "csr-file": None } # # Here the action begins # pdb.set_trace() try: idg_mgmt.api_call(URI_KEYGEN, method='POST', data=json.dumps(create_msg), id="keygen_call") if idg_mgmt.is_ok(idg_mgmt.last_call()): # If the answer is correct tmp_result['msg'] = idg_mgmt.last_call()["data"]['Keygen'] tmp_result['changed'] = True # Directories key_dir = TMP_DIR if module.params['export_key'] else CERT_DIR if "FileName" in create_msg["Keygen"].keys(): tmp_result['key-file'] = key_dir + create_msg["Keygen"][ "FileName"] + '-' + CRYPTO_KEY_POSTFIX + '.' + CRYPTO_FORMAT_EXT if module.params['gen_sscert']: ssc_dir = TMP_DIR if module.params[ 'export_sscert'] else CERT_DIR tmp_result['sscert-file'] = ssc_dir + create_msg["Keygen"][ "FileName"] + '-' + CRYPTO_SSC_POSTFIX + '.' + CRYPTO_FORMAT_EXT tmp_result['csr-file'] = TMP_DIR + create_msg["Keygen"][ "FileName"] + '.' + CSR_EXT else: tmp_result['key-file'] = key_dir + create_msg["Keygen"][ "CN"] + '-' + CRYPTO_KEY_POSTFIX + '.' + CRYPTO_FORMAT_EXT if module.params['gen_sscert']: ssc_dir = TMP_DIR if module.params[ 'export_sscert'] else CERT_DIR tmp_result['sscert-file'] = ssc_dir + create_msg["Keygen"][ "CN"] + '-' + CRYPTO_SSC_POSTFIX + '.' + CRYPTO_FORMAT_EXT tmp_result['csr-file'] = TMP_DIR + create_msg["Keygen"][ "CN"] + '.' + CSR_EXT else: # Wrong request module.fail_json( msg=IDGApi.GENERAL_STATELESS_ERROR.format( __MODULE_FULLNAME, domain_name) + str(ErrorHandler(idg_mgmt.last_call()["data"]['error']))) # # Finish # # Customize the result del result['name'] # Update for k, v in tmp_result.items(): if v is not None: result[k] = v except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)
def main(): # Validates the dependence of the utility module if HAS_IDG_DEPS: # Arguments/parameters that a user can pass to the module module_args = dict( entrys=dict(type='list'), # List of hosts alias idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True) # IDG connection ) # AnsibleModule instantiation module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) else: # Failure AnsibleModule instance module = AnsibleModule(argument_spec={}, check_invalid_arguments=False) module.fail_json(msg="The IDG utils modules is required") # Parameters if module.params['entrys'] == []: module.fail_json(msg='Need data in the "entrys" field') entrys = [translate(e) for e in module.params['entrys']] domain_name = "default" # System's level configurations are always do in default domain # Parse arguments to dict idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format( idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) # Intermediate values for result tmp_result = {"msg": None, "changed": False, "failed": None} # # Here the action begins # pdb.set_trace() try: # Get host alias configuration idg_mgmt.api_call(IDGApi.URI_CONFIG.format(domain_name) + "/HostAlias", method='GET', id="get_hosts_alias") if idg_mgmt.is_ok(idg_mgmt.last_call()): # If the answer is correct exist = [] for hc in idg_mgmt.call_by_id( "get_hosts_alias")["data"]["HostAlias"]: exist += [ h for h in entrys if (h["name"] == hc["name"] and h["IPAddress"] == hc["IPAddress"]) and (h not in exist) ] if exist == [] or (entrys.sort(key=lambda host: host["IPAddress"]) != exist.sort(key=lambda host: host["IPAddress"])): # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module) nh = [h for h in entrys if h not in exist] for h in nh: hosts_alias_msg = {"HostAlias": h} # Set host alias configuration idg_mgmt.api_call(IDGApi.URI_CONFIG.format(domain_name) + "/HostAlias", method='POST', data=json.dumps(hosts_alias_msg), id="set_hostsalias") if idg_mgmt.is_created( idg_mgmt.last_call()): # If the answer is correct tmp_result['changed'] = True tmp_result['msg'] = idg_mgmt.last_call()["data"][ h["name"]] else: module.fail_json( msg=IDGApi.GENERAL_STATELESS_ERROR.format( __MODULE_FULLNAME, domain_name) + str( ErrorHandler(idg_mgmt.last_call()["data"] ['error']))) else: tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE else: # Can't read the settings module.fail_json( msg="Could not be read the current host alias settings") # # Finish # # Customize del result['name'] # Update for k, v in tmp_result.items(): if v is not None: result[k] = v except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)
def main(): # Validates the dependence of the utility module if HAS_IDG_DEPS: # Arguments/parameters that a user can pass to the module module_args = dict( name=dict(type='str', required=True), # User name user_summary=dict(type='str', required=False), # Description state=dict(type='str', choices=[ "present", "absent", "password_resets", "force_password_change", "failed_login_resets" ], default='present'), admin_state=dict(type='str', choices=['enabled', 'disabled'], default='enabled'), # Administrative state password=dict(type='str'), # User password suppress_password_change=dict(type='bool', default=False), access_level=dict(type='str', choices=['privileged', 'group-defined']), group=dict(type='str'), # User group idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True) # IDG connection ) # AnsibleModule instantiation module = AnsibleModule( argument_spec=module_args, supports_check_mode=True, required_if=[["access_level", "group-defined", ["group"]], ["state", "present", ["password"]], ["state", "password_resets", ["password"]]]) else: # Failure AnsibleModule instance module = AnsibleModule(argument_spec={}, check_invalid_arguments=False) module.fail_json(msg="The IDG utils modules is required") # Parse arguments to dict idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) # Domain to work domain_name = "default" # Status state = module.params['state'] admin_state = module.params['admin_state'] user_name = module.params['name'] user_password = module.params['password'] # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format( idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) # Intermediate values for result tmp_result = { "name": user_name, "msg": None, "changed": False, "failed": None } # Configuration template for the object user_msg = { "User": { "name": user_name, "mAdminState": admin_state, "SuppressPasswordChange": module.params['suppress_password_change'], "Password": user_password, "AccessLevel": module.params['access_level'] } } # Optional parameters # Comments if module.params['user_summary'] is not None: user_msg["User"].update({"UserSummary": module.params['user_summary']}) # Group if module.params['access_level'] == "group-defined": user_msg["User"].update( {"GroupName": { "value": module.params['group'] }}) # # Here the action begins # pdb.set_trace() try: rest_operation = user_name # Get host alias configuration idg_mgmt.api_call(IDGApi.URI_CONFIG.format(domain_name) + "/User", method='GET', id="get_users") if idg_mgmt.is_ok(idg_mgmt.last_call()): # If the answer is correct exist_user, exist_user_name = False, False for u in idg_mgmt.last_call()["data"]["User"]: # Clean del u["_links"] if "GroupName" in u.keys(): del u["GroupName"]["href"] if not u["UserSummary"]: del u["UserSummary"] if user_msg["User"] == u: exist_user, exist_user_name = True, True break elif user_msg["User"]["name"] == u["name"]: exist_user_name = True break pdb.set_trace() if (state not in ["present", "absent" ]) and not (exist_user or exist_user_name): module.fail_json( msg=IDGApi.ERROR_REACH_STATE.format(state, domain_name) + " User don't exist") if state == "present": # Requires the creation or modification of the user if not exist_user: # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module) idg_mgmt.api_call(IDGApi.URI_CONFIG.format(domain_name) + "/User/" + user_name, method='PUT', data=json.dumps(user_msg), id="do_user") else: tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE elif state == "password_resets": rest_operation = "UserResetPassword" action_msg = { rest_operation: { "User": user_name, "Password": user_password } } idg_mgmt.api_call(IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(action_msg), id="reset_user_password") elif state == "force_password_change": rest_operation = "UserForcePasswordChange" action_msg = {rest_operation: {"User": user_name}} idg_mgmt.api_call(IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(action_msg), id="force_password_change") elif state == "failed_login_resets": rest_operation = "UserResetFailedLogin" action_msg = {rest_operation: {"User": user_name}} idg_mgmt.api_call(IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(action_msg), id="failed_login_resets") else: # state == "absent" if exist_user or exist_user_name: # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module) idg_mgmt.api_call(IDGApi.URI_CONFIG.format(domain_name) + "/User/" + user_name, method='DELETE', id="delete_user") else: tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE if idg_mgmt.last_call( )["id"] != "get_users": # Some modification to the configuration was required if idg_mgmt.is_created(idg_mgmt.last_call()) or idg_mgmt.is_ok( idg_mgmt.last_call()): tmp_result['msg'] = idg_mgmt.last_call( )["data"][rest_operation] tmp_result['changed'] = True else: module.fail_json( msg=IDGApi.ERROR_REACH_STATE.format( state, domain_name) + str(ErrorHandler(idg_mgmt.last_call()["data"] ['error']))) else: # Can't read the settings module.fail_json(msg="Could not be read the current user settings") # # Finish # # Update for k, v in tmp_result.items(): if v is not None: result[k] = v except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)
def main(): # Validates the dependence of the utility module if HAS_IDG_DEPS: # Arguments/parameters that a user can pass to the module module_args = dict( state=dict(type='str', choices=['present', 'absent'], default='present'), # Object state object_class=dict(type='str', choices=['key', 'public-key'], default='key'), # class type idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True), # IDG connection domain=dict(type='str', required=True), # Domain name=dict(type='str', required=True), # Object name admin_state=dict(type='str', choices=['enabled', 'disabled'], default='enabled'), # Administrative state file_name=dict(type='str'), # File with the public key ignore_expiration=dict(type='bool', default=False), password_alias=dict(type='str')) # AnsibleModule instantiation module = AnsibleModule( argument_spec=module_args, supports_check_mode=True, required_if=[["state", "present", ["file_name"]]]) else: # Failure AnsibleModule instance module = AnsibleModule(argument_spec={}, check_invalid_arguments=False) module.fail_json(msg="The IDG utils modules is required") # Parse arguments to dict idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) # Status & domain state = module.params['state'] domain_name = module.params['domain'] object_name = module.params['name'] file_name = module.params['file_name'] password_alias = module.params['password_alias'] admin_state = module.params['admin_state'] object_class = module.params['object_class'] ignore_expiration = IDGUtils.str_on_off(module.params['ignore_expiration']) # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format( idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) # Action messages: if object_class == 'public-key': # Create crypto certificate object REQ_OBJECT_ID = "CryptoCertificate" create_msg = { REQ_OBJECT_ID: { "name": object_name, "mAdminState": admin_state, "Filename": file_name, "IgnoreExpiration": ignore_expiration } } CRYPTOOBJ_URI_CFG = IDGApi.URI_CONFIG.format( domain_name) + "/" + REQ_OBJECT_ID else: # Create crypto key object REQ_OBJECT_ID = "CryptoKey" create_msg = { REQ_OBJECT_ID: { "name": object_name, "mAdminState": admin_state, "Filename": file_name } } CRYPTOOBJ_URI_CFG = IDGApi.URI_CONFIG.format( domain_name) + "/" + REQ_OBJECT_ID if password_alias is not None: create_msg[REQ_OBJECT_ID].update({"Alias": {"value": password_alias}}) # Intermediate values for result tmp_result = { "name": object_name, "domain": domain_name, "msg": None, "changed": None, "failed": None } # # Here the action begins # pdb.set_trace() try: # List of configured crypto objects idg_mgmt.api_call(CRYPTOOBJ_URI_CFG, method='GET', id="list_crypto_objets") if idg_mgmt.is_ok(idg_mgmt.last_call()): # If the answer is correct if REQ_OBJECT_ID in idg_mgmt.last_call()["data"].keys(): exist_obj = True if object_name in AbstractListDict( idg_mgmt.last_call()["data"][REQ_OBJECT_ID]).values( key="name") else False else: exist_obj = False if state == 'present': if not exist_obj: # Create it idg_mgmt.api_call(CRYPTOOBJ_URI_CFG, method='POST', data=json.dumps(create_msg), id="create_crypto_objet") if idg_mgmt.is_created(idg_mgmt.last_call()): tmp_result['msg'] = idg_mgmt.last_call( )["data"][object_name] tmp_result['changed'] = True else: # Can't create the object module.fail_json(msg=IDGApi.ERROR_REACH_STATE.format( state, domain_name) + str( ErrorHandler(idg_mgmt.last_call()["data"] ['error']))) else: # Update idg_mgmt.api_call(CRYPTOOBJ_URI_CFG + "/" + object_name, method='GET', id="get_crypto_object") if idg_mgmt.is_ok(idg_mgmt.last_call()): del idg_mgmt.last_call( )["data"][REQ_OBJECT_ID]['PasswordAlias'] if "Alias" in idg_mgmt.last_call( )["data"][REQ_OBJECT_ID].keys(): del idg_mgmt.last_call( )["data"][REQ_OBJECT_ID]['Alias']['href'] if idg_mgmt.last_call( )["data"][REQ_OBJECT_ID] != create_msg[REQ_OBJECT_ID]: idg_mgmt.api_call(CRYPTOOBJ_URI_CFG + "/" + object_name, method='PUT', data=json.dumps(create_msg), id="update_crypto_object") if idg_mgmt.is_ok(idg_mgmt.last_call()): tmp_result['msg'] = idg_mgmt.last_call( )["data"][object_name] tmp_result['changed'] = True else: # Can't read IDG status module.fail_json( msg=IDGApi.ERROR_REACH_STATE.format( state, domain_name) + str( ErrorHandler(idg_mgmt.last_call() ["data"]['error']))) else: tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE else: # Can't read IDG status module.fail_json(msg=IDGApi.GENERAL_ERROR.format( __MODULE_FULLNAME, state, domain_name) + str( ErrorHandler(idg_mgmt.last_call()["data"] ['error']))) else: #state == 'absent': if not exist_obj: # Create it tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE else: idg_mgmt.api_call(CRYPTOOBJ_URI_CFG + "/" + object_name, method='DELETE', id="delete_crypto_object") if idg_mgmt.is_ok(idg_mgmt.last_call()): tmp_result['msg'] = idg_mgmt.last_call( )["data"][object_name] tmp_result['changed'] = True else: # Can't remove for update object module.fail_json(msg=IDGApi.ERROR_REACH_STATE.format( state, domain_name) + str( ErrorHandler(idg_mgmt.last_call()["data"] ['error']))) else: # Can't read domain's lists module.fail_json(msg=IDGApi.ERROR_GET_DOMAIN_LIST) # # Finish # # Update for k, v in tmp_result.items(): if v is not None: result[k] = v except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)
def main(): # Validates the dependence of the utility module if HAS_IDG_DEPS: # Arguments/parameters that a user can pass to the module module_args = dict( state=dict(type='str', choices=['exported', 'imported', 'enabled', 'disabled']), idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True), # IDG connection domain=dict(type='str', required=True), # Domain to work objects=dict(type='list'), # Objects to export # for Export user_summary=dict(type='str'), # Backup comment persisted=dict(type='bool', default=False ), # Export from persisted or running configuration internal_files=dict( type='bool', default=True), # Export internal configuration file # for Import input_file=dict(type='str', required=False, no_log=True), # The base64-encoded BLOB to import overwrite_files=dict(type='bool', default=False), # Overwrite files that exist overwrite_objects=dict( type='bool', default=False), # Overwrite objects that exist dry_run=dict( type='bool', default=False ), # Import package (on) or validate the import operation without importing (off). ) # AnsibleModule instantiation module = AnsibleModule( argument_spec=module_args, supports_check_mode=True, # Interaction between parameters required_if=[['state', 'imported', ['input_file']], ['state', 'exported', ['objects']]]) else: # Failure AnsibleModule instance module = AnsibleModule(argument_spec={}, check_invalid_arguments=False) module.fail_json(msg="The IDG utils modules is required") # Parse arguments to dict idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format( idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) # Status & domain state = module.params['state'] domain_name = module.params['domain'] if module.params["objects"] is not None: # For export if isinstance( AbstractListStr(module.params["objects"]).optimal(), list): objects = [ translate(module, o) for o in AbstractListStr(module.params["objects"]).optimal() ] else: objects = translate( module, AbstractListStr(module.params["objects"]).optimal()) # Configuration template for the domain export_action_msg = { "Export": { "Format": "ZIP", "Persisted": IDGUtils.str_on_off(module.params['persisted']), "IncludeInternalFiles": IDGUtils.str_on_off(module.params['internal_files']), "Object": objects } } # Optional parameters # Comments if module.params['user_summary'] is not None: export_action_msg["Export"].update( {"UserSummary": module.params['user_summary']}) import_action_msg = { "Import": { "Format": "ZIP", "InputFile": module.params['input_file'], "OverwriteFiles": IDGUtils.str_on_off(module.params['overwrite_files']), "OverwriteObjects": IDGUtils.str_on_off(module.params['overwrite_objects']), "DryRun": IDGUtils.str_on_off(module.params['dry_run']) } } # Intermediate values for result tmp_result = { "domain": domain_name, "msg": None, "export_file": None, "changed": None, "failed": None } # # Here the action begins # pdb.set_trace() try: if state == "exported" or state == "enabled" or state == "disabled": # Validate objects if isinstance(objects, list): for o in objects: idg_mgmt.api_call(IDGApi.URI_CONFIG.format(domain_name) + "/{0}/{1}".format(o["class"], o["name"]), method='GET', id="get_status_" + o["name"]) if not idg_mgmt.is_ok(idg_mgmt.last_call()): break else: idg_mgmt.api_call( IDGApi.URI_CONFIG.format(domain_name) + "/{0}/{1}".format(objects["class"], objects["name"]), method='GET', id="get_status_" + objects["name"]) if not idg_mgmt.is_ok(idg_mgmt.last_call()): module.fail_json( msg=IDGApi.GENERAL_ERROR.format(__MODULE_FULLNAME, state, domain_name) + "URL: " + idg_mgmt.last_call()["url"] + str(ErrorHandler(idg_mgmt.last_call()["data"]['error']))) if state == "exported": # export and finish idg_mgmt.api_call(IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(export_action_msg), id="export_objects") if idg_mgmt.is_accepted(idg_mgmt.last_call()): # Asynchronous actions export accepted. Wait for complete idg_mgmt.api_event_sink( IDGApi.URI_ACTION.format(domain_name), href=idg_mgmt.last_call()["data"]['_links']['location'] ['href'], state=state) if idg_mgmt.is_ok(idg_mgmt.last_call()): # Export ok tmp_result['export_file'] = idg_mgmt.last_call( )["data"]['result']['file'] tmp_result['msg'] = idg_mgmt.last_call( )["data"]["status"].capitalize() tmp_result['changed'] = False else: # Can't retrieve the export module.fail_json( msg=IDGApi.ERROR_RETRIEVING_RESULT.format( state, domain_name)) else: # Export not accepted module.fail_json(msg=IDGApi.ERROR_ACCEPTING_ACTION.format( state, domain_name)) else: # state == "enabled" or state == "disabled" adminstate_msg = {"mAdminState": state} need_change = False if not isinstance(objects, list): objects = [objects] for o in objects: if idg_mgmt.call_by_id("get_status_" + o["name"])["data"][ o["class"]]["mAdminState"] != state: # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module) # change de admin state idg_mgmt.api_call( IDGApi.URI_CONFIG.format(domain_name) + "/{0}/{1}/{2}".format(o["class"], o["name"], "mAdminState"), method='PUT', data=json.dumps(adminstate_msg), id="set_status_" + o["name"]) if idg_mgmt.is_ok(idg_mgmt.last_call()): tmp_result['changed'] = True else: module.fail_json( msg=IDGApi.ERROR_REACH_STATE.format( state, domain_name) + str( ErrorHandler(idg_mgmt.last_call() ["data"]['error']))) if tmp_result['changed']: tmp_result['msg'] = idg_mgmt.last_call( )["data"]["mAdminState"] else: tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE elif state == "imported": # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module) # Import # pdb.set_trace() idg_mgmt.api_call(IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(import_action_msg), id="import_objects") if idg_mgmt.is_accepted(idg_mgmt.last_call()): # Asynchronous actions import accepted. Wait for complete idg_mgmt.api_event_sink(IDGApi.URI_ACTION.format(domain_name), href=idg_mgmt.last_call()["data"] ['_links']['location']['href'], state=state) if idg_mgmt.is_ok(idg_mgmt.last_call()): # Export completed import_results = idg_mgmt.last_call( )["data"]['result']['Import']['import-results'] if import_results['detected-errors'] != 'false': # Import failed tmp_result[ 'msg'] = 'Import failed with error code: "' + import_results[ 'detected-errors']['error'] + '"' tmp_result['changed'] = True tmp_result['failed'] = True else: # Import success tmp_result['msg'] = idg_mgmt.last_call( )["data"]['status'].capitalize() tmp_result['changed'] = True tmp_result.update({"results": []}) # Add result details tmp_result['results'].append({ "export-details": import_results['export-details'] }) # Export action detail # Elements of the export to incorporate in the final result relevant_results = { "imported-objects": "object", "imported-files": "file", "imported-debug": "debug" } for k, v in relevant_results.items( ): # Add all elements tmp_result['results'].append( IDGUtils.format_import_result(import_results, element=k, detail=v)) else: # Can't retrieve the import result module.fail_json(msg=IDGApi.ERROR_RETRIEVING_RESULT.format( state, domain_name)) else: # Imported not accepted module.fail_json(msg=IDGApi.ERROR_ACCEPTING_ACTION.format( state, domain_name)) # # Finish # # Customize del result['name'] # Update for k, v in tmp_result.items(): if v is not None: result[k] = v except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)
def translate(module, d): # Class keywords valid_class = [ "AAAPolicy", # AAA Policy "AccessControlList", # Access Control List "TAM", # Access Manager Client "ISAMReverseProxyJunction", # Access Manager Junction (deprecated) "ISAMReverseProxy", # Access Manager Reverse Proxy (deprecated) "ISAMRuntime", # Access Manager Runtime (deprecated) "AccessProfile", # Access Profile "AnalyticsEndpoint", # Analytics Endpoint "APIClientIdentification", # API Client Identification Action "APICollection", # API Collection "APIConnectGatewayService", # API Connect Gateway Service "APIContext", # API Context Action "APICORS", # API CORS Action "APIDefinition", # API Definition "APIExecute", # API Execute Action "APIGateway", # API Gateway "APILDAPRegistry", # API LDAP Registry "OperationRateLimit", # API Operation Rate Limit "APIOperation", # API Operation "APIPath", # API Path "APIPlan", # API Plan "APIRateLimit", # API Rate Limit Action "APIResult", # API Result Action "APIRouting", # API Routing Action "APIRule", # API Rule "APISecurity", # API Security Action "APISecurityAPIKey", # API Security API Key "APISecurityBasicAuth", # API Security Basic Authentication "APISecurityOAuthReq", # API Security OAuth Requirement "APISecurityOAuth", # API Security OAuth "APISecurityRequirement", # API Security Requirement "APISecurityTokenManager", # API Security Token Manager "Domain", # Application Domain "AppSecurityPolicy", # Application Security Policy "AS1PollerSourceProtocolHandler", # AS1 Poller Handler "AS2SourceProtocolHandler", # AS2 Handler "AS3SourceProtocolHandler", # AS3 Handler "AssemblyActionGatewayScript", # Assembly GatewayScript Action "AssemblyActionJWTGenerate", # Assembly Generate JWT Action "AssemblyActionInvoke", # Assembly Invoke Action "AssemblyActionJson2Xml", # Assembly JSON to XML Action "AssemblyActionMap", # Assembly Map Action "AssemblyActionOAuth", # Assembly OAuth Action "AssemblyActionParse", # Assembly Parse Action "AssemblyActionSetVar", # Assembly Set Variable Action "AssemblyLogicSwitch", # Assembly Switch Action "AssemblyActionThrow", # Assembly Throw Action "AssemblyActionUserSecurity", # Assembly User Security Action "AssemblyActionJWTValidate", # Assembly Validate JWT Action "AssemblyActionXml2Json", # Assembly XML to JSON Action "AssemblyActionXSLT", # Assembly XSLT Action "Assembly", # Assembly "AuditLog", # Audit Log Settings "B2BCPACollaboration", # B2B CPA Collaboration "B2BCPA", # B2B CPA "B2BGateway", # B2B Gateway "B2BProfileGroup", # B2B Partner Profile Group "B2BProfile", # B2B Partner Profile "B2BPersistence", # B2B Persistence "B2BXPathRoutingPolicy", # B2B XPath Routing Policy "SecureBackupMode", # Backup Mode "CloudConnectorService", # Cloud Connector Service "CloudGatewayService", # Cloud Gateway Service "SecureCloudConnector", # Cloud Instance (deprecated) "CompactFlash", # Compact Flash "CompileOptionsPolicy", # Compile Options Policy "ConfigSequence", # Configuration Sequence "ConformancePolicy", # Conformance Policy "CookieAttributePolicy", # Cookie Attribute Policy "B2BCPAReceiverSetting", # CPA Receiver Setting "B2BCPASenderSetting", # CPA Sender Setting "CRLFetch", # CRL Retrieval "CertMonitor", # Crypto Certificate Monitor "CryptoCertificate", # Crypto Certificate "CryptoFWCred", # Crypto Firewall Credentials "CryptoIdentCred", # Crypto Identification Credentials "CryptoKey", # Crypto Key "CryptoProfile", # Crypto Profile "CryptoSSKey", # Crypto Shared Secret Key "CryptoValCred", # Crypto Validation Credentials "MCFCustomRule", # Custom Rule Message Content Filter "DeploymentPolicyParametersBinding", # Deployment Policy Variables "ConfigDeploymentPolicy", # Deployment Policy "DFDLSettings", # DFDL Settings "DNSNameService", # DNS Settings "DocumentCryptoMap", # Document Crypto Map "DomainAvailability", # Domain Availability "DomainSettings", # Domain Settings "EBMS2SourceProtocolHandler", # ebMS2 Handler "EBMS3SourceProtocolHandler", # ebMS3 Handler "EthernetInterface", # Ethernet Interface "WXSGrid", # eXtreme Scale Grid "ErrorReportSettings", # Failure Notification "FTPFilePollerSourceProtocolHandler", # FTP Poller Handler "FTPQuoteCommands", # FTP Quoted Commands "FTPServerSourceProtocolHandler", # FTP Server Handler "GatewayPeering", # Gateway Peering "GWScriptSettings", # GatewayScript Settings "HostAlias", # Host Alias "FormsLoginPolicy", # HTML Forms Login Policy "HTTPSourceProtocolHandler", # HTTP Handler "MCFHttpHeader", # HTTP Header Message Content Filter "HTTPInputConversionMap", # HTTP Input Conversion Map "MCFHttpMethod", # HTTP Method Message Content Filter "HTTPService", # HTTP Service "MCFHttpURL", # HTTP URL Message Content Filter "HTTPSSourceProtocolHandler", # HTTPS Handler "MQSourceProtocolHandler", # IBM MQ Handler "MQQMGroup", # IBM MQ Queue Manager Group "MQQM", # IBM MQ Queue Manager "MQFTESourceProtocolHandler", # IBM MQFTE Handler "ILMTScanner", # ILMT Disconnected Scanner "ImportPackage", # Import Configuration File "IMSCalloutSourceProtocolHandler", # IMS Callout Handler "IMSConnectSourceProtocolHandler", # IMS Connect Handler "IMSConnect", # IMS Connect "IncludeConfig", # Include Configuration File "InteropService", # Interoperability Test Service "IPMulticast", # IP Multicast "IPMILanChannel", # IPMI LAN Channel "IPMIUser", # IPMI User "IScsiChapConfig", # iSCSI CHAP "IScsiHBAConfig", # iSCSI Host Bus Adapter "IScsiInitiatorConfig", # iSCSI Initiator "IScsiTargetConfig", # iSCSI Target "IScsiVolumeConfig", # iSCSI Volume "JSONSettings", # JSON Settings "JWEHeader", # JWE Header "JWERecipient", # JWE Recipient "JWSSignature", # JWS Signature "AAAJWTGenerator", # JWT Generator "AAAJWTValidator", # JWT Validator "CryptoKerberosKDC", # Kerberos KDC Server "CryptoKerberosKeytab", # Kerberos Keytab "Language", # Language "LDAPConnectionPool", # LDAP Connection Pool "LDAPSearchParameters", # LDAP Search Parameters "LinkAggregation", # Link Aggregation Interface "LoadBalancerGroup", # Load Balancer Group "LogLabel", # Log Category "LogTarget", # Log Target "LunaPartition", # Luna HSM Partition "Luna", # Luna HSM "Matching", # Matching Rule "AS2ProxySourceProtocolHandler", # MEIG AS2 Proxy Handler "MessageContentFilters", # Message Content Filters "CountMonitor", # Message Count Monitor "DurationMonitor", # Message Duration Monitor "FilterAction", # Message Filter Action "MessageMatching", # Message Matching "MessageType", # Message Type "MTOMPolicy", # MTOM Policy "MPGWErrorAction", # Multi-Protocol Gateway Error Action "MPGWErrorHandlingPolicy", # Multi-Protocol Gateway Error Policy "MultiProtocolGateway", # Multi-Protocol Gateway "NameValueProfile", # Name-Value Profile "NetworkSettings", # Network Settings "NFSClientSettings", # NFS Client Settings "NFSDynamicMounts", # NFS Dynamic Mounts "NFSFilePollerSourceProtocolHandler", # NFS Poller Handler "NFSStaticMount", # NFS Static Mounts "ZosNSSClient", # NSS Client "NTPService", # NTP Service "OAuthSupportedClientGroup", # OAuth Client Group "OAuthSupportedClient", # OAuth Client Profile "OAuthProviderSettings", # OAuth Provider Settings "ODRConnectorGroup", # ODR Connector Group "ODR", # On Demand Router "ParseSettings", # Parse Settings "PasswordAlias", # Password Map Alias "Pattern", # Pattern "PeerGroup", # Peer Group "PolicyAttachments", # Policy Attachment "PolicyParameters", # Policy Parameters "POPPollerSourceProtocolHandler", # POP Poller Handler "StylePolicyAction", # Processing Action "ProcessingMetadata", # Processing Metadata "StylePolicy", # Processing Policy "StylePolicyRule", # Processing Rule "ProductInsights", # Product Insights "QuotaEnforcementServer", # Quota Enforcement Server "RADIUSSettings", # RADIUS Settings "RaidVolume", # RAID Array "SimpleCountMonitor", # Rate Limiter "RBMSettings", # RBM Settings "JOSERecipientIdentifier", # Recipient Identifier "RestMgmtInterface", # REST Management Interface "SAMLAttributes", # SAML Attributes "SchemaExceptionMap", # Schema Exception Map "SecureGatewayClient", # Secure Gateway Client "WebAppSessionPolicy", # Session Management Policy "SFTPFilePollerSourceProtocolHandler", # SFTP Poller Handler "SSHServerSourceProtocolHandler", # SFTP Server Handler "ShellAlias", # Shell Alias (deprecated) "JOSESignatureIdentifier", # Signature Identifier "SLMAction", # SLM Action "SLMCredClass", # SLM Credential Class "SLMPolicy", # SLM Policy "SLMRsrcClass", # SLM Resource Class "SLMSchedule", # SLM Schedule "SMTPServerConnection", # SMTP Server Connection "SNMPSettings", # SNMP Settings "SOAPHeaderDisposition", # SOAP Header Disposition Table "SocialLoginPolicy", # Social Login Policy "SQLRuntimeSettings", # SQL Data Source Runtime Settings "SQLDataSource", # SQL Data Source "SSHClientProfile", # SSH Client Profile "SSHDomainClientProfile", # SSH Domain Client Profile "SSHServerProfile", # SSH Server Profile "SSHService", # SSH Service "SSLClientProfile", # SSL Client Profile "SSLSNIMapping", # SSL Host Name Mapping "SSLProxyProfile", # SSL Proxy Profile (deprecated) "SSLProxyService", # SSL Proxy Service "SSLServerProfile", # SSL Server Profile "SSLSNIServerProfile", # SSL SNI Server Profile "StandaloneStandbyControl", # Standalone Standby Control "StandaloneStandbyControlInterface", # StandaloneStandbyControlInterface "XTCProtocolHandler", # Stateful Raw XML Handler "StatelessTCPSourceProtocolHandler", # Stateless Raw XML Handler "Statistics", # Statistic Settings "ZHybridTargetControlService", # Sysplex Distributor Target Control Service "SystemSettings", # System Settings "TCPProxyService", # TCP Proxy Service "TelnetService", # Telnet Service "Tenant", # Tenant "Throttler", # Throttle Settings "TibcoEMSSourceProtocolHandler", # TIBCO EMS Handler "TibcoEMSServer", # TIBCO EMS "TimeSettings", # Time Settings "TFIMEndpoint", # Tivoli Federated Identity Manager "UDDIRegistry", # UDDI Registry (deprecated) "UDDISubscription", # UDDI Subscription (deprecated) "URLMap", # URL Map "URLRefreshPolicy", # URL Refresh Policy "URLRewritePolicy", # URL Rewrite Policy "User", # User Account "HTTPUserAgent", # User Agent "UserGroup", # User Group "VLANInterface", # VLAN Interface "WebAppErrorHandlingPolicy", # Web Application Firewall Error Policy "WebAppFW", # Web Application Firewall "WebB2BViewer", # Web B2B Viewer Management Service "WebGUI", # Web Management Service "WebAppRequest", # Web Request Profile "WebAppResponse", # Web Response Profile "WSGateway", # Web Service Proxy "WebServicesAgent", # Web Services Management Agent "WebServiceMonitor", # Web Services Monitor "WebTokenService", # Web Token Service "WCCService", # WebSphere Cell "WebSphereJMSSourceProtocolHandler", # WebSphere JMS Handler "WebSphereJMSServer", # WebSphere JMS "WSEndpointRewritePolicy", # WS-Proxy Endpoint Rewrite "WSStylePolicy", # WS-Proxy Processing Policy "WSStylePolicyRule", # WS-Proxy Processing Rule "WSRRSavedSearchSubscription", # WSRR Saved Search Subscription "WSRRServer", # WSRR Server "WSRRSubscription", # WSRR Subscription "XACMLPDP", # XACML Policy Decision Point "XC10Grid", # XC10 Grid (deprecated) "xmltrace", # XML File Capture "XMLFirewallService", # XML Firewall Service "MgmtInterface", # XML Management Interface "XMLManager", # XML Manager "MCFXPath", # XPath Message Content Filter "XPathRoutingMap", # XPath Routing Map "XSLCoprocService", # XSL Coprocessor Service "XSLProxyService" # XSL Proxy Service ] if d["class"] not in valid_class: module.fail_json( msg='The class({0}) defined for the object "{1}" is not valid'. format(d["class"], d["name"])) t = {"class": d["class"], "name": d["name"]} if "ref_objects" in d.keys(): t.update({"ref-objects": IDGUtils.str_on_off(d["ref_objects"])}) if "ref_files" in d.keys(): t.update({"ref-files": IDGUtils.str_on_off(d["ref_files"])}) if "include_debug" in d.keys(): t.update({"include-debug": IDGUtils.str_on_off(d["include_debug"])}) return t
def main(): try: # Define the available arguments/parameters that a user can pass to the module # File permission to the local: directory filemap_spec = { 'display': dict(type='bool'), # File content can be displayed for the local: directory. 'exec': dict(type='bool'), # Files in the local: directory can be run as scripts. 'copyfrom': dict(type='bool'), # Files can be copied FROM the local: directory. 'copyto': dict(type='bool'), # Files can be copied TO the local: directory. 'delete': dict(type='bool'), # Files can be DELETED from the local: directory. 'subdir': dict(type='bool') # Subdirectories can be created in the local: directory. } # Which types of events to generate when files are added to or deleted from the local: directory. monitoringmap_spec = { 'audit': dict(type='bool'), # Generate audit events. 'log': dict(type='bool') # Generate log events. } # Quiesce configuration quiescemap_spec = { 'delay': dict(type='int', default=0), # Specifies the interval of time in seconds to wait before initiating the quiesce action. 'timeout': dict(type='int', default=60) # Specifies the length of time in seconds to wait for all transactions to complete. } module_args = dict( name=dict(type='str', required=True), # Domain name user_summary=dict(type='str', required=False), # Domain description admin_state=dict(type='str', choices=['enabled', 'disabled'], default='enabled'), # Domain's administrative state state=dict(type='str', choices=['present', 'absent', 'restarted', 'quiesced', 'unquiesced'], default='present'), # Domain's operational state quiesce_conf=dict(type='dict', options=quiescemap_spec, default=dict({'delay': 0, 'timeout': 60})), # Transitions the operational state to down idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True), # IDG connection file_map=dict(type='dict', options=filemap_spec, default=dict({'display': True, 'exec': True, 'copyfrom': True, 'copyto': True, 'delete': True, 'subdir': True})), # File permission monitoring_map=dict(type='dict', options=monitoringmap_spec, default=dict({'audit': False, 'log': False})), # Events when work whith files max_chkpoints=dict(type='int', default=3), # The maximum number of configuration checkpoints to support. visible=dict(type='list', default=['default']), # Which application domains have visible to this domain # TODO !!! # It is better to guarantee immutability while waiting. config_mode=dict(type='str', default='local'), config_permissions_mode=dict(type='str', default='scope-domain'), import_format=dict(type='str', default='ZIP'), local_ip_rewrite=dict(type='bool', default=True) ) # AnsibleModule instantiation module = AnsibleModule( argument_spec=module_args, supports_check_mode=True, # Interaction between parameters required_if=[['state', 'quiesced', ['quiesce_conf']]] ) # Validates the dependence of the utility module if not HAS_IDG_DEPS: module.fail_json(msg="The IDG utils modules is required") # Parse arguments to dict idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) filemap_data_spec = IDGUtils.parse_to_dict(module, module.params['file_map'], 'FileMap', IDGUtils.ANSIBLE_VERSION) monitoringmap_data_spec = IDGUtils.parse_to_dict(module, module.params['monitoring_map'], 'MonitoringMap', IDGUtils.ANSIBLE_VERSION) quiesce_conf_data_spec = IDGUtils.parse_to_dict(module, module.params['quiesce_conf'], 'QuiesceConf', IDGUtils.ANSIBLE_VERSION) if len(module.params['visible']) == 1: visible_domain = {"value": module.params['visible'][0]} else: visible_domain = [] for d in module.params['visible']: visible_domain.append({"value": d}) # Domain to work domain_name = module.params['name'] # Status state = module.params['state'] admin_state = module.params['admin_state'] # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format(idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) # Variable to store the status of the action action_result = '' # Configuration template for the domain domain_obj_msg = {"Domain": { "name": domain_name, "mAdminState": admin_state, "UserSummary": module.params['user_summary'], "ConfigMode": module.params['config_mode'], "ConfigPermissionsMode": module.params['config_permissions_mode'], "ImportFormat": module.params['import_format'], "LocalIPRewrite": IDGUtils.str_on_off(module.params['local_ip_rewrite']), "MaxChkpoints": module.params['max_chkpoints'], "FileMap": { "Display": IDGUtils.str_on_off(filemap_data_spec['display']), "Exec": IDGUtils.str_on_off(filemap_data_spec['exec']), "CopyFrom": IDGUtils.str_on_off(filemap_data_spec['copyfrom']), "CopyTo": IDGUtils.str_on_off(filemap_data_spec['copyto']), "Delete": IDGUtils.str_on_off(filemap_data_spec['delete']), "Subdir": IDGUtils.str_on_off(filemap_data_spec['subdir']) }, "MonitoringMap": { "Audit": IDGUtils.str_on_off(monitoringmap_data_spec['audit']), "Log": IDGUtils.str_on_off(monitoringmap_data_spec['log']) }, "NeighborDomain": visible_domain }} # List of properties that are managed domain_obj_items = [k for k, v in domain_obj_msg['Domain'].items()] # Action messages # Restart restart_act_msg = {"RestartThisDomain": {}} # Quiesce quiesce_act_msg = {"DomainQuiesce": { "delay": quiesce_conf_data_spec['delay'], "name": domain_name, "timeout": quiesce_conf_data_spec['timeout'] }} # Unquiesce unquiesce_act_msg = {"DomainUnquiesce": {"name": domain_name}} # # Here the action begins # # pdb.set_trace() # Intermediate values for result tmp_result={"msg": None, "name": domain_name, "changed": None} # List of configured domains chk_code, chk_msg, chk_data = idg_mgmt.api_call(IDGApi.URI_DOMAIN_LIST, method='GET') if chk_code == 200 and chk_msg == 'OK': # If the answer is correct # List of existing domains if isinstance(chk_data['domain'], dict): # if has only default domain configured_domains = [chk_data['domain']['name']] else: configured_domains = [d['name'] for d in chk_data['domain']] if state in ('present', 'restarted', 'quiesced', 'unquiesced'): # They need for or do a domain if domain_name not in configured_domains: # Domain NOT EXIST. # pdb.set_trace() if state == 'present': # Create it # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module, result) create_code, create_msg, create_data = idg_mgmt.api_call(IDGApi.URI_DOMAIN_CONFIG.format(domain_name), method='PUT', data=json.dumps(domain_obj_msg)) if create_code == 201 and create_msg == 'Created': # Created successfully tmp_result['msg'] = idg_mgmt.status_text(create_data[domain_name]) tmp_result['changed'] = True elif create_code == 200 and create_msg == 'OK': # Updated successfully tmp_result['msg'] = idg_mgmt.status_text(create_data[domain_name]) tmp_result['changed'] = True else: # Opps can't create module.fail_json(msg=IDGApi.ERROR_REACH_STATE.format(state, domain_name)) elif state in ('restarted', 'quiesced', 'unquiesced'): # Can't do this actions module.fail_json(msg=(IDGApi.ERROR_REACH_STATE + " " + IDGApi.ERROR_NOT_DOMAIN).format(state, domain_name)) else: # Domain EXIST # Update, save or restart # pdb.set_trace() # Get current domain configuration dc_code, dc_msg, dc_data = idg_mgmt.api_call(IDGApi.URI_DOMAIN_CONFIG.format(domain_name), method='GET') if dc_code == 200 and dc_msg == 'OK': # We focus only on the properties we administer del dc_data['_links'] for k, v in dc_data['Domain'].items(): if k not in domain_obj_items: del dc_data['Domain'][k] elif k == 'NeighborDomain': if isinstance(dc_data['Domain'][k], dict): del dc_data['Domain'][k]['href'] elif isinstance(dc_data['Domain'][k], list): dc_data['Domain'][k] = [{'value': dv['value']} for dv in dc_data['Domain'][k]] if state == 'present' and (domain_obj_msg['Domain'] != dc_data['Domain']): # Need update # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module, result) upd_code, upd_msg, upd_json = idg_mgmt.api_call(IDGApi.URI_DOMAIN_CONFIG.format(domain_name), method='PUT', data=json.dumps(domain_obj_msg)) # pdb.set_trace() if upd_code == 200 and upd_msg == 'OK': # Updates successfully tmp_result['msg'] = idg_mgmt.status_text(upd_json[domain_name]) tmp_result['changed'] = True else: # Opps can't update module.fail_json(msg=IDGApi.GENERAL_ERROR.format(__MODULE_FULLNAME, state, domain_name) + str(ErrorHandler(upd_json['error']))) elif state == 'present' and (domain_obj_msg['Domain'] == dc_data['Domain']): # Identicals configurations # The current configuration is identical to the new configuration, there is nothing to do tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE elif state == 'restarted': # Restart domain # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module, result) restart_code, restart_msg, restart_data = idg_mgmt.api_call(IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(restart_act_msg)) if restart_code == 202 and restart_msg == 'Accepted': # Asynchronous actions restart accepted. Wait for complete action_result = idg_mgmt.wait_for_action_end(IDGApi.URI_ACTION.format(domain_name), href=restart_data['_links']['location']['href'], state=state) # Restart completed. Get result acs_code, acs_msg, acs_data = idg_mgmt.api_call(restart_data['_links']['location']['href'], method='GET') if acs_code == 200 and acs_msg == 'OK': # Restarted successfully tmp_result['msg'] = action_result tmp_result['changed'] = True else: # Can't retrieve the restart result module.fail_json(msg=IDGApi.ERROR_RETRIEVING_RESULT.format(state, domain_name)) elif restart_code == 200 and restart_msg == 'OK': # Successfully processed synchronized action tmp_result['msg'] = idg_mgmt.status_text(restart_data['RestartThisDomain']) tmp_result['changed'] = True else: # Can't restarted module.fail_json(msg=IDGApi.ERROR_ACCEPTING_ACTION.format(state, domain_name)) elif state in ('quiesced', 'unquiesced'): qds_code, qds_msg, qds_data = idg_mgmt.api_call(IDGApi.URI_DOMAIN_STATUS, method='GET') # pdb.set_trace() if qds_code == 200 and qds_msg == 'OK': if isinstance(qds_data['DomainStatus'], dict): domain_quiesce_status = qds_data['DomainStatus']['QuiesceState'] else: domain_quiesce_status = [d['QuiesceState'] for d in qds_data['DomainStatus'] if d['Domain'] == domain_name][0] if state == 'quiesced': if domain_quiesce_status == '': # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module, result) # Quiesce domain qd_code, qd_msg, qd_data = idg_mgmt.api_call(IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(quiesce_act_msg)) # pdb.set_trace() if qd_code == 202 and qd_msg == 'Accepted': # Asynchronous actions quiesce accepted. Wait for complete action_result = idg_mgmt.wait_for_action_end(IDGApi.URI_ACTION.format(domain_name), href=qd_data['_links']['location']['href'], state=state) # Quiesced completed. Get result acs_code, acs_msg, acs_data = idg_mgmt.api_call(qd_data['_links']['location']['href'], method='GET') if acs_code == 200 and acs_msg == 'OK': # Quiesced successfully tmp_result['msg'] = action_result tmp_result['changed'] = True else: # Can't get the quiesced action result module.fail_json(msg=IDGApi.ERROR_RETRIEVING_RESULT.format(state, domain_name)) elif qd_code == 200 and qd_msg == 'OK': # Successfully processed synchronized action tmp_result['msg'] = idg_mgmt.status_text(qd_data['DomainQuiesce']) tmp_result['changed'] = True else: # Can't quiesced module.fail_json(msg=IDGApi.ERROR_ACCEPTING_ACTION.format(state, domain_name)) else: # Domain is quiesced tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE elif state == 'unquiesced': if domain_quiesce_status == 'quiesced': # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module, result) # Unquiesce domain uqd_code, uqd_msg, uqd_data = idg_mgmt.api_call(IDGApi.URI_ACTION.format(domain_name), method='POST', data=json.dumps(unquiesce_act_msg)) # pdb.set_trace() if uqd_code == 202 and uqd_msg == 'Accepted': # Asynchronous actions unquiesce accepted. Wait for complete action_result = idg_mgmt.wait_for_action_end(IDGApi.URI_ACTION.format(domain_name), href=uqd_data['_links']['location']['href'], state=state) # Unquiesced completed. Get result acs_code, acs_msg, acs_data = idg_mgmt.api_call(uqd_data['_links']['location']['href'], method='GET') if acs_code == 200 and acs_msg == 'OK': # Unquiesce successfully tmp_result['msg'] = action_result tmp_result['changed'] = True else: # Can't get unquiesce final result module.fail_json(msg=IDGApi.ERROR_RETRIEVING_RESULT.format(state, domain_name)) elif uqd_code == 200 and uqd_msg == 'OK': # Successfully processed synchronized action tmp_result['msg'] = idg_mgmt.status_text(uqd_data['DomainUnquiesce']) tmp_result['changed'] = True else: # Can't accept unquiesce module.fail_json(msg=IDGApi.ERROR_ACCEPTING_ACTION.format(state, domain_name)) else: # Domain is unquiesced tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE else: # Can't get domain status module.fail_json(msg="Unable to get status from domain {0}.".format(domain_name)) else: # Can't read domain configuration module.fail_json(msg="Unable to get configuration from domain {0}.".format(domain_name)) elif state == 'absent': # Remove domain if domain_name in configured_domains: # Domain EXIST. # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module, result) # Remove del_code, del_msg, del_data = idg_mgmt.api_call(IDGApi.URI_DOMAIN_CONFIG.format(domain_name), method='DELETE') # pdb.set_trace() if del_code == 200 and del_msg == 'OK': # Remove successfully tmp_result['msg'] = idg_mgmt.status_text(del_data[domain_name]) tmp_result['changed'] = True else: # Can't remove module.fail_json(msg='Error deleting domain "{0}".'.format(domain_name)) else: # Domain NOT EXIST. tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE else: # Can't read domain's lists module.fail_json(msg=IDGApi.ERROR_GET_DOMAIN_LIST) # # Finish # # Update for k, v in tmp_result.items(): if v != None: result[k] = v except (NameError, UnboundLocalError) as e: # Very early error module_except = AnsibleModule(argument_spec={}) module_except.fail_json(msg=to_native(e)) except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)
def main(): # Validates the dependence of the utility module if HAS_IDG_DEPS: module_args = dict( filter=dict(type='str', required=False, default=None), # Domain to search ignore_case=dict(type='bool', required=False, default=True), # Case-insensitive matching idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True) # IDG connection ) # AnsibleModule instantiation module = AnsibleModule( argument_spec=module_args, supports_check_mode=True, # Interaction between parameters required_if=[['ignore_case', False, ['filter']]]) else: # Failure AnsibleModule instance module = AnsibleModule(argument_spec={}, check_invalid_arguments=False) module.fail_json(msg="The IDG utils modules is required") # Parse arguments to dict idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) # Domain to search domain_filter = module.params['filter'] filter_flags = re.IGNORECASE if module.params['ignore_case'] else 0 # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format( idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) # Intermediate values for result tmp_result = {"msg": IDGUtils.COMPLETED_MESSAGE, "domain_status": []} # # Here the action begins # pdb.set_trace() try: # List of configured domains and their status idg_mgmt.api_call(IDGApi.URI_DOMAIN_STATUS, method='GET', id="get_configured_domains") if idg_mgmt.is_ok(idg_mgmt.last_call()): # If the answer is correct # List of existing domains if isinstance(idg_mgmt.last_call()["data"]['DomainStatus'], dict): # if has only default domain configured_domains = [ idg_mgmt.last_call()["data"]['DomainStatus'] if (domain_filter is None) or (re.match( domain_filter, idg_mgmt.last_call()["data"]['DomainStatus']['Domain'], filter_flags)) else None ] else: if domain_filter is not None: configured_domains = [ d for d in idg_mgmt.last_call()["data"]['DomainStatus'] if re.match(domain_filter, d['Domain'], filter_flags) ] else: configured_domains = idg_mgmt.last_call( )["data"]['DomainStatus'] if configured_domains != [] and configured_domains != [None]: for d in configured_domains: if d is None: # don't process it continue for field in [ "DebugEnabled", "DiagEnabled", "ProbeEnabled", "SaveNeeded", "TraceEnabled" ]: d.update({field: IDGUtils.bool_on_off(d[field])}) # Get domain configuration idg_mgmt.api_call(IDGApi.URI_DOMAIN_CONFIG.format( d['Domain']), method='GET', id="get_domain_configuration") ds = {} # State of each domain if idg_mgmt.is_ok(idg_mgmt.last_call()): ds.update(d) # Add status data # Add configuration data ds.update({ "mAdminState": idg_mgmt.last_call()["data"]["Domain"] ["mAdminState"] }) if 'UserSummary' in idg_mgmt.last_call( )["data"]["Domain"]: ds.update({ "UserSummary": idg_mgmt.last_call()["data"]["Domain"] ["UserSummary"] }) else: ds.update({"UserSummary": ""}) tmp_result['domain_status'].append(ds) # Add domain else: # Can't read domain configuration module.fail_json( msg="Unable to get configuration from domain {0}.". format(d['Domain'])) else: # Domain not exist module.fail_json(msg=IDGApi.ERROR_NOT_DOMAIN) else: # Can't read domain's lists module.fail_json(msg=IDGApi.ERROR_GET_DOMAIN_LIST) # # Finish # # Customize del result['name'] # Update for k, v in tmp_result.items(): if v is not None: result[k] = v except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)
def main(): try: # Define the available arguments/parameters that a user can pass to the module # File permission to the local: directory module_args = dict(idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True) # IDG connection ) # AnsibleModule instantiation module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) # Validates the dependence of the utility module if not HAS_IDG_DEPS: module.fail_json(msg="The IDG utils modules is required") idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format( idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) # Variable to store the status of the action action_result = '' # Intermediate values for result tmp_result = {"msg": None} # List of configured domains chk_code, chk_msg, chk_data = idg_mgmt.api_call(IDGApi.URI_DOMAIN_LIST, method='GET') if chk_code == 200 and chk_msg == 'OK': # If the answer is correct if isinstance(chk_data['domain'], dict): # if has only default domain configured_domains = [chk_data['domain']['name']] else: configured_domains = [d['name'] for d in chk_data['domain']] tmp_result['msg'] = configured_domains for k, v in tmp_result.items(): if v != None: result[k] = v except (NameError, UnboundLocalError) as e: # Very early error module_except = AnsibleModule(argument_spec={}) module_except.fail_json(msg=to_native(e)) except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)
def main(): # Validates the dependence of the utility module if HAS_IDG_DEPS: module_args = dict( backup=dict(type='bool', required=False, default=False), # Create a backup file domain=dict(type='str', required=True), # Domain name src=dict(type='str', required=True), # Local path to a file or directory dest=dict(type='str', required=True), # Remote absolute path recursive=dict(type='bool', required=False, default=False), # Download recursively idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True) # IDG connection ) # AnsibleModule instantiation module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) else: # Failure AnsibleModule instance module = AnsibleModule(argument_spec={}, check_invalid_arguments=False) module.fail_json(msg="The IDG utils modules is required") # Parse arguments to dict idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) domain_name = module.params['domain'] backup = module.params['backup'] recursive = module.params['recursive'] tmp_dir = '' # Directory for processing on the control host src = module.params['src'] dest = module.params['dest'] _dest_parse = urlparse(dest) _dest_ldir = _dest_parse.scheme # Local directory if _dest_ldir + ':' not in IDGUtils.IDG_DIRS: module.fail_json( msg= "Base directory of the destination file {0} does not correspond to what is specified for datapower." .format(dest)) _dest_path_list = [ d for d in _dest_parse.path.split('/') if d.strip() != '' ] # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format( idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) # Intermediate values for result tmp_result = { "msg": IDGUtils.COMPLETED_MESSAGE, "domain": domain_name, "backup_file": None, "changed": True } # # Here the action begins # pdb.set_trace() try: remote_home_path = '/'.join( [IDGApi.URI_FILESTORE.format(domain_name), _dest_ldir] + _dest_path_list) idg_path = '/'.join([_dest_ldir + ':'] + _dest_path_list) if os.path.isdir(src): # The source is a directory # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module) if recursive: for home, subdirs, files in os.walk( src): # Loop over directory home_dir = home.strip('/').split( os.sep)[-1 * ((len(home.strip('/').split(os.sep)) - len(src.strip('/').split(os.sep))) + 1):] remote_home_path_uri = '/'.join( [remote_home_path] + home_dir) # Update root path idg_path_upd = '/'.join([idg_path] + home_dir) # Update path inside IDG create_directory(module, idg_mgmt, remote_home_path_uri, domain_name) for file_name in files: # files in home uri_file = '/'.join([remote_home_path_uri, file_name]) # Update URI for file remote_file = '/'.join([idg_path_upd, file_name ]) # Update path inside IDG if backup: # Backup required dummy = do_backup(module, idg_mgmt, uri_file, remote_file, domain_name) local_file_path = os.path.join(home, file_name) upload_file(module, idg_mgmt, local_file_path, uri_file, domain_name) else: # Not recursive for home, dummy, files in os.walk(src): # Loop over directory home_dir = home.split(os.sep)[-1] remote_home_path = '/'.join([remote_home_path, home_dir]) # Update root path idg_path = '/'.join([idg_path, home_dir]) # Update path inside IDG create_directory(module, idg_mgmt, remote_home_path, domain_name) for file_name in files: # files in home uri_file = '/'.join([remote_home_path, file_name]) # Update URI for file remote_file = '/'.join([idg_path, file_name]) # Path inside IDG if backup: # check backup dummy = do_backup(module, idg_mgmt, uri_file, remote_file, domain_name) local_file_path = os.path.join(home, file_name) upload_file(module, idg_mgmt, local_file_path, uri_file, domain_name) break # Prevent continue touring directories elif os.path.isfile(src): # The source is a local file file_name = src.split(os.sep)[-1] uri_file = '/'.join([remote_home_path, file_name]) # Update URI for file remote_file = '/'.join([idg_path, file_name]) # Path inside IDG idg_mgmt.api_call(remote_home_path, method='GET', id="get_remote_path") if idg_mgmt.is_ok(idg_mgmt.last_call()) or idg_mgmt.is_notfound( idg_mgmt.last_call()): # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module) if 'filestore' not in idg_mgmt.last_call()["data"].keys( ) or idg_mgmt.is_notfound(idg_mgmt.last_call() ): # Is not a directory or not found create_directory(module, idg_mgmt, remote_home_path, domain_name) if backup: # check backup tmp_result["backup_file"] = do_backup( module, idg_mgmt, uri_file, remote_file, domain_name) upload_file(module, idg_mgmt, src, uri_file, domain_name) # Upload file else: # Other Errors module.fail_json(msg=IDGApi.GENERAL_STATELESS_ERROR.format( __MODULE_FULLNAME, domain_name) + str( ErrorHandler( idg_mgmt.call_by_id("get_remote_path")["data"] ['error']))) else: module.fail_json(msg='Source "{0}" is not supported.'.format(src)) # # Finish # # Customize del result['name'] # Update for k, v in tmp_result.items(): if v is not None: result[k] = v except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)
def main(): # Validates the dependence of the utility module if HAS_IDG_DEPS: # Arguments/parameters that a user can pass to the module module_args = dict( name=dict(type='str', required=True), # User group name user_summary=dict(type='str', required=False), # Description state=dict(type='str', choices=['present', 'absent'], default='present'), admin_state=dict(type='str', choices=['enabled', 'disabled'], default='enabled'), # Administrative state access_profile=dict(type='list', default=["*/*/*?Access=r"]), # Access policies command_group=dict(type='list'), # CLI access command groups idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True) # IDG connection ) # AnsibleModule instantiation module = AnsibleModule( argument_spec=module_args, supports_check_mode=True ) else: # Failure AnsibleModule instance module = AnsibleModule( argument_spec={}, check_invalid_arguments=False ) module.fail_json(msg="The IDG utils modules is required") # Commands groups valid_commands_groups = [ "aaapolicy", # AAA Policy "acl", # Access Control List "assembly", # Assembly Actions "b2b", # B2B "common", # Common commands "compile-options", # Compile Options "config-management", # Configuration Management "configuration", # Configuration "crl", # CRL "quota-enforcement", # Quota Enforcement "crypto", # Cryptography "device-management", # Device Management "diagnostics", # Diagnostics "document-crypto-map", # Document Crypto Map "domain", # Domain "failure-notification", # Failure Notification "file-management", # File Management "firewallcred", # Firewall Credentials "flash", # Flash "httpserv", # HTTP Service "input-conversion", # Input Conversion Map "interface", # Interface "load-balancer", # Load Balancer "logging", # Logging "matching", # Matching "messages", # Messages "monitors", # Monitors "mpgw", # Multi-Protocol Gateway "mq-qm", # IBM MQ Queue Manager "network", # Network "radius", # RADIUS "rbm", # RBM "schema-exception-map", # Schema Exception Map "service-monitor", # Web Service Monitor "snmp", # SNMP Settings "sql", # SQL Data Source "sslforwarder", # SSL Proxy Service "stylesheetaction", # Processing Action "stylesheetpolicy", # Processing Policy "stylesheetrule", # Processing Rule "system", # System "tam", # IBM Security Access Manager and Tivoli Federated Identity Manager "tcpproxy", # TCP Proxy Service "urlmap", # URL Map "urlrefresh", # URL Refresh Policy "urlrewrite", # URL Rewrite Policy "useragent", # User Agent "usergroup", # User and User Group "validation", # Validation Credentials "webservice", # Web Service Proxy "wsm-agent", # Web Services Management Agent "xmlfirewall", # XML Firewall "xmlmgr", # XML Manager "xpath-routing", # XPath Routing Map "xslcoproc", # XSL Coprocessor "xslproxy", # XSL Proxy ] # Parse arguments to dict idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) # Domain to work domain_name = "default" # Status state = module.params['state'] admin_state = module.params['admin_state'] usergroup_name = module.params['name'] # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format(idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) # Intermediate values for result tmp_result = {"name": usergroup_name, "msg": None, "changed": False, "failed": None} # Configuration template for the object usergroup_msg = {"UserGroup": { "name": usergroup_name, "mAdminState": admin_state, "AccessPolicies": AbstractListStr(module.params["access_profile"]).optimal() }} # Optional parameters # Comments if module.params['user_summary'] is not None: usergroup_msg["UserGroup"].update({"UserSummary": module.params['user_summary']}) command_group = module.params['command_group'] # Commands Groups if command_group is not None: if not all(c in valid_commands_groups for c in command_group): module.fail_json(msg="The command groups must belong to one of the valid values") usergroup_msg["UserGroup"].update({"CommandGroup": AbstractListStr(command_group).optimal() }) # # Here the action begins # pdb.set_trace() try: # Get host alias configuration idg_mgmt.api_call(IDGApi.URI_CONFIG.format(domain_name) + "/UserGroup", method='GET', id="get_user_groups") if idg_mgmt.is_ok(idg_mgmt.last_call()): # If the answer is correct exist_user_group, exist_user_group_name = False, False if "UserGroup" in idg_mgmt.last_call()["data"].keys(): for ug in idg_mgmt.last_call()["data"]["UserGroup"]: del ug["_links"] # Clean if usergroup_msg["UserGroup"] == ug: exist_user_group, exist_user_group_name = True, True break elif usergroup_msg["UserGroup"]["name"] == ug["name"]: exist_user_group_name = True break if state == "present" and not exist_user_group: # Requires the creation or modification of the group # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module) idg_mgmt.api_call(IDGApi.URI_CONFIG.format(domain_name) + "/UserGroup/" + usergroup_name , method='PUT', data=json.dumps(usergroup_msg), id="do_user_group") elif state == "absent" and (exist_user_group or exist_user_group_name): # Requires remove the group # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module) idg_mgmt.api_call(IDGApi.URI_CONFIG.format(domain_name) + "/UserGroup/" + usergroup_name , method='DELETE', id="delete_user_group") else: # Nothing to do tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE if idg_mgmt.last_call()["id"] != "get_user_groups": # Some modification to the configuration was required if idg_mgmt.is_created(idg_mgmt.last_call()) or idg_mgmt.is_ok(idg_mgmt.last_call()): tmp_result['msg'] = idg_mgmt.last_call()["data"][usergroup_name] tmp_result['changed'] = True else: module.fail_json(msg=IDGApi.ERROR_REACH_STATE.format(state, domain_name) + str(ErrorHandler(idg_mgmt.last_call()["data"]['error']))) else: # Can't read the settings module.fail_json(msg="Could not be read the current user group settings") # # Finish # # Update for k, v in tmp_result.items(): if v is not None: result[k] = v except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)
def main(): # Validates the dependence of the utility module if HAS_IDG_DEPS: # Arguments/parameters that a user can pass to the module module_args = dict( user_summary=dict(type='str', required=False), # Object description admin_state=dict(type='str', choices=['enabled', 'disabled'], default='enabled'), # Administrative state remote_server=dict(type='list', default=[]), # List of remote NTP servers refresh_interval=dict(type='int', default=900), state=dict(type='str', choices=['present', 'absent'], default='present'), # Service's operational state idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True) # IDG connection ) # AnsibleModule instantiation module = AnsibleModule( argument_spec=module_args, supports_check_mode=True, # Interaction between parameters required_if=[['admin_state', 'enabled', ['remote_server']]]) else: # Failure AnsibleModule instance module = AnsibleModule(argument_spec={}, check_invalid_arguments=False) module.fail_json(msg="The IDG utils modules is required") # Parameters state = module.params['state'] admin_state = module.params['admin_state'] remote_server = module.params['remote_server'] refresh_interval = module.params['refresh_interval'] domain_name = "default" # System's level configurations are always do in default domain # Parse arguments to dict idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format( idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) # Quiesce ntpservice_msg = { "NTPService": { "name": "NTP Service", "RefreshInterval": refresh_interval, "mAdminState": admin_state, "RemoteServer": remote_server } } ntpservice_disable_msg = {"mAdminState": "disabled"} if module.params['user_summary'] is not None: ntpservice_msg["NTPService"].update( {"UserSummary": module.params['user_summary']}) # Intermediate values for result tmp_result = {"msg": None, "changed": False, "failed": None} # # Here the action begins # pdb.set_trace() try: # Get NTP Service status idg_mgmt.api_call(IDGApi.URI_CONFIG.format(domain_name) + "/NTPService", method='GET', id="get_ntpservice_status") if idg_mgmt.is_ok(idg_mgmt.last_call()): # If the answer is correct if state == 'present': # Clean del idg_mgmt.last_call()["data"]["NTPService"]["_links"] if idg_mgmt.last_call( )["data"]["NTPService"] != ntpservice_msg[ "NTPService"]: # Need update or create idg_mgmt.api_call(IDGApi.URI_CONFIG.format(domain_name) + "/NTPService/NTP+Service", method="PUT", data=json.dumps(ntpservice_msg), id="set_ntpservice_configuration") if idg_mgmt.is_ok(idg_mgmt.last_call()): tmp_result['msg'] = idg_mgmt.status_text( idg_mgmt.last_call()["data"]["NTP_Service"]) tmp_result['changed'] = True else: # Opps can't update module.fail_json(msg=IDGApi.GENERAL_ERROR.format( __MODULE_FULLNAME, state, domain_name) + str( ErrorHandler(idg_mgmt.last_call()["data"] ['error']))) else: # Ident configuration tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE else: # state = absent if idg_mgmt.last_call()["data"]["NTPService"][ "mAdminState"] == "enabled": # Need change idg_mgmt.api_call(IDGApi.URI_CONFIG.format(domain_name) + "/NTPService/NTP+Service/mAdminState", method="PUT", data=json.dumps(ntpservice_disable_msg), id="disable_ntpservice") if idg_mgmt.is_ok(idg_mgmt.last_call()): tmp_result['msg'] = idg_mgmt.status_text( idg_mgmt.last_call()["data"]["mAdminState"]) tmp_result['changed'] = True else: # Opps can't update module.fail_json(msg=IDGApi.GENERAL_ERROR.format( __MODULE_FULLNAME, state, domain_name) + str( ErrorHandler(idg_mgmt.last_call()["data"] ['error']))) else: # Ident configuration tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE else: # Can't read the settings module.fail_json( msg="Could not be read the current NTP service settings") # # Finish # # Customize del result['name'] # Update for k, v in tmp_result.items(): if v is not None: result[k] = v except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)
def main(): # Validates the dependence of the utility module if HAS_IDG_DEPS: # Arguments/parameters that a user can pass to the module module_args = dict( state=dict(type='str', choices=['present', 'absent'], default='present'), # Password map alias state idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True), # IDG connection domain=dict(type='str', required=True), # Domain name=dict(type='str', required=True), # Password map alias password=dict(type='str', no_log=True), # Plaintext password to alias admin_state=dict(type='str', choices=['enabled', 'disabled'], default='enabled'), # Administrative state summary=dict(type='str', required=False) # Description ) # AnsibleModule instantiation module = AnsibleModule(argument_spec=module_args, supports_check_mode=True, required_if=[["state", "present", ["password"]]]) else: # Failure AnsibleModule instance module = AnsibleModule(argument_spec={}, check_invalid_arguments=False) module.fail_json(msg="The IDG utils modules is required") # Parse arguments to dict idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) state = module.params['state'] domain_name = module.params['domain'] # Password Alias Map (pam) pam_name = module.params['name'] pam_admin_state = module.params['admin_state'] pam_summary = module.params['summary'] pam_passw = module.params['password'] # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format( idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) # Create or update create_msg = { "PasswordAlias": { "name": pam_name, "mAdminState": pam_admin_state, "Password": pam_passw, "UserSummary": pam_summary } } URI_PAM_CONFIG = IDGApi.URI_CONFIG.format(domain_name) + "/PasswordAlias" # Variable to store the status of the action action_result = '' # Intermediate values for result tmp_result = { "name": pam_name, "domain": domain_name, "msg": None, "changed": None } # # Here the action begins # pdb.set_trace() try: # List of configured password alias in domain idg_mgmt.api_call(URI_PAM_CONFIG, method='GET', id="get_configured_password_alias") if idg_mgmt.is_ok(idg_mgmt.last_call()): # If the answer is correct if 'PasswordAlias' in idg_mgmt.last_call()["data"].keys(): pams = AbstractListDict( idg_mgmt.last_call()["data"]['PasswordAlias']) else: pams = AbstractListDict({}) if state == 'present': # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module) if pams.empty() or (pam_name not in pams.values(key='name')): # Create idg_mgmt.api_call(URI_PAM_CONFIG, method='POST', data=json.dumps(create_msg), id="create_password_alias") if idg_mgmt.is_created(idg_mgmt.last_call()): # Create successfully tmp_result['msg'] = idg_mgmt.last_call( )["data"][pam_name] tmp_result['changed'] = True else: module.fail_json(msg=IDGApi.ERROR_REACH_STATE.format( state, domain_name) + str( ErrorHandler(idg_mgmt.last_call()["data"] ['error']))) else: # Update idg_mgmt.api_call(URI_PAM_CONFIG + '/' + pam_name, method='PUT', data=json.dumps(create_msg), id="update_password_alias") if idg_mgmt.is_ok(idg_mgmt.last_call()): # Update successfully tmp_result['msg'] = idg_mgmt.last_call( )["data"][pam_name] tmp_result['changed'] = True else: module.fail_json(msg=IDGApi.ERROR_REACH_STATE.format( state, domain_name) + str( ErrorHandler(idg_mgmt.last_call()["data"] ['error']))) elif state == 'absent': # If the user is working in only check mode we do not want to make any changes IDGUtils.implement_check_mode(module) if pam_name in pams.values(key='name'): idg_mgmt.api_call(URI_PAM_CONFIG + '/' + pam_name, method='DELETE', id="delete_password_alias") if idg_mgmt.is_ok(idg_mgmt.last_call()): # Update successfully tmp_result['msg'] = idg_mgmt.last_call( )["data"][pam_name] tmp_result['changed'] = True else: module.fail_json(msg=IDGApi.ERROR_REACH_STATE.format( state, domain_name) + str( ErrorHandler(idg_mgmt.last_call()["data"] ['error']))) else: tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE else: # Can't read password alias status module.fail_json(msg=IDGApi.GENERAL_ERROR.format( __MODULE_FULLNAME, state, domain_name) + str( ErrorHandler( idg_mgmt.call_by_id("get_configured_password_alias") ["data"]['error']))) # # Finish # # Update for k, v in tmp_result.items(): if v is not None: result[k] = v except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)
def main(): # Validates the dependence of the utility module if HAS_IDG_DEPS: module_args = dict( parameters=dict(type='list', required=False, default=['All']), # Parameters to recover idg_connection=dict(type='dict', options=idg_endpoint_spec, required=True) # IDG connection ) # AnsibleModule instantiation module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) else: # Failure AnsibleModule instance module = AnsibleModule(argument_spec={}, check_invalid_arguments=False) module.fail_json(msg="The IDG utils modules is required") # pdb.set_trace() # Parse arguments to dict idg_data_spec = IDGUtils.parse_to_dict(module, module.params['idg_connection'], 'IDGConnection', IDGUtils.ANSIBLE_VERSION) parameters = set() if isinstance(module.params['parameters'], list): parameters = {x.lower() for x in module.params['parameters'] } if module.params['parameters'] != [] else {'all'} if 'all' in parameters and len(parameters) > 1: parameters = {'all'} module.warn( 'If specify "All" the rest of the parameters are ignored') else: module.fail_json( msg='If "parameters" is specified, a list is required') result.update({"status": []}) # Init IDG API connect idg_mgmt = IDGApi(ansible_module=module, idg_host="https://{0}:{1}".format( idg_data_spec['server'], idg_data_spec['server_port']), headers=IDGUtils.BASIC_HEADERS, http_agent=IDGUtils.HTTP_AGENT_SPEC, use_proxy=idg_data_spec['use_proxy'], timeout=idg_data_spec['timeout'], validate_certs=idg_data_spec['validate_certs'], user=idg_data_spec['user'], password=idg_data_spec['password'], force_basic_auth=IDGUtils.BASIC_AUTH_SPEC) _DOMAIN = "default" _STATUS_DEFAULT = "/mgmt/status/" + _DOMAIN + "/" status_db = [{ "param": "Battery", "href": _STATUS_DEFAULT + "Battery" }, { "param": "Crypto", "href": _STATUS_DEFAULT + "CryptoEngineStatus2" }, { "param": "Crypto", "href": _STATUS_DEFAULT + "CryptoHwDisableStatus" }, { "param": "Crypto", "href": _STATUS_DEFAULT + "CryptoModeStatus" }, { "param": "Crypto", "href": _STATUS_DEFAULT + "LunaLatency" }, { "param": "Sensors", "href": _STATUS_DEFAULT + "CurrentSensors" }, { "param": "Sensors", "href": _STATUS_DEFAULT + "PowerSensors" }, { "param": "DateTime", "href": _STATUS_DEFAULT + "DateTimeStatus" }, { "param": "DateTime", "href": _STATUS_DEFAULT + "DateTimeStatus2" }, { "param": "Temperature", "href": _STATUS_DEFAULT + "EnvironmentalFanSensors" }, { "param": "Temperature", "href": _STATUS_DEFAULT + "TemperatureSensors" }, { "param": "Network", "href": _STATUS_DEFAULT + "EthernetInterfaceStatus" }, { "param": "Network", "href": _STATUS_DEFAULT + "IPAddressStatus" }, { "param": "Network", "href": _STATUS_DEFAULT + "IPMulticastStatus" }, { "param": "Network", "href": _STATUS_DEFAULT + "LinkAggregationMemberStatus" }, { "param": "Network", "href": _STATUS_DEFAULT + "LinkAggregationStatus" }, { "param": "Network", "href": _STATUS_DEFAULT + "LinkStatus" }, { "param": "Network", "href": _STATUS_DEFAULT + "NetworkInterfaceStatus" }, { "param": "Network", "href": _STATUS_DEFAULT + "VlanInterfaceStatus2" }, { "param": "Failure", "href": _STATUS_DEFAULT + "FailureNotificationStatus2" }, { "param": "Firmware", "href": _STATUS_DEFAULT + "FirmwareStatus" }, { "param": "Firmware", "href": _STATUS_DEFAULT + "FirmwareVersion2" }, { "param": "Platform", "href": _STATUS_DEFAULT + "Hypervisor3" }, { "param": "Platform", "href": _STATUS_DEFAULT + "VirtualPlatform3" }, { "param": "Library", "href": _STATUS_DEFAULT + "LibraryVersion" }, { "param": "License", "href": _STATUS_DEFAULT + "LicenseStatus" }, { "param": "NTP", "href": _STATUS_DEFAULT + "NTPRefreshStatus" }, { "param": "Raid", "href": _STATUS_DEFAULT + "RaidArrayStatus" }, { "param": "Raid", "href": _STATUS_DEFAULT + "RaidBatteryBackUpStatus" }, { "param": "Raid", "href": _STATUS_DEFAULT + "RaidBatteryModuleStatus" }, { "param": "Raid", "href": _STATUS_DEFAULT + "RaidLogicalDriveStatus" }, { "param": "Raid", "href": _STATUS_DEFAULT + "RaidPartitionStatus" }, { "param": "Raid", "href": _STATUS_DEFAULT + "RaidPhysicalDriveStatus" }, { "param": "SNMP", "href": _STATUS_DEFAULT + "SNMPStatus" }, { "param": "Cloud", "href": _STATUS_DEFAULT + "SecureCloudConnectorConnectionsStatus" }, { "param": "Balanced", "href": _STATUS_DEFAULT + "SelfBalancedStatus2" }, { "param": "Balanced", "href": _STATUS_DEFAULT + "SelfBalancedTable" }, { "param": "Services", "href": _STATUS_DEFAULT + "ServicesMemoryStatus2" }, { "param": "Services", "href": _STATUS_DEFAULT + "ServicesStatus" }, { "param": "Standby", "href": _STATUS_DEFAULT + "StandbyStatus2" }, { "param": "System", "href": _STATUS_DEFAULT + "SystemUsage" }, { "param": "System", "href": _STATUS_DEFAULT + "SystemUsage2Table" }, { "param": "System", "href": _STATUS_DEFAULT + "FilesystemStatus" }, { "param": "System", "href": _STATUS_DEFAULT + "MemoryStatus" }, { "param": "System", "href": _STATUS_DEFAULT + "CPUUsage" }] # # Here the action begins # pdb.set_trace() try: # Do request status_results = [] pset = set() for s in status_db: pl = [] if (s['param'].lower() in parameters or parameters == {'all'}) and (s['param'] not in pset): pset.add(s['param']) for s1 in status_db: if s1['param'] == s['param']: resource = s1['href'].rsplit('/', 1)[-1] idg_mgmt.api_call(s1['href'], method='GET', id="get_appliance_status") if idg_mgmt.is_ok(idg_mgmt.last_call()): del (idg_mgmt.last_call()["data"]['_links']) if 'result' in idg_mgmt.last_call()["data"].keys( ) and idg_mgmt.last_call( )["data"]['result'] == "No status retrieved.": idg_mgmt.last_call()["data"].update({ resource: idg_mgmt.last_call()["data"]['result'] }) del (idg_mgmt.last_call()["data"]['result']) pl.append(idg_mgmt.last_call()["data"]) else: # Can't retrieve the status module.fail_json( msg=IDGApi.ERROR_RETRIEVING_RESULT.format( resource, _DOMAIN)) if pl: status_results.append({s['param']: pl}) # # Finish # # Customize the result del result['name'] # Update result['msg'] = IDGUtils.COMPLETED_MESSAGE result['changed'] = False result['status'] = status_results except Exception as e: # Uncontrolled exception module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION + '. {0}').format(to_native(e))) else: # That's all folks! module.exit_json(**result)