Ejemplo n.º 1
0
    def rpc(self, action, params):
        """Make a call to the LogicMonitor RPC library
        and return the response"""
        self.module.debug("Running LogicMonitor.rpc")

        param_str = urlencode(params)
        creds = urlencode({
            "c": self.company,
            "u": self.user,
            "p": self.password
        })

        if param_str:
            param_str = param_str + "&"

        param_str = param_str + creds

        try:
            url = ("https://" + self.company + "." + self.lm_url + "/rpc/" +
                   action + "?" + param_str)

            # Set custom LogicMonitor header with version
            headers = {"X-LM-User-Agent": self.__version__}

            # Set headers
            f = open_url(url, headers=headers)

            raw = f.read()
            resp = json.loads(raw)
            if resp["status"] == 403:
                self.module.debug("Authentication failed.")
                self.fail(msg="Error: " + resp["errmsg"])
            else:
                return raw
        except IOError as ioe:
            self.fail(msg="Error: Exception making RPC call to " + "https://" +
                      self.company + "." + self.lm_url + "/rpc/" + action +
                      "\nException" + to_native(ioe))
Ejemplo n.º 2
0
    def __init__(self, session):
        self.session = session
        self.parameters = {}

        for url in session._spec.get("paths").keys():
            methods = session._spec.get("paths").get(url)
            for method in methods.keys():
                operation_spec = methods.get(method)
                operation_name = operation_spec.get("operationId", None)
                parameters = operation_spec.get("parameters")

                if not operation_name:
                    if method.lower() == "post":
                        operation_name = "Create"
                    elif method.lower() == "get":
                        operation_name = "Get"
                    elif method.lower() == "put":
                        operation_name = "Update"
                    elif method.lower() == "delete":
                        operation_name = "Delete"
                    elif method.lower() == "patch":
                        operation_name = "Patch"
                    else:
                        raise SessionConfigurationException(
                            to_native(
                                "Invalid REST method type {0}".format(method)))

                    # Get the non-parameter parts of the URL and append to the operation name
                    # e.g  /application/version -> GetApplicationVersion
                    # e.g. /application/{id}    -> GetApplication
                    # This may lead to duplicates, which we must prevent.
                    operation_name += re.sub(r"{(.*)}", "", url).replace(
                        "/", " ").title().replace(" ", "")
                    operation_spec["operationId"] = operation_name

                op = RestOperation(session, url, method, parameters)
                setattr(self, operation_name,
                        bind(self, op.restmethod, operation_spec))
 def get_destination(self):
     result = None
     release_get = netapp_utils.zapi.NaElement(
         'snapmirror-get-destination-iter')
     query = netapp_utils.zapi.NaElement('query')
     snapmirror_dest_info = netapp_utils.zapi.NaElement(
         'snapmirror-destination-info')
     snapmirror_dest_info.add_new_child('destination-location',
                                        self.parameters['destination_path'])
     query.add_child_elem(snapmirror_dest_info)
     release_get.add_child_elem(query)
     try:
         result = self.source_server.invoke_successfully(
             release_get, enable_tunneling=True)
     except netapp_utils.zapi.NaApiError as error:
         self.module.fail_json(
             msg='Error fetching snapmirror destinations info: %s' %
             to_native(error),
             exception=traceback.format_exc())
     if result.get_child_by_name('num-records') and \
             int(result.get_child_content('num-records')) > 0:
         return True
     return None
Ejemplo n.º 4
0
    def unlock_given_user(self):
        """
        unlocks the user

        :return:
            True if user unlocked
            False if unlock user is not performed
        :rtype: bool
        """
        user_unlock = netapp_utils.zapi.NaElement.create_node_with_children(
            'security-login-unlock', **{'vserver': self.parameters['vserver'],
                                        'user-name': self.parameters['name']})

        try:
            self.server.invoke_successfully(user_unlock,
                                            enable_tunneling=False)
        except netapp_utils.zapi.NaApiError as error:
            if to_native(error.code) == '13114':
                return False
            else:
                self.module.fail_json(msg='Error unlocking user %s: %s' % (self.parameters['name'], to_native(error)),
                                      exception=traceback.format_exc())
        return True
