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: # 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( 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=['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(): 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( 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: 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 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( 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( 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 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)