Exemple #1
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)
Exemple #2
0
def main():
    # Validates the dependence of the utility module
    if HAS_IDG_DEPS:

        certificate_spec = {
            "country": dict(type='str'),
            "state": dict(type='str'),
            "locality": dict(type='str'),
            "organization": dict(type='str'),
            "organizational_unit": dict(type='str'),
            "organizational_unit1": dict(type='str'),
            "organizational_unit2": dict(type='str'),
            "organizational_unit3": dict(type='str'),
            "common_name": dict(type='str', required=True),
            "days": dict(type='int', default=365)
        }

        # Arguments/parameters that a user can pass to the module
        module_args = dict(
            idg_connection=dict(type='dict',
                                options=idg_endpoint_spec,
                                required=True),  # IDG connection
            certificate_data=dict(type='dict',
                                  options=certificate_spec,
                                  required=True),  # Certificate data
            ldap_reverse_order=dict(type='bool', default=False),
            domain=dict(type='str', required=True),  # Domain
            prefix_name=dict(
                type='str', required=False
            ),  # prefix for the generated private key, CSR, and certificate
            password_alias=dict(type='str'),
            key_type=dict(type='str', choices=['RSA', 'ECDSA'], default='RSA'),
            key_length=dict(type='int',
                            choices=[1024, 2048, 4096],
                            default=2048),
            digest=dict(type='str',
                        choices=['sha1', 'sha256'],
                        default='sha256'),
            ecdsa_curve=dict(
                type='str',
                choices=[
                    "sect163k1", "sect163r1", "sect163r2", "sect193r1",
                    "sect193r2", "sect233k1", "sect233r1", "sect239k1",
                    "sect283k1", "sect283r1", "sect409k1", "sect409r1",
                    "sect571k1", "sect571r1", "secp160k1", "secp160r1",
                    "secp160r2", "secp192k1", "secp192r1", "secp224k1",
                    "secp224r1", "secp256k1", "secp256r1", "secp384r1",
                    "secp521r1", "brainpoolP256r1", "brainpoolP384r1",
                    "brainpoolP512r1"
                ],
                default='secp256r1'),
            using_key=dict(type='str'),
            export_key=dict(type='bool', default=False),
            export_sscert=dict(type='bool', default=False),
            gen_sscert=dict(type='bool', default=True),
            gen_object=dict(type='bool', default=True),
            # Validate relation HSM/Object OJO
            hsm=dict(type='bool', default=False),
        )

        # AnsibleModule instantiation
        module = AnsibleModule(argument_spec=module_args,
                               supports_check_mode=True)

    else:
        # Failure AnsibleModule instance
        module = AnsibleModule(argument_spec={}, check_invalid_arguments=False)
        module.fail_json(msg="The IDG utils modules is required")

    # Parse arguments to dict
    idg_data_spec = IDGUtils.parse_to_dict(module,
                                           module.params['idg_connection'],
                                           'IDGConnection',
                                           IDGUtils.ANSIBLE_VERSION)
    certificate_data = IDGUtils.parse_to_dict(
        module, module.params['certificate_data'], 'CertificateData',
        IDGUtils.ANSIBLE_VERSION)

    domain_name = module.params['domain']

    CRYPTO_FORMAT_EXT = "pem"  # Cryptographic file extension
    CSR_EXT = "csr"
    CRYPTO_KEY_POSTFIX = "privkey"
    CRYPTO_SSC_POSTFIX = "sscert"

    TMP_DIR = "temporary:/"
    CERT_DIR = "cert:/"

    # Init IDG API connect
    idg_mgmt = IDGApi(ansible_module=module,
                      idg_host="https://{0}:{1}".format(
                          idg_data_spec['server'],
                          idg_data_spec['server_port']),
                      headers=IDGUtils.BASIC_HEADERS,
                      http_agent=IDGUtils.HTTP_AGENT_SPEC,
                      use_proxy=idg_data_spec['use_proxy'],
                      timeout=idg_data_spec['timeout'],
                      validate_certs=idg_data_spec['validate_certs'],
                      user=idg_data_spec['user'],
                      password=idg_data_spec['password'],
                      force_basic_auth=IDGUtils.BASIC_AUTH_SPEC)

    # Create
    create_tpl = {
        "Keygen": {
            "LDAPOrder":
            IDGUtils.str_on_off(module.params['ldap_reverse_order']),
            "C": certificate_data['country'],
            "ST": certificate_data['state'],
            "L": certificate_data['locality'],
            "O": certificate_data['organization'],
            "OU": certificate_data['organizational_unit'],
            "OU1": certificate_data['organizational_unit1'],
            "OU2": certificate_data['organizational_unit2'],
            "OU3": certificate_data['organizational_unit3'],
            "CN": certificate_data['common_name'],
            "Days": certificate_data['days'],
            "KeyType": module.params['key_type'],
            "KeyLength": module.params['key_length'],
            "Digest": module.params['digest'],
            "ECDSACurve": module.params['ecdsa_curve'],
            "FileName": module.params['prefix_name'],
            "PasswordAlias": module.params['password_alias'],
            "ExportKey": IDGUtils.str_on_off(module.params['export_key']),
            "ExportSSCert":
            IDGUtils.str_on_off(module.params['export_sscert']),
            "GenSSCert": IDGUtils.str_on_off(module.params['gen_sscert']),
            "HSM": IDGUtils.str_on_off(module.params['hsm']),
            "UsingKey": module.params['using_key']
        }
    }

    create_msg = copy.deepcopy(create_tpl)
    for k, v in create_tpl['Keygen'].items():
        if v is None:
            del create_msg['Keygen'][k]

    URI_KEYGEN = IDGApi.URI_ACTION.format(domain_name)

    # Intermediate values ​​for result
    tmp_result = {
        "domain": domain_name,
        "msg": None,
        "changed": None,
        "key-file": None,
        "sscert-file": None,
        "csr-file": None
    }

    #
    # Here the action begins
    #

    pdb.set_trace()
    try:

        idg_mgmt.api_call(URI_KEYGEN,
                          method='POST',
                          data=json.dumps(create_msg),
                          id="keygen_call")

        if idg_mgmt.is_ok(idg_mgmt.last_call()):  # If the answer is correct
            tmp_result['msg'] = idg_mgmt.last_call()["data"]['Keygen']
            tmp_result['changed'] = True

            # Directories
            key_dir = TMP_DIR if module.params['export_key'] else CERT_DIR

            if "FileName" in create_msg["Keygen"].keys():
                tmp_result['key-file'] = key_dir + create_msg["Keygen"][
                    "FileName"] + '-' + CRYPTO_KEY_POSTFIX + '.' + CRYPTO_FORMAT_EXT
                if module.params['gen_sscert']:
                    ssc_dir = TMP_DIR if module.params[
                        'export_sscert'] else CERT_DIR
                    tmp_result['sscert-file'] = ssc_dir + create_msg["Keygen"][
                        "FileName"] + '-' + CRYPTO_SSC_POSTFIX + '.' + CRYPTO_FORMAT_EXT
                tmp_result['csr-file'] = TMP_DIR + create_msg["Keygen"][
                    "FileName"] + '.' + CSR_EXT

            else:
                tmp_result['key-file'] = key_dir + create_msg["Keygen"][
                    "CN"] + '-' + CRYPTO_KEY_POSTFIX + '.' + CRYPTO_FORMAT_EXT
                if module.params['gen_sscert']:
                    ssc_dir = TMP_DIR if module.params[
                        'export_sscert'] else CERT_DIR
                    tmp_result['sscert-file'] = ssc_dir + create_msg["Keygen"][
                        "CN"] + '-' + CRYPTO_SSC_POSTFIX + '.' + CRYPTO_FORMAT_EXT
                tmp_result['csr-file'] = TMP_DIR + create_msg["Keygen"][
                    "CN"] + '.' + CSR_EXT

        else:  # Wrong request
            module.fail_json(
                msg=IDGApi.GENERAL_STATELESS_ERROR.format(
                    __MODULE_FULLNAME, domain_name) +
                str(ErrorHandler(idg_mgmt.last_call()["data"]['error'])))

        #
        # Finish
        #
        # Customize the result
        del result['name']
        # Update
        for k, v in tmp_result.items():
            if v is not None:
                result[k] = v

    except Exception as e:
        # Uncontrolled exception
        module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION +
                              '. {0}').format(to_native(e)))
    else:
        # That's all folks!
        module.exit_json(**result)