Ejemplo n.º 5
0
def main():
    argument_spec = DigitalOceanHelper.digital_ocean_argument_spec()
    argument_spec.update(
        snapshot_type=dict(type='str',
                           required=False,
                           choices=['all', 'droplet', 'volume', 'by_id'],
                           default='all'),
        snapshot_id=dict(type='str',
                         required=False),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        required_if=[
            ['snapshot_type', 'by_id', ['snapshot_id']],
        ],
    )
    if module._name == 'digital_ocean_snapshot_facts':
        module.deprecate("The 'digital_ocean_snapshot_facts' module has been renamed to 'digital_ocean_snapshot_info'", version='2.13')

    try:
        core(module)
    except Exception as e:
        module.fail_json(msg=to_native(e), exception=format_exc())
    def get_configuration(self):
        """Retrieve the existing audit-log configurations.

        :returns: dictionary containing current audit-log configuration
        """
        try:
            if self.proxy_used:
                rc, data = request(self.url + "audit-log/config",
                                   timeout=300,
                                   headers=self.HEADERS,
                                   **self.creds)
            else:
                rc, data = request(
                    self.url +
                    "storage-systems/%s/audit-log/config" % self.ssid,
                    timeout=300,
                    headers=self.HEADERS,
                    **self.creds)
            return data
        except Exception as err:
            self.module.fail_json(
                msg="Failed to retrieve the audit-log configuration! "
                "Array Id [%s]. Error [%s]." % (self.ssid, to_native(err)))
def create_vgw(client, module):
    params = dict()
    params['Type'] = module.params.get('type')
    if module.params.get('asn'):
        params['AmazonSideAsn'] = module.params.get('asn')

    try:
        response = client.create_vpn_gateway(**params)
        get_waiter(
            client, 'vpn_gateway_exists'
        ).wait(
            VpnGatewayIds=[response['VpnGateway']['VpnGatewayId']]
        )
    except botocore.exceptions.WaiterError as e:
        module.fail_json(msg="Failed to wait for Vpn Gateway {0} to be available".format(response['VpnGateway']['VpnGatewayId']),
                         exception=traceback.format_exc())
    except is_boto3_error_code('VpnGatewayLimitExceeded'):
        module.fail_json(msg="Too many VPN gateways exist in this account.", exception=traceback.format_exc())
    except botocore.exceptions.ClientError as e:  # pylint: disable=duplicate-except
        module.fail_json(msg=to_native(e), exception=traceback.format_exc())

    result = response
    return result
 def quota_entry_modify(self, modify_attrs):
     """
     Modifies a quota entry
     """
     options = {
         'volume': self.parameters['volume'],
         'quota-target': self.parameters['quota_target'],
         'quota-type': self.parameters['type'],
         'qtree': self.parameters['qtree']
     }
     options.update(modify_attrs)
     if self.parameters.get('policy'):
         options['policy'] = str(self.parameters['policy'])
     modify_entry = netapp_utils.zapi.NaElement.create_node_with_children(
         'quota-modify-entry', **options)
     try:
         self.server.invoke_successfully(modify_entry,
                                         enable_tunneling=True)
     except netapp_utils.zapi.NaApiError as error:
         self.module.fail_json(
             msg='Error modifying quota entry %s: %s' %
             (self.parameters['volume'], to_native(error)),
             exception=traceback.format_exc())
