Example #1
0
def do_backup(module, idg_mgmt, uri_file, remote_file, domain_name):
    idg_mgmt.api_call(uri_file, method='GET', id="make_backup")
    if idg_mgmt.is_ok(idg_mgmt.last_call()):  # File exists

        now = datetime.datetime.now()
        bak_file = remote_file + "-" + now.strftime("%Y%m%dT%H%M%S")
        move_file_msg = {
            "MoveFile": {
                "sURL": remote_file,
                "dURL": bak_file,
                "Overwrite": "on"
            }
        }

        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()):
            return bak_file
        else:
            module.fail_json(
                msg=IDGApi.GENERAL_ERROR.format(
                    __MODULE_FULLNAME, "Creating backup", domain_name) +
                str(ErrorHandler(idg_mgmt.last_call()["data"]['error'])))
Example #2
0
def create_directory(module, idg_mgmt, home_path, domain_name):
    create_dir_msg = {"directory": {"name": home_path.split('/')[-1]}}
    idg_mgmt.api_call(home_path,
                      method='PUT',
                      data=json.dumps(create_dir_msg),
                      id="create_directory")

    if not idg_mgmt.is_created(
            idg_mgmt.last_call()) and not idg_mgmt.is_conflict(
                idg_mgmt.last_call()):
        module.fail_json(
            msg=IDGApi.GENERAL_ERROR.format(__MODULE_FULLNAME,
                                            "Upload directory", domain_name) +
            str(ErrorHandler(idg_mgmt.last_call()["data"]['error'])))
    else:
        return True
Example #3
0
def upload_file(module, idg_mgmt, local_file_path, uri_file, domain_name):

    with open(local_file_path, "rb") as f:
        encoded_file = base64.b64encode(f.read())

    create_file_msg = {
        "file": {
            "name": uri_file.split('/')[-1],
            "content": encoded_file.decode("utf-8")
        }
    }
    idg_mgmt.api_call(uri_file,
                      method='PUT',
                      data=json.dumps(create_file_msg),
                      id="upload_file")

    if not idg_mgmt.is_created(idg_mgmt.last_call()) and not idg_mgmt.is_ok(
            idg_mgmt.last_call()):
        module.fail_json(
            msg=IDGApi.GENERAL_ERROR.format(__MODULE_FULLNAME, "Upload file",
                                            domain_name) +
            str(ErrorHandler(idg_mgmt.last_call()["data"]['error'])))
    else:
        return True
Example #4
0
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)
Example #5
0
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)
Example #6
0
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)
Example #7
0
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)
Example #8
0
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)
Example #9
0
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)
Example #10
0
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)
Example #11
0
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)
Example #12
0
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)
Example #13
0
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)
Example #14
0
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)