Exemple #3
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)
Exemple #4
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)
Exemple #5
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)
Exemple #6
0
def translate(module, d):

    # Class keywords
    valid_class = [
        "AAAPolicy",  # AAA Policy
        "AccessControlList",  # Access Control List
        "TAM",  # Access Manager Client
        "ISAMReverseProxyJunction",  # Access Manager Junction (deprecated)
        "ISAMReverseProxy",  # Access Manager Reverse Proxy (deprecated)
        "ISAMRuntime",  # Access Manager Runtime (deprecated)
        "AccessProfile",  # Access Profile
        "AnalyticsEndpoint",  # Analytics Endpoint
        "APIClientIdentification",  # API Client Identification Action
        "APICollection",  # API Collection
        "APIConnectGatewayService",  # API Connect Gateway Service
        "APIContext",  # API Context Action
        "APICORS",  # API CORS Action
        "APIDefinition",  # API Definition
        "APIExecute",  # API Execute Action
        "APIGateway",  # API Gateway
        "APILDAPRegistry",  # API LDAP Registry
        "OperationRateLimit",  # API Operation Rate Limit
        "APIOperation",  # API Operation
        "APIPath",  # API Path
        "APIPlan",  # API Plan
        "APIRateLimit",  # API Rate Limit Action
        "APIResult",  # API Result Action
        "APIRouting",  # API Routing Action
        "APIRule",  # API Rule
        "APISecurity",  # API Security Action
        "APISecurityAPIKey",  # API Security API Key
        "APISecurityBasicAuth",  # API Security Basic Authentication
        "APISecurityOAuthReq",  # API Security OAuth Requirement
        "APISecurityOAuth",  # API Security OAuth
        "APISecurityRequirement",  # API Security Requirement
        "APISecurityTokenManager",  # API Security Token Manager
        "Domain",  # Application Domain
        "AppSecurityPolicy",  # Application Security Policy
        "AS1PollerSourceProtocolHandler",  # AS1 Poller Handler
        "AS2SourceProtocolHandler",  # AS2 Handler
        "AS3SourceProtocolHandler",  # AS3 Handler
        "AssemblyActionGatewayScript",  # Assembly GatewayScript Action
        "AssemblyActionJWTGenerate",  # Assembly Generate JWT Action
        "AssemblyActionInvoke",  # Assembly Invoke Action
        "AssemblyActionJson2Xml",  # Assembly JSON to XML Action
        "AssemblyActionMap",  # Assembly Map Action
        "AssemblyActionOAuth",  # Assembly OAuth Action
        "AssemblyActionParse",  # Assembly Parse Action
        "AssemblyActionSetVar",  # Assembly Set Variable Action
        "AssemblyLogicSwitch",  # Assembly Switch Action
        "AssemblyActionThrow",  # Assembly Throw Action
        "AssemblyActionUserSecurity",  # Assembly User Security Action
        "AssemblyActionJWTValidate",  # Assembly Validate JWT Action
        "AssemblyActionXml2Json",  # Assembly XML to JSON Action
        "AssemblyActionXSLT",  # Assembly XSLT Action
        "Assembly",  # Assembly
        "AuditLog",  # Audit Log Settings
        "B2BCPACollaboration",  # B2B CPA Collaboration
        "B2BCPA",  # B2B CPA
        "B2BGateway",  # B2B Gateway
        "B2BProfileGroup",  # B2B Partner Profile Group
        "B2BProfile",  # B2B Partner Profile
        "B2BPersistence",  # B2B Persistence
        "B2BXPathRoutingPolicy",  # B2B XPath Routing Policy
        "SecureBackupMode",  # Backup Mode
        "CloudConnectorService",  # Cloud Connector Service
        "CloudGatewayService",  # Cloud Gateway Service
        "SecureCloudConnector",  # Cloud Instance (deprecated)
        "CompactFlash",  # Compact Flash
        "CompileOptionsPolicy",  # Compile Options Policy
        "ConfigSequence",  # Configuration Sequence
        "ConformancePolicy",  # Conformance Policy
        "CookieAttributePolicy",  # Cookie Attribute Policy
        "B2BCPAReceiverSetting",  # CPA Receiver Setting
        "B2BCPASenderSetting",  # CPA Sender Setting
        "CRLFetch",  # CRL Retrieval
        "CertMonitor",  # Crypto Certificate Monitor
        "CryptoCertificate",  # Crypto Certificate
        "CryptoFWCred",  # Crypto Firewall Credentials
        "CryptoIdentCred",  # Crypto Identification Credentials
        "CryptoKey",  # Crypto Key
        "CryptoProfile",  # Crypto Profile
        "CryptoSSKey",  # Crypto Shared Secret Key
        "CryptoValCred",  # Crypto Validation Credentials
        "MCFCustomRule",  # Custom Rule Message Content Filter
        "DeploymentPolicyParametersBinding",  # Deployment Policy Variables
        "ConfigDeploymentPolicy",  # Deployment Policy
        "DFDLSettings",  # DFDL Settings
        "DNSNameService",  # DNS Settings
        "DocumentCryptoMap",  # Document Crypto Map
        "DomainAvailability",  # Domain Availability
        "DomainSettings",  # Domain Settings
        "EBMS2SourceProtocolHandler",  # ebMS2 Handler
        "EBMS3SourceProtocolHandler",  # ebMS3 Handler
        "EthernetInterface",  # Ethernet Interface
        "WXSGrid",  # eXtreme Scale Grid
        "ErrorReportSettings",  # Failure Notification
        "FTPFilePollerSourceProtocolHandler",  # FTP Poller Handler
        "FTPQuoteCommands",  # FTP Quoted Commands
        "FTPServerSourceProtocolHandler",  # FTP Server Handler
        "GatewayPeering",  # Gateway Peering
        "GWScriptSettings",  # GatewayScript Settings
        "HostAlias",  # Host Alias
        "FormsLoginPolicy",  # HTML Forms Login Policy
        "HTTPSourceProtocolHandler",  # HTTP Handler
        "MCFHttpHeader",  # HTTP Header Message Content Filter
        "HTTPInputConversionMap",  # HTTP Input Conversion Map
        "MCFHttpMethod",  # HTTP Method Message Content Filter
        "HTTPService",  # HTTP Service
        "MCFHttpURL",  # HTTP URL Message Content Filter
        "HTTPSSourceProtocolHandler",  # HTTPS Handler
        "MQSourceProtocolHandler",  # IBM MQ Handler
        "MQQMGroup",  # IBM MQ Queue Manager Group
        "MQQM",  # IBM MQ Queue Manager
        "MQFTESourceProtocolHandler",  # IBM MQFTE Handler
        "ILMTScanner",  # ILMT Disconnected Scanner
        "ImportPackage",  # Import Configuration File
        "IMSCalloutSourceProtocolHandler",  # IMS Callout Handler
        "IMSConnectSourceProtocolHandler",  # IMS Connect Handler
        "IMSConnect",  # IMS Connect
        "IncludeConfig",  # Include Configuration File
        "InteropService",  # Interoperability Test Service
        "IPMulticast",  # IP Multicast
        "IPMILanChannel",  # IPMI LAN Channel
        "IPMIUser",  # IPMI User
        "IScsiChapConfig",  # iSCSI CHAP
        "IScsiHBAConfig",  # iSCSI Host Bus Adapter
        "IScsiInitiatorConfig",  # iSCSI Initiator
        "IScsiTargetConfig",  # iSCSI Target
        "IScsiVolumeConfig",  # iSCSI Volume
        "JSONSettings",  # JSON Settings
        "JWEHeader",  # JWE Header
        "JWERecipient",  # JWE Recipient
        "JWSSignature",  # JWS Signature
        "AAAJWTGenerator",  # JWT Generator
        "AAAJWTValidator",  # JWT Validator
        "CryptoKerberosKDC",  # Kerberos KDC Server
        "CryptoKerberosKeytab",  # Kerberos Keytab
        "Language",  # Language
        "LDAPConnectionPool",  # LDAP Connection Pool
        "LDAPSearchParameters",  # LDAP Search Parameters
        "LinkAggregation",  # Link Aggregation Interface
        "LoadBalancerGroup",  # Load Balancer Group
        "LogLabel",  # Log Category
        "LogTarget",  # Log Target
        "LunaPartition",  # Luna HSM Partition
        "Luna",  # Luna HSM
        "Matching",  # Matching Rule
        "AS2ProxySourceProtocolHandler",  # MEIG AS2 Proxy Handler
        "MessageContentFilters",  # Message Content Filters
        "CountMonitor",  # Message Count Monitor
        "DurationMonitor",  # Message Duration Monitor
        "FilterAction",  # Message Filter Action
        "MessageMatching",  # Message Matching
        "MessageType",  # Message Type
        "MTOMPolicy",  # MTOM Policy
        "MPGWErrorAction",  # Multi-Protocol Gateway Error Action
        "MPGWErrorHandlingPolicy",  # Multi-Protocol Gateway Error Policy
        "MultiProtocolGateway",  # Multi-Protocol Gateway
        "NameValueProfile",  # Name-Value Profile
        "NetworkSettings",  # Network Settings
        "NFSClientSettings",  # NFS Client Settings
        "NFSDynamicMounts",  # NFS Dynamic Mounts
        "NFSFilePollerSourceProtocolHandler",  # NFS Poller Handler
        "NFSStaticMount",  # NFS Static Mounts
        "ZosNSSClient",  # NSS Client
        "NTPService",  # NTP Service
        "OAuthSupportedClientGroup",  # OAuth Client Group
        "OAuthSupportedClient",  # OAuth Client Profile
        "OAuthProviderSettings",  # OAuth Provider Settings
        "ODRConnectorGroup",  # ODR Connector Group
        "ODR",  # On Demand Router
        "ParseSettings",  # Parse Settings
        "PasswordAlias",  # Password Map Alias
        "Pattern",  # Pattern
        "PeerGroup",  # Peer Group
        "PolicyAttachments",  # Policy Attachment
        "PolicyParameters",  # Policy Parameters
        "POPPollerSourceProtocolHandler",  # POP Poller Handler
        "StylePolicyAction",  # Processing Action
        "ProcessingMetadata",  # Processing Metadata
        "StylePolicy",  # Processing Policy
        "StylePolicyRule",  # Processing Rule
        "ProductInsights",  # Product Insights
        "QuotaEnforcementServer",  # Quota Enforcement Server
        "RADIUSSettings",  # RADIUS Settings
        "RaidVolume",  # RAID Array
        "SimpleCountMonitor",  # Rate Limiter
        "RBMSettings",  # RBM Settings
        "JOSERecipientIdentifier",  # Recipient Identifier
        "RestMgmtInterface",  # REST Management Interface
        "SAMLAttributes",  # SAML Attributes
        "SchemaExceptionMap",  # Schema Exception Map
        "SecureGatewayClient",  # Secure Gateway Client
        "WebAppSessionPolicy",  # Session Management Policy
        "SFTPFilePollerSourceProtocolHandler",  # SFTP Poller Handler
        "SSHServerSourceProtocolHandler",  # SFTP Server Handler
        "ShellAlias",  # Shell Alias (deprecated)
        "JOSESignatureIdentifier",  # Signature Identifier
        "SLMAction",  # SLM Action
        "SLMCredClass",  # SLM Credential Class
        "SLMPolicy",  # SLM Policy
        "SLMRsrcClass",  # SLM Resource Class
        "SLMSchedule",  # SLM Schedule
        "SMTPServerConnection",  # SMTP Server Connection
        "SNMPSettings",  # SNMP Settings
        "SOAPHeaderDisposition",  # SOAP Header Disposition Table
        "SocialLoginPolicy",  # Social Login Policy
        "SQLRuntimeSettings",  # SQL Data Source Runtime Settings
        "SQLDataSource",  # SQL Data Source
        "SSHClientProfile",  # SSH Client Profile
        "SSHDomainClientProfile",  # SSH Domain Client Profile
        "SSHServerProfile",  # SSH Server Profile
        "SSHService",  # SSH Service
        "SSLClientProfile",  # SSL Client Profile
        "SSLSNIMapping",  # SSL Host Name Mapping
        "SSLProxyProfile",  # SSL Proxy Profile (deprecated)
        "SSLProxyService",  # SSL Proxy Service
        "SSLServerProfile",  # SSL Server Profile
        "SSLSNIServerProfile",  # SSL SNI Server Profile
        "StandaloneStandbyControl",  # Standalone Standby Control
        "StandaloneStandbyControlInterface",  # StandaloneStandbyControlInterface
        "XTCProtocolHandler",  # Stateful Raw XML Handler
        "StatelessTCPSourceProtocolHandler",  # Stateless Raw XML Handler
        "Statistics",  # Statistic Settings
        "ZHybridTargetControlService",  # Sysplex Distributor Target Control Service
        "SystemSettings",  # System Settings
        "TCPProxyService",  # TCP Proxy Service
        "TelnetService",  # Telnet Service
        "Tenant",  # Tenant
        "Throttler",  # Throttle Settings
        "TibcoEMSSourceProtocolHandler",  # TIBCO EMS Handler
        "TibcoEMSServer",  # TIBCO EMS
        "TimeSettings",  # Time Settings
        "TFIMEndpoint",  # Tivoli Federated Identity Manager
        "UDDIRegistry",  # UDDI Registry (deprecated)
        "UDDISubscription",  # UDDI Subscription (deprecated)
        "URLMap",  # URL Map
        "URLRefreshPolicy",  # URL Refresh Policy
        "URLRewritePolicy",  # URL Rewrite Policy
        "User",  # User Account
        "HTTPUserAgent",  # User Agent
        "UserGroup",  # User Group
        "VLANInterface",  # VLAN Interface
        "WebAppErrorHandlingPolicy",  # Web Application Firewall Error Policy
        "WebAppFW",  # Web Application Firewall
        "WebB2BViewer",  # Web B2B Viewer Management Service
        "WebGUI",  # Web Management Service
        "WebAppRequest",  # Web Request Profile
        "WebAppResponse",  # Web Response Profile
        "WSGateway",  # Web Service Proxy
        "WebServicesAgent",  # Web Services Management Agent
        "WebServiceMonitor",  # Web Services Monitor
        "WebTokenService",  # Web Token Service
        "WCCService",  # WebSphere Cell
        "WebSphereJMSSourceProtocolHandler",  # WebSphere JMS Handler
        "WebSphereJMSServer",  # WebSphere JMS
        "WSEndpointRewritePolicy",  # WS-Proxy Endpoint Rewrite
        "WSStylePolicy",  # WS-Proxy Processing Policy
        "WSStylePolicyRule",  # WS-Proxy Processing Rule
        "WSRRSavedSearchSubscription",  # WSRR Saved Search Subscription
        "WSRRServer",  # WSRR Server
        "WSRRSubscription",  # WSRR Subscription
        "XACMLPDP",  # XACML Policy Decision Point
        "XC10Grid",  # XC10 Grid (deprecated)
        "xmltrace",  # XML File Capture
        "XMLFirewallService",  # XML Firewall Service
        "MgmtInterface",  # XML Management Interface
        "XMLManager",  # XML Manager
        "MCFXPath",  # XPath Message Content Filter
        "XPathRoutingMap",  # XPath Routing Map
        "XSLCoprocService",  # XSL Coprocessor Service
        "XSLProxyService"  # XSL Proxy Service
    ]

    if d["class"] not in valid_class:
        module.fail_json(
            msg='The class({0}) defined for the object "{1}" is not valid'.
            format(d["class"], d["name"]))

    t = {"class": d["class"], "name": d["name"]}

    if "ref_objects" in d.keys():
        t.update({"ref-objects": IDGUtils.str_on_off(d["ref_objects"])})
    if "ref_files" in d.keys():
        t.update({"ref-files": IDGUtils.str_on_off(d["ref_files"])})
    if "include_debug" in d.keys():
        t.update({"include-debug": IDGUtils.str_on_off(d["include_debug"])})

    return t