def remove_compute_environment(module, aws):
    """
    Remove a Batch compute environment

    :param module:
    :param aws:
    :return:
    """

    client = aws.client('batch')
    changed = False

    # set API parameters
    api_params = {'computeEnvironment': module.params['compute_environment_name']}

    try:
        if not module.check_mode:
            client.delete_compute_environment(**api_params)
        changed = True
    except (ClientError, ParamValidationError, MissingParametersError) as e:
        module.fail_json(msg='Error removing compute environment: {0}'.format(to_native(e)),
                         exception=traceback.format_exc())
    return changed
Ejemplo n.º 10
0
    def set_acceptance_level(self):
        change = []
        for host in self.hosts:
            host_changed = False
            if self.hosts_facts[host.name]['level'] != self.acceptance_level:
                host_image_config_mgr = host.configManager.imageConfigManager
                if host_image_config_mgr:
                    try:
                        if self.module.check_mode:
                            self.hosts_facts[
                                host.name]['level'] = self.acceptance_level
                        else:
                            host_image_config_mgr.UpdateHostImageAcceptanceLevel(
                                newAcceptanceLevel=self.acceptance_level)
                            self.hosts_facts[host.name][
                                'level'] = host_image_config_mgr.HostImageConfigGetAcceptance(
                                )
                        host_changed = True
                    except vim.fault.HostConfigFault as e:
                        self.hosts_facts[host.name]['error'] = to_native(e.msg)

            change.append(host_changed)
        self.module.exit_json(changed=any(change), facts=self.hosts_facts)
 def create_subsystem(self):
     """
     Create a NVME Subsystem
     """
     if self.parameters.get('ostype') is None:
         self.module.fail_json(
             msg=
             "Error: Missing required parameter 'os_type' for creating subsystem"
         )
     options = {
         'subsystem': self.parameters['subsystem'],
         'ostype': self.parameters['ostype']
     }
     subsystem_create = netapp_utils.zapi.NaElement('nvme-subsystem-create')
     subsystem_create.translate_struct(options)
     try:
         self.server.invoke_successfully(subsystem_create,
                                         enable_tunneling=True)
     except netapp_utils.zapi.NaApiError as error:
         self.module.fail_json(
             msg='Error creating subsystem for %s: %s' %
             (self.parameters.get('subsystem'), to_native(error)),
             exception=traceback.format_exc())
Ejemplo n.º 12
0
 def remove_broadcast_domain_ports(self, ports):
     """
     Deletes broadcast domain ports
     :param: ports to be removed.
     """
     domain_obj = netapp_utils.zapi.NaElement(
         'net-port-broadcast-domain-remove-ports')
     domain_obj.add_new_child("broadcast-domain",
                              self.parameters['resource_name'])
     if self.parameters.get('ipspace'):
         domain_obj.add_new_child("ipspace", self.parameters['ipspace'])
     ports_obj = netapp_utils.zapi.NaElement('ports')
     domain_obj.add_child_elem(ports_obj)
     for port in ports:
         ports_obj.add_new_child('net-qualified-port-name', port)
     try:
         self.server.invoke_successfully(domain_obj, True)
         return True
     except netapp_utils.zapi.NaApiError as error:
         self.module.fail_json(
             msg='Error removing port for broadcast domain %s: %s' %
             (self.parameters['resource_name'], to_native(error)),
             exception=traceback.format_exc())