def main():

    try:
        # Arguments/parameters that a user can pass to the module
        module_args = dict(
            state=dict(type='str',
                       choices=['exported', 'imported', 'reseted', 'saved'],
                       default='saved'),  # Domain's operational state
            idg_connection=dict(type='dict',
                                options=idg_endpoint_spec,
                                required=True),  # IDG connection
            name=dict(type='str', required=True),  # Domain to work
            # for Export
            user_summary=dict(type='str'),  # Backup comment
            all_files=dict(
                type='bool', default=False
            ),  # Include all files in the local: directory for the domain
            persisted=dict(type='bool', default=False
                           ),  # Export from persisted or running configuration
            internal_files=dict(
                type='bool',
                default=True),  # Export internal configuration file
            # for Import
            input_file=dict(type='str', required=False,
                            no_log=True),  # The base64-encoded BLOB to import
            overwrite_files=dict(type='bool',
                                 default=False),  # Overwrite files that exist
            overwrite_objects=dict(
                type='bool', default=False),  # Overwrite objects that exist
            dry_run=dict(
                type='bool', default=False
            ),  # Import package (on) or validate the import operation without importing (off).
            rewrite_local_ip=dict(
                type='bool', default=False
            )  # The local address binding to their equivalent interfaces in appliance
            # TODO !!!
            # DeploymentPolicy
        )

        # AnsibleModule instantiation
        module = AnsibleModule(
            argument_spec=module_args,
            supports_check_mode=True,
            # Interaction between parameters
            required_if=[['state', 'imported', ['input_file']]])

        # Validates the dependence of the utility module
        if not HAS_IDG_DEPS:
            module.fail_json(msg="The IDG utils modules is required")

        # Parse arguments to dict
        idg_data_spec = IDGUtils.parse_to_dict(module,
                                               module.params['idg_connection'],
                                               'IDGConnection',
                                               IDGUtils.ANSIBLE_VERSION)

        # Status & domain
        state = module.params['state']
        domain_name = module.params['name']

        # Init IDG API connect
        idg_mgmt = IDGApi(ansible_module=module,
                          idg_host="https://{0}:{1}".format(
                              idg_data_spec['server'],
                              idg_data_spec['server_port']),
                          headers=IDGUtils.BASIC_HEADERS,
                          http_agent=IDGUtils.HTTP_AGENT_SPEC,
                          use_proxy=idg_data_spec['use_proxy'],
                          timeout=idg_data_spec['timeout'],
                          validate_certs=idg_data_spec['validate_certs'],
                          user=idg_data_spec['user'],
                          password=idg_data_spec['password'],
                          force_basic_auth=IDGUtils.BASIC_AUTH_SPEC)

        # Variable to store the status of the action
        action_result = ''

        # Configuration template for the domain
        export_action_msg = {
            "Export": {
                "Format":
                "ZIP",
                "UserComment":
                module.params['user_summary'],
                "AllFiles":
                IDGUtils.str_on_off(module.params['all_files']),
                "Persisted":
                IDGUtils.str_on_off(module.params['persisted']),
                "IncludeInternalFiles":
                IDGUtils.str_on_off(module.params['internal_files'])
                # TODO
                # "DeploymentPolicy":""
            }
        }

        import_action_msg = {
            "Import": {
                "Format":
                "ZIP",
                "InputFile":
                module.params['input_file'],
                "OverwriteFiles":
                IDGUtils.str_on_off(module.params['overwrite_files']),
                "OverwriteObjects":
                IDGUtils.str_on_off(module.params['overwrite_objects']),
                "DryRun":
                IDGUtils.str_on_off(module.params['dry_run']),
                "RewriteLocalIP":
                IDGUtils.str_on_off(module.params['rewrite_local_ip'])
                # TODO
                # "DeploymentPolicy": "name",
                # "DeploymentPolicyParams": "name",
            }
        }

        # Action messages
        # Reset
        reset_act_msg = {"ResetThisDomain": {}}

        # Save
        save_act_msg = {"SaveConfig": {}}

        #
        # Here the action begins
        #

        # Intermediate values ​​for result
        tmp_result = {
            "name": domain_name,
            "msg": None,
            "file": None,
            "changed": None,
            "failed": None
        }

        # List of configured domains
        chk_code, chk_msg, chk_data = idg_mgmt.api_call(IDGApi.URI_DOMAIN_LIST,
                                                        method='GET')

        if chk_code == 200 and chk_msg == 'OK':  # If the answer is correct

            if isinstance(chk_data['domain'],
                          dict):  # if has only default domain
                configured_domains = [chk_data['domain']['name']]
            else:
                configured_domains = [d['name'] for d in chk_data['domain']]

            if domain_name in configured_domains:  # Domain EXIST.

                # pdb.set_trace()
                if state == 'exported':

                    # If the user is working in only check mode we do not want to make any changes
                    IDGUtils.implement_check_mode(module, result)

                    # export and finish
                    # pdb.set_trace()
                    exp_code, exp_msg, exp_data = idg_mgmt.api_call(
                        IDGApi.URI_ACTION.format(domain_name),
                        method='POST',
                        data=json.dumps(export_action_msg))

                    if exp_code == 202 and exp_msg == 'Accepted':
                        # Asynchronous actions export accepted. Wait for complete
                        action_result = idg_mgmt.wait_for_action_end(
                            IDGApi.URI_ACTION.format(domain_name),
                            href=exp_data['_links']['location']['href'],
                            state=state)

                        # Export completed. Get result
                        doex_code, doex_msg, doex_data = idg_mgmt.api_call(
                            exp_data['_links']['location']['href'],
                            method='GET')

                        if doex_code == 200 and doex_msg == 'OK':
                            # Export ok
                            tmp_result['file'] = doex_data['result']['file']
                            tmp_result['msg'] = action_result
                            tmp_result['changed'] = True
                        else:
                            # Can't retrieve the export
                            module.fail_json(
                                msg=IDGApi.ERROR_RETRIEVING_RESULT.format(
                                    state, domain_name))

                    elif exp_code == 200 and exp_msg == 'OK':
                        # Successfully processed synchronized action
                        tmp_result['msg'] = idg_mgmt.status_text(
                            exp_data['Export'])
                        tmp_result['changed'] = True

                    else:
                        # Export not accepted
                        module.fail_json(
                            msg=IDGApi.ERROR_ACCEPTING_ACTION.format(
                                state, domain_name))

                elif state == 'reseted':

                    # If the user is working in only check mode we do not want to make any changes
                    IDGUtils.implement_check_mode(module, result)

                    # Reseted domain
                    reset_code, reset_msg, reset_data = idg_mgmt.api_call(
                        IDGApi.URI_ACTION.format(domain_name),
                        method='POST',
                        data=json.dumps(reset_act_msg))

                    # pdb.set_trace()
                    if reset_code == 202 and reset_msg == 'Accepted':
                        # Asynchronous actions reset accepted. Wait for complete
                        action_result = idg_mgmt.wait_for_action_end(
                            IDGApi.URI_ACTION.format(domain_name),
                            href=reset_data['_links']['location']['href'],
                            state=state)

                        # Reseted completed
                        dore_code, dore_msg, dore_data = idg_mgmt.api_call(
                            reset_data['_links']['location']['href'],
                            method='GET')

                        if dore_code == 200 and dore_msg == 'OK':
                            # Reseted successfully
                            tmp_result['msg'] = dore_data['status'].capitalize(
                            )
                            tmp_result['changed'] = True
                        else:
                            # Can't retrieve the reset result
                            module.fail_json(
                                msg=IDGApi.ERROR_RETRIEVING_RESULT.format(
                                    state, domain_name))

                    elif reset_code == 200 and reset_msg == 'OK':
                        # Successfully processed synchronized action
                        tmp_result['msg'] = idg_mgmt.status_text(
                            reset_data['ResetThisDomain'])
                        tmp_result['changed'] = True

                    else:
                        # Reseted not accepted
                        module.fail_json(
                            msg=IDGApi.ERROR_ACCEPTING_ACTION.format(
                                state, domain_name))

                elif state == 'saved':

                    qds_code, qds_msg, qds_data = idg_mgmt.api_call(
                        IDGApi.URI_DOMAIN_STATUS, method='GET')

                    # pdb.set_trace()
                    if qds_code == 200 and qds_msg == 'OK':

                        if isinstance(qds_data['DomainStatus'], dict):
                            domain_save_needed = qds_data['DomainStatus'][
                                'SaveNeeded']
                        else:
                            domain_save_needed = [
                                d['SaveNeeded']
                                for d in qds_data['DomainStatus']
                                if d['Domain'] == domain_name
                            ][0]

                        # Saved domain
                        if domain_save_needed != 'off':

                            # If the user is working in only check mode we do not want to make any changes
                            IDGUtils.implement_check_mode(module, result)

                            save_code, save_msg, save_data = idg_mgmt.api_call(
                                IDGApi.URI_ACTION.format(domain_name),
                                method='POST',
                                data=json.dumps(save_act_msg))

                            # pdb.set_trace()
                            if save_code == 202 and save_msg == 'Accepted':
                                # Asynchronous actions save accepted. Wait for complete
                                action_result = idg_mgmt.wait_for_action_end(
                                    IDGApi.URI_ACTION.format(domain_name),
                                    href=save_data['_links']['location']
                                    ['href'],
                                    state=state)

                                # Save ready
                                dosv_code, dosv_msg, dosv_data = idg_mgmt.api_call(
                                    save_data['_links']['location']['href'],
                                    method='GET')

                                if dosv_code == 200 and dosv_msg == 'OK':
                                    # Save completed
                                    tmp_result['msg'] = action_result
                                    tmp_result['changed'] = True
                                else:
                                    # Can't retrieve the save result
                                    module.fail_json(
                                        msg=IDGApi.ERROR_RETRIEVING_RESULT.
                                        format(state, domain_name))

                            elif save_code == 200 and save_msg == 'OK':
                                # Successfully processed synchronized action save
                                tmp_result['msg'] = idg_mgmt.status_text(
                                    save_data['SaveConfig'])
                                tmp_result['changed'] = True
                            else:
                                # Can't saved
                                module.fail_json(
                                    msg=IDGApi.ERROR_RETRIEVING_RESULT.format(
                                        state, domain_name))
                        else:
                            # Domain is save
                            tmp_result['msg'] = IDGUtils.IMMUTABLE_MESSAGE

                elif state == 'imported':

                    # If the user is working in only check mode we do not want to make any changes
                    IDGUtils.implement_check_mode(module, result)

                    # Import
                    # pdb.set_trace()
                    imp_code, imp_msg, imp_data = idg_mgmt.api_call(
                        IDGApi.URI_ACTION.format(domain_name),
                        method='POST',
                        data=json.dumps(import_action_msg))

                    if imp_code == 202 and imp_msg == 'Accepted':
                        # Asynchronous actions import accepted. Wait for complete
                        action_result = idg_mgmt.wait_for_action_end(
                            IDGApi.URI_ACTION.format(domain_name),
                            href=imp_data['_links']['location']['href'],
                            state=state)

                        # Import ready
                        doim_code, doim_msg, doim_data = idg_mgmt.api_call(
                            imp_data['_links']['location']['href'],
                            method='GET')

                        if doim_code == 200 and doim_msg == 'OK':
                            # Export completed
                            import_results = doim_data['result']['Import'][
                                'import-results']
                            if import_results['detected-errors'] != 'false':
                                # Import failed
                                # pdb.set_trace()
                                tmp_result[
                                    'msg'] = 'Import failed with error code: "' + import_results[
                                        'detected-errors']['error'] + '"'
                                tmp_result['changed'] = False
                                tmp_result['failed'] = True
                            else:
                                # Import success
                                tmp_result.update({"results":
                                                   []})  # Update to result

                                tmp_result['results'].append({
                                    "export-details":
                                    import_results['export-details']
                                })

                                # EXEC-SCRIPT-RESULTS
                                try:
                                    exec_script_results = import_results[
                                        'exec-script-results']
                                    try:
                                        if isinstance(
                                                exec_script_results[
                                                    'cfg-result'], list):

                                            tmp_result['results'].append({
                                                "exec-script-results": {
                                                    "summary": {
                                                        "total":
                                                        len(exec_script_results[
                                                            'cfg-result']),
                                                        "status":
                                                        get_status_summary(
                                                            exec_script_results[
                                                                'cfg-result'])
                                                    },
                                                    "detail":
                                                    exec_script_results[
                                                        'cfg-result']
                                                }
                                            })
                                        else:
                                            tmp_result['results'].append({
                                                "exec-script-results":
                                                exec_script_results[
                                                    'cfg-result']
                                            })

                                    except Exception as e:
                                        tmp_result['results'].append({
                                            "exec-script-results":
                                            exec_script_results
                                        })

                                except Exception as e:
                                    pass

                                try:
                                    tmp_result['results'].append({
                                        "file-copy-log":
                                        import_results['file-copy-log']
                                        ['file-result']
                                    })
                                except Exception as e:
                                    pass

                                try:
                                    tmp_result['results'].append({
                                        "imported-debug":
                                        import_results['imported-debug']
                                    })
                                except Exception as e:
                                    pass

                                # IMPORTED-FILES
                                try:
                                    imported_files = import_results[
                                        'imported-files']
                                    try:
                                        if isinstance(imported_files['file'],
                                                      list):

                                            tmp_result['results'].append({
                                                "imported-files": {
                                                    "summary": {
                                                        "total":
                                                        len(imported_files[
                                                            'file']),
                                                        "status":
                                                        get_status_summary(
                                                            imported_files[
                                                                'file'])
                                                    },
                                                    "detail":
                                                    imported_files['file']
                                                }
                                            })
                                        else:
                                            tmp_result['results'].append({
                                                "imported-files":
                                                imported_files['file']
                                            })

                                    except Exception as e:
                                        tmp_result['results'].append(
                                            {"imported-files": imported_files})

                                except Exception as e:
                                    pass

                                # IMPORTED-OBJECTS
                                try:
                                    imported_objects = import_results[
                                        'imported-objects']
                                    try:
                                        if isinstance(
                                                imported_objects['object'],
                                                list):

                                            tmp_result['results'].append({
                                                "imported-objects": {
                                                    "summary": {
                                                        "total":
                                                        len(imported_objects[
                                                            'object']),
                                                        "status":
                                                        get_status_summary(
                                                            imported_objects[
                                                                'object'])
                                                    },
                                                    "detail":
                                                    imported_objects['object']
                                                }
                                            })
                                        else:
                                            tmp_result['results'].append({
                                                "imported-objects":
                                                imported_objects['object']
                                            })

                                    except Exception as e:
                                        tmp_result['results'].append({
                                            "imported-objects":
                                            imported_objects
                                        })

                                except Exception as e:
                                    pass

                                tmp_result['msg'] = doim_data[
                                    'status'].capitalize()
                                tmp_result['changed'] = True
                        else:
                            # Can't retrieve the import result
                            module.fail_json(
                                msg=IDGApi.ERROR_RETRIEVING_RESULT.format(
                                    state, domain_name))

                    elif imp_code == 200 and imp_msg == 'OK':
                        # Successfully processed synchronized action
                        tmp_result['msg'] = idg_mgmt.status_text(
                            imp_data['Import'])
                        tmp_result['changed'] = True

                    else:
                        # Imported not accepted
                        module.fail_json(
                            msg=IDGApi.ERROR_ACCEPTING_ACTION.format(
                                state, domain_name))

            else:  # Domain NOT EXIST.
                # pdb.set_trace()
                # Opps can't work the configuration of non-existent domain
                module.fail_json(
                    msg=(IDGApi.ERROR_REACH_STATE + " " +
                         IDGApi.ERROR_NOT_DOMAIN).format(state, domain_name))

        else:  # Can't read domain's lists
            module.fail_json(msg=IDGApi.ERROR_GET_DOMAIN_LIST)

        #
        # Finish
        #
        # Update
        for k, v in tmp_result.items():
            if v != None:
                result[k] = v

    except (NameError, UnboundLocalError) as e:
        # Very early error
        module_except = AnsibleModule(argument_spec={})
        module_except.fail_json(msg=to_native(e))

    except Exception as e:
        # Uncontrolled exception
        module.fail_json(msg=(IDGUtils.UNCONTROLLED_EXCEPTION +
                              '. {0}').format(to_native(e)))
    else:
        # That's all folks!
        module.exit_json(**result)