Ejemplo n.º 13
0
    def create_interface(self):
        ''' calling zapi to create interface '''
        required_keys = set(['role', 'home_port'])
        data_protocols_obj = None
        if self.parameters.get('subnet_name') is None:
            required_keys.add('address')
            required_keys.add('netmask')
        data_protocols_obj = self.set_protocol_option(required_keys)
        self.validate_create_parameters(required_keys)

        options = {'interface-name': self.parameters['interface_name'],
                   'role': self.parameters['role'],
                   'home-node': self.parameters.get('home_node'),
                   'vserver': self.parameters['vserver']}
        NetAppOntapInterface.set_options(options, self.parameters)
        interface_create = netapp_utils.zapi.NaElement.create_node_with_children('net-interface-create', **options)
        if data_protocols_obj is not None:
            interface_create.add_child_elem(data_protocols_obj)
        try:
            self.server.invoke_successfully(interface_create, enable_tunneling=True)
        except netapp_utils.zapi.NaApiError as exc:
            self.module.fail_json(msg='Error Creating interface %s: %s' %
                                  (self.parameters['interface_name'], to_native(exc)), exception=traceback.format_exc())
 def delete_log_messages(self):
     """Delete all audit-log messages."""
     self._logger.info("Deleting audit-log messages...")
     try:
         if self.proxy_used:
             rc, result = request(self.url + "audit-log?clearAll=True",
                                  timeout=300,
                                  method="DELETE",
                                  headers=self.HEADERS,
                                  **self.creds)
         else:
             rc, result = request(
                 self.url +
                 "storage-systems/%s/audit-log?clearAll=True" % self.ssid,
                 timeout=300,
                 method="DELETE",
                 headers=self.HEADERS,
                 **self.creds)
     except Exception as err:
         self.module.fail_json(
             msg=
             "Failed to delete audit-log messages! Array Id [%s]. Error [%s]."
             % (self.ssid, to_native(err)))
    def rename_subnet(self):
        """
        TODO
        """
        options = {
            'subnet-name': self.parameters.get('from_name'),
            'new-name': self.parameters.get('name')
        }

        subnet_rename = netapp_utils.zapi.NaElement.create_node_with_children(
            'net-subnet-rename', **options)

        if self.parameters.get('ipspace'):
            subnet_rename.add_new_child('ipspace',
                                        self.parameters.get('ipspace'))

        try:
            self.server.invoke_successfully(subnet_rename, True)
        except netapp_utils.zapi.NaApiError as error:
            self.module.fail_json(
                msg='Error renaming subnet %s: %s' %
                (self.parameters.get('name'), to_native(error)),
                exception=traceback.format_exc())
Ejemplo n.º 16
0
def write_changes(module, b_lines, dest):

    tmpfd, tmpfile = tempfile.mkstemp()
    with os.fdopen(tmpfd, 'wb') as f:
        f.writelines(b_lines)

    validate = module.params.get('validate', None)
    valid = not validate
    if validate:
        if "%s" not in validate:
            module.fail_json(msg="validate must contain %%s: %s" % (validate))
        (rc, out, err) = module.run_command(
            to_bytes(validate % tmpfile, errors='surrogate_or_strict'))
        valid = rc == 0
        if rc != 0:
            module.fail_json(msg='failed to validate: '
                             'rc:%s error:%s' % (rc, err))
    if valid:
        module.atomic_move(tmpfile,
                           to_native(os.path.realpath(
                               to_bytes(dest, errors='surrogate_or_strict')),
                                     errors='surrogate_or_strict'),
                           unsafe_writes=module.params['unsafe_writes'])
 def create_broadcast_domain(self):
     """
     Creates a new broadcast domain
     """
     domain_obj = netapp_utils.zapi.NaElement(
         'net-port-broadcast-domain-create')
     domain_obj.add_new_child("broadcast-domain", self.parameters['name'])
     if self.parameters.get('ipspace'):
         domain_obj.add_new_child("ipspace", self.parameters['ipspace'])
     if self.parameters.get('mtu'):
         domain_obj.add_new_child("mtu", self.parameters['mtu'])
     if self.parameters.get('ports'):
         ports_obj = netapp_utils.zapi.NaElement('ports')
         domain_obj.add_child_elem(ports_obj)
         for port in self.parameters['ports']:
             ports_obj.add_new_child('net-qualified-port-name', port)
     try:
         self.server.invoke_successfully(domain_obj, True)
     except netapp_utils.zapi.NaApiError as error:
         self.module.fail_json(
             msg='Error creating broadcast domain %s: %s' %
             (self.parameters['name'], to_native(error)),
             exception=traceback.format_exc())
    def get_initiators(self):
        """
        Get the existing list of initiators from an igroup
        :rtype: list() or None
        """
        igroup_info = netapp_utils.zapi.NaElement('igroup-get-iter')
        attributes = dict(query={'initiator-group-info': {'initiator-group-name': self.parameters['initiator_group'],
                                                          'vserver': self.parameters['vserver']}})
        igroup_info.translate_struct(attributes)
        result, current = None, []

        try:
            result = self.server.invoke_successfully(igroup_info, True)
        except netapp_utils.zapi.NaApiError as error:
            self.module.fail_json(msg='Error fetching igroup info %s: %s' % (self.parameters['initiator_group'],
                                                                             to_native(error)),
                                  exception=traceback.format_exc())

        if result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) >= 1:
            igroup_info = result.get_child_by_name('attributes-list').get_child_by_name('initiator-group-info')
            if igroup_info.get_child_by_name('initiators') is not None:
                current = [initiator['initiator-name'] for initiator in igroup_info['initiators'].get_children()]
        return current
Ejemplo n.º 19
0
def main():
    argument_spec = ipa_argument_spec()
    argument_spec.update(
        description=dict(type='str'),
        state=dict(type='str',
                   default='present',
                   choices=['present', 'absent', 'enabled', 'disabled']),
        sudocmd=dict(type='str', required=True, aliases=['name']))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)

    client = SudoCmdIPAClient(module=module,
                              host=module.params['ipa_host'],
                              port=module.params['ipa_port'],
                              protocol=module.params['ipa_prot'])
    try:
        client.login(username=module.params['ipa_user'],
                     password=module.params['ipa_pass'])
        changed, sudocmd = ensure(module, client)
        module.exit_json(changed=changed, sudocmd=sudocmd)
    except Exception as e:
        module.fail_json(msg=to_native(e), exception=traceback.format_exc())
Ejemplo n.º 20
0
    def update_api_address_interface_match(self, body):
        """Change network interface address which matches the api_address"""
        try:
            try:
                (rc, data) = request(self.url + 'storage-systems/%s/configuration/ethernet-interfaces' % self.ssid,
                                     use_proxy=False, force=True, ignore_errors=True, method='POST',
                                     data=json.dumps(body), headers=HEADERS, timeout=10, **self.creds)
            except Exception:
                url_parts = list(urlparse.urlparse(self.url))
                domain = url_parts[1].split(":")
                domain[0] = self.address
                url_parts[1] = ":".join(domain)
                expected_url = urlparse.urlunparse(url_parts)
                self._logger.info(pformat(expected_url))

                (rc, data) = request(expected_url + 'storage-systems/%s/configuration/ethernet-interfaces' % self.ssid,
                                     headers=HEADERS, timeout=300, **self.creds)
                return
        except Exception as err:
            self._logger.info(type(err))
            self.module.fail_json(
                msg="Connection failure: we failed to modify the network settings! Array Id [%s]. Error [%s]."
                    % (self.ssid, to_native(err)))
Ejemplo n.º 21
0
def main():
    argument_spec = dict(
        ip_address=dict(required=True),
        key_filename=dict(),
        password=dict(no_log=True),
        cert_cn=dict(required=True),
        cert_friendly_name=dict(required=True),
        rsa_nbits=dict(default='2048'),
        signed_by=dict(required=True)

    )
    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False,
                           required_one_of=[['key_filename', 'password']])
    if paramiko is None:
        module.fail_json(msg='paramiko is required for this module')

    ip_address = module.params["ip_address"]
    key_filename = module.params["key_filename"]
    password = module.params["password"]
    cert_cn = module.params["cert_cn"]
    cert_friendly_name = module.params["cert_friendly_name"]
    signed_by = module.params["signed_by"]
    rsa_nbits = module.params["rsa_nbits"]

    try:
        stdout = generate_cert(module,
                               ip_address,
                               key_filename,
                               password,
                               cert_cn,
                               cert_friendly_name,
                               signed_by,
                               rsa_nbits)
    except Exception as exc:
        module.fail_json(msg=to_native(exc))

    module.exit_json(changed=True, msg="okey dokey")
    def apply_iscsi_settings(self):
        """Update the iSCSI target alias and CHAP settings"""
        update = False
        target = self.target

        body = dict()

        if self.name is not None and self.name != target['alias']:
            update = True
            body['alias'] = self.name

        # If the CHAP secret was provided, we trigger an update.
        if self.chap_secret:
            update = True
            body.update(
                dict(enableChapAuthentication=True,
                     chapSecret=self.chap_secret))
        # If no secret was provided, then we disable chap
        elif target['chap']:
            update = True
            body.update(dict(enableChapAuthentication=False))

        if update and not self.check_mode:
            try:
                request(self.url +
                        'storage-systems/%s/iscsi/target-settings' % self.ssid,
                        method='POST',
                        data=json.dumps(body),
                        headers=HEADERS,
                        **self.creds)
            except Exception as err:
                self.module.fail_json(
                    msg=
                    "Failed to update the iSCSI target settings. Array Id [%s]. Error [%s]."
                    % (self.ssid, to_native(err)))

        return update
def main():
    module = AnsibleModule(
        argument_spec=dict(
            name=dict(),
            glob=dict(),
            color=dict(),
            password=dict(no_log=True),
            token=dict(no_log=True),
            url=dict(default="http://localhost:8080"),
            user=dict(),
            validate_certs=dict(type='bool', default=True),
        ),
        mutually_exclusive=[
            ['password', 'token'],
            ['name', 'glob'],
        ],
        required_one_of=[
            ['password', 'token'],
        ],
        supports_check_mode=True,
    )
    if module._name == 'jenkins_job_facts':
        module.deprecate(
            "The 'jenkins_job_facts' module has been renamed to 'jenkins_job_info'",
            version='2.13')

    test_dependencies(module)
    jobs = list()

    try:
        jobs = get_jobs(module)
    except jenkins.JenkinsException as err:
        module.fail_json(msg='Unable to connect to Jenkins server, %s' %
                         to_native(err),
                         exception=traceback.format_exc())

    module.exit_json(changed=False, jobs=jobs)
Ejemplo n.º 24
0
    def _podman(self, cmd, cmd_args=None, in_data=None, use_container_id=True):
        """
        run podman executable

        :param cmd: podman's command to execute (str)
        :param cmd_args: list of arguments to pass to the command (list of str/bytes)
        :param in_data: data passed to podman's stdin
        :return: return code, stdout, stderr
        """
        podman_exec = self.get_option('podman_executable')
        podman_cmd = distutils.spawn.find_executable(podman_exec)
        if not podman_cmd:
            raise AnsibleError("%s command not found in PATH" % podman_exec)
        local_cmd = [podman_cmd]
        if self.get_option('podman_extra_args'):
            local_cmd += shlex.split(
                to_native(
                    self.get_option('podman_extra_args'),
                    errors='surrogate_or_strict'))
        local_cmd.append(cmd)
        if use_container_id:
            local_cmd.append(self._container_id)
        if cmd_args:
            local_cmd += cmd_args
        local_cmd = [to_bytes(i, errors='surrogate_or_strict') for i in local_cmd]

        display.vvv("RUN %s" % (local_cmd,), host=self._container_id)
        p = subprocess.Popen(local_cmd, shell=False, stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        stdout, stderr = p.communicate(input=in_data)
        display.vvvvv("STDOUT %s" % stdout)
        display.vvvvv("STDERR %s" % stderr)
        display.vvvvv("RC CODE %s" % p.returncode)
        stdout = to_bytes(stdout, errors='surrogate_or_strict')
        stderr = to_bytes(stderr, errors='surrogate_or_strict')
        return p.returncode, stdout, stderr
Ejemplo n.º 25
0
    def init_swarm(self):
        if not self.force and self.client.check_if_swarm_manager():
            self.__update_swarm()
            return

        if not self.check_mode:
            init_arguments = {
                'advertise_addr': self.parameters.advertise_addr,
                'listen_addr': self.parameters.listen_addr,
                'force_new_cluster': self.force,
                'swarm_spec': self.parameters.spec,
            }
            if self.parameters.default_addr_pool is not None:
                init_arguments[
                    'default_addr_pool'] = self.parameters.default_addr_pool
            if self.parameters.subnet_size is not None:
                init_arguments['subnet_size'] = self.parameters.subnet_size
            try:
                self.client.init_swarm(**init_arguments)
            except APIError as exc:
                self.client.fail("Can not create a new Swarm Cluster: %s" %
                                 to_native(exc))

        if not self.client.check_if_swarm_manager():
            if not self.check_mode:
                self.client.fail("Swarm not created or other error!")

        self.created = True
        self.inspect_swarm()
        self.results['actions'].append("New Swarm cluster created: %s" %
                                       (self.swarm_info.get('ID')))
        self.differences.add('state', parameter='present', active='absent')
        self.results['changed'] = True
        self.results['swarm_facts'] = {
            'JoinTokens': self.swarm_info.get('JoinTokens'),
            'UnlockKey': self.swarm_info.get('UnlockKey')
        }
    def get_adapter(self):
        """
        Return details about the adapter
        :param:
            name : Name of the name of the adapter

        :return: Details about the adapter. None if not found.
        :rtype: dict
        """
        adapter_info = netapp_utils.zapi.NaElement('ucm-adapter-get')
        adapter_info.add_new_child('adapter-name',
                                   self.parameters['adapter_name'])
        adapter_info.add_new_child('node-name', self.parameters['node_name'])
        try:
            result = self.server.invoke_successfully(adapter_info, True)
        except netapp_utils.zapi.NaApiError as error:
            self.module.fail_json(
                msg='Error fetching ucadapter details: %s: %s' %
                (self.parameters['node_name'], to_native(error)),
                exception=traceback.format_exc())
        if result.get_child_by_name('attributes'):
            adapter_attributes = result.get_child_by_name('attributes').\
                get_child_by_name('uc-adapter-info')
            return_value = {
                'mode':
                adapter_attributes.get_child_content('mode'),
                'pending-mode':
                adapter_attributes.get_child_content('pending-mode'),
                'type':
                adapter_attributes.get_child_content('fc4-type'),
                'pending-type':
                adapter_attributes.get_child_content('pending-fc4-type'),
                'status':
                adapter_attributes.get_child_content('status'),
            }
            return return_value
        return None
    def flexcache_get(self):
        """
        Get current FlexCache relations
        :return: Dictionary of current FlexCache details if query successful, else None
        """
        flexcache_get_iter = self.flexcache_get_iter()
        flex_info = dict()
        try:
            result = self.server.invoke_successfully(flexcache_get_iter,
                                                     enable_tunneling=True)
        except netapp_utils.zapi.NaApiError as error:
            self.module.fail_json(msg='Error fetching FlexCache info: %s' %
                                  to_native(error),
                                  exception=traceback.format_exc())
        if result.get_child_by_name('num-records') and \
                int(result.get_child_content('num-records')) == 1:
            flexcache_info = result.get_child_by_name('attributes-list') \
                                   .get_child_by_name('flexcache-info')
            flex_info['origin_cluster'] = flexcache_info.get_child_content(
                'origin-cluster')
            flex_info['origin_volume'] = flexcache_info.get_child_content(
                'origin-volume')
            flex_info['origin_vserver'] = flexcache_info.get_child_content(
                'origin-vserver')
            flex_info['size'] = flexcache_info.get_child_content('size')
            flex_info['volume'] = flexcache_info.get_child_content('volume')
            flex_info['vserver'] = flexcache_info.get_child_content('vserver')
            flex_info['auto_provision_as'] = flexcache_info.get_child_content(
                'auto-provision-as')

            return flex_info
        if result.get_child_by_name('num-records') and \
                int(result.get_child_content('num-records')) > 1:
            msg = 'Multiple records found for %s:' % self.parameters['volume']
            self.module.fail_json(msg='Error fetching FlexCache info: %s' %
                                  msg)
        return None
    def full_login(self):
        if self.auto_login is not None:
            if None in [
                    self.auto_login.get('subdomain'),
                    self.auto_login.get('username'),
                    self.auto_login.get('secret_key'),
                    self.auto_login.get('master_password')
            ]:
                module.fail_json(
                    msg='Unable to perform initial sign in to 1Password. '
                    'subdomain, username, secret_key, and master_password are required to perform initial sign in.'
                )

            args = [
                'signin',
                '{0}.1password.com'.format(self.auto_login['subdomain']),
                to_bytes(self.auto_login['username']),
                to_bytes(self.auto_login['secret_key']),
                '--output=raw',
            ]

            try:
                rc, out, err = self._run(
                    args,
                    command_input=to_bytes(self.auto_login['master_password']))
                self.token = out.strip()
            except AnsibleModuleError as e:
                module.fail_json(
                    msg="Failed to perform initial sign in to 1Password: %s" %
                    to_native(e))
        else:
            module.fail_json(
                msg=
                "Unable to perform an initial sign in to 1Password. Please run '%s sigin' "
                "or define credentials in 'auto_login'. See the module documentation for details."
                % self.cli_path)
Ejemplo n.º 29
0
    def modify_dvs_host(self, operation):
        changed, result = False, None
        spec = vim.DistributedVirtualSwitch.ConfigSpec()
        spec.configVersion = self.dv_switch.config.configVersion
        spec.host = [vim.dvs.HostMember.ConfigSpec()]
        spec.host[0].operation = operation
        spec.host[0].host = self.host
        if self.vendor_specific_config:
            config = list()
            for item in self.vendor_specific_config:
                config.append(
                    vim.dvs.KeyedOpaqueBlob(key=item['key'],
                                            opaqueData=item['value']))
            spec.host[0].vendorSpecificConfig = config

        if operation in ("edit", "add"):
            spec.host[0].backing = vim.dvs.HostMember.PnicBacking()
            count = 0

            for nic in self.vmnics:
                spec.host[0].backing.pnicSpec.append(
                    vim.dvs.HostMember.PnicSpec())
                spec.host[0].backing.pnicSpec[count].pnicDevice = nic
                spec.host[0].backing.pnicSpec[
                    count].uplinkPortgroupKey = self.uplink_portgroup.key
                count += 1

        try:
            task = self.dv_switch.ReconfigureDvs_Task(spec)
            changed, result = wait_for_task(task)
        except vmodl.fault.NotSupported as not_supported:
            self.module.fail_json(
                msg="Failed to configure DVS host %s as it is not"
                " compatible with the VDS version." % self.esxi_hostname,
                details=to_native(not_supported.msg))
        return changed, result
Ejemplo n.º 30
0
def pem_to_der(pem_filename):
    '''
    Load PEM file, and convert to DER.

    If PEM contains multiple entities, the first entity will be used.
    '''
    certificate_lines = []
    try:
        with open(pem_filename, "rt") as f:
            header_line_count = 0
            for line in f:
                if line.startswith('-----'):
                    header_line_count += 1
                    if header_line_count == 2:
                        # If certificate file contains other certs appended
                        # (like intermediate certificates), ignore these.
                        break
                    continue
                certificate_lines.append(line.strip())
    except Exception as err:
        raise ModuleFailException("cannot load PEM file {0}: {1}".format(
            pem_filename, to_native(err)),
                                  exception=traceback.format_exc())
    return base64.b64decode(''.join(certificate_lines))