def export_tech_support_report(idrac, module):
    """
    Export Tech Support Report (TSR)

    Keyword arguments:
    idrac  -- iDRAC handle
    module -- Ansible module
    """

    msg = {}
    msg['changed'] = False
    msg['failed'] = False
    err = False

    try:
        tsr_file_name_format = "%ip_%Y%m%d_%H%M%S_tsr.zip"

        myshare = FileOnShare(remote=module.params['share_name'],
                              isFolder=True)
        myshare.addcreds(
            UserCredentials(module.params['share_user'],
                            module.params['share_pwd']))
        tsr_file_name = myshare.new_file(tsr_file_name_format)

        msg['msg'] = idrac.config_mgr.export_tsr(tsr_file_name)

        if "Status" in msg['msg'] and msg['msg']['Status'] != "Success":
            msg['failed'] = True

    except Exception as e:
        err = True
        msg['msg'] = "Error: %s" % str(e)
        msg['failed'] = True

    return msg, err
def export_lc_logs(idrac, module):
    """
    Export Lifecycle Controller Log to the given file share

    Keyword arguments:
    idrac  -- iDRAC handle
    module -- Ansible module
    """

    msg = {}
    msg['changed'] = False
    msg['failed'] = False
    err = False

    try:
        lclog_file_name_format = "%ip_%Y%m%d_%H%M%S_LC_Log.log"

        myshare = FileOnShare(remote=module.params['share_name'],
                              isFolder=True,
                              creds=UserCredentials(module.params['share_user'],
                                                    module.params['share_pwd']))
        lc_log_file = myshare.new_file(lclog_file_name_format)

        msg['msg'] = idrac.log_mgr.lclog_export(lc_log_file)

        if "Status" in msg['msg'] and msg['msg']['Status'] != "Success":
            msg['failed'] = True

    except Exception as e:
        err = True
        msg['msg'] = "Error: %s" % str(e)
        msg['failed'] = True

    return msg, err
コード例 #3
0
def import_server_config_profile(idrac, module):
    """
    Import Server Configuration Profile from a network share

    Keyword arguments:
    idrac  -- iDRAC handle
    module -- Ansible module
    """

    msg = {}
    msg['changed'] = False
    msg['failed'] = False
    msg['msg'] = {}
    err = False

    try:
        if module.check_mode:
            msg['changed'] = True
        else:
            myshare = FileOnShare(remote=module.params['share_name'],
                                  mount_point=module.params['share_mnt'],
                                  isFolder=True)
            myshare.addcreds(
                UserCredentials(module.params['share_user'],
                                module.params['share_pwd']))
            scp_file_path = myshare.new_file(module.params['scp_file'])

            scp_components = SCPTargetEnum.ALL

            if module.params['scp_components'] == 'IDRAC':
                scp_components = SCPTargetEnum.iDRAC
            elif module.params['scp_components'] == 'BIOS':
                scp_components = SCPTargetEnum.BIOS
            elif module.params['scp_components'] == 'NIC':
                scp_components = SCPTargetEnum.NIC
            elif module.params['scp_components'] == 'RAID':
                scp_components = SCPTargetEnum.RAID

            msg['msg'] = idrac.config_mgr.scp_import(
                scp_share_path=scp_file_path,
                components=scp_components,
                format_file=ExportFormatEnum.XML,
                reboot=module.params['reboot'],
                job_wait=module.params['job_wait'])

            if "Status" in msg['msg']:
                if msg['msg']['Status'] == "Success":
                    msg['changed'] = True
                else:
                    msg['failed'] = True

    except Exception as e:
        err = True
        msg['msg'] = "Error: %s" % str(e)
        msg['failed'] = True

    return msg, err
def export_server_config_profile(idrac, module):
    """
    Export Server Configuration Profile to a network share

    Keyword arguments:
    idrac  -- iDRAC handle
    module -- Ansible module
    """

    msg = {}
    msg['changed'] = False
    msg['failed'] = False
    err = False

    try:
        scp_file_name_format = "%ip_%Y%m%d_%H%M%S_" + \
            module.params['scp_components'] + "_SCP.xml"

        myshare = FileOnShare(remote=module.params['share_name'],
                              isFolder=True)
        myshare.addcreds(
            UserCredentials(module.params['share_user'],
                            module.params['share_pwd']))
        scp_file_name = myshare.new_file(scp_file_name_format)

        scp_components = TypeHelper.convert_to_enum(
            module.params['scp_components'], SCPTargetEnum)

        export_format = ExportFormatEnum.XML
        if module.params['export_format'] == 'JSON':
            export_format = ExportFormatEnum.JSON

        export_method = ExportMethodEnum.Default
        if module.params['export_method'] == 'Clone':
            export_method = ExportMethodEnum.Clone

        msg['msg'] = idrac.config_mgr.scp_export(
            scp_share_path=scp_file_name,
            components=scp_components,
            format_file=export_format,
            method=export_method,
            job_wait=module.params['job_wait'])

        if 'Status' in msg['msg'] and msg['msg']['Status'] != "Success":
            msg['failed'] = True

    except Exception as e:
        err = True
        msg['msg'] = "Error: %s" % str(e)
        msg['failed'] = True

    return msg, err
def update_firmware(idrac, module):
    """Update firmware from a network share and return the job details."""
    msg = {}
    msg['changed'] = False
    msg['update_status'] = {}

    try:
        upd_share = FileOnShare(remote=module.params['share_name'] + "/" +
                                module.params['catalog_file_name'],
                                mount_point=module.params['share_mnt'],
                                isFolder=False,
                                creds=UserCredentials(
                                    module.params['share_user'],
                                    module.params['share_password']))

        idrac.use_redfish = True
        if '12' in idrac.ServerGeneration or '13' in idrac.ServerGeneration:
            idrac.use_redfish = False

        apply_update = True
        msg['update_status'] = idrac.update_mgr.update_from_repo(
            upd_share, apply_update, module.params['reboot'],
            module.params['job_wait'])
    except RuntimeError as e:
        module.fail_json(msg=str(e))

    if "Status" in msg['update_status']:
        if msg['update_status']['Status'] == "Success":
            if module.params['job_wait']:
                msg['changed'] = True
        else:
            module.fail_json(msg='Failed to update firmware.',
                             update_status=msg['update_status'])
    return msg
def run_update_fw_from_nw_share(idrac, module):
    """
    Update firmware from a network share
    Keyword arguments:
    idrac  -- iDRAC handle
    module -- Ansible module
    """

    msg = {}
    msg['changed'] = False
    msg['failed'] = False
    msg['msg'] = {}
    err = False

    try:
        invalid, message = _validate_catalog_file(module.params)
        if invalid:
            err = True
            msg['msg'] = message
            msg['failed'] = True
            return msg, err

        share_name = module.params['share_name']
        if share_name is None:
            share_name = ''
        upd_share = FileOnShare(
            remote="{}{}{}".format(share_name, os.sep,
                                   module.params['catalog_file_name']),
            mount_point=module.params['share_mnt'],
            isFolder=False,
            creds=UserCredentials(module.params['share_user'],
                                  module.params['share_pwd']))

        idrac.use_redfish = True
        if '12' in idrac.ServerGeneration or '13' in idrac.ServerGeneration:
            idrac.use_redfish = False

        # upd_share_file_path = upd_share.new_file("Catalog.xml")

        apply_update = True
        msg['msg'] = idrac.update_mgr.update_from_repo(
            upd_share, apply_update, module.params['reboot'],
            module.params['job_wait'])

        if "Status" in msg['msg']:
            if msg['msg']['Status'] == "Success":
                if module.params['job_wait'] is True:
                    msg['changed'] = True
            else:
                msg['failed'] = True

    except Exception as e:
        err = True
        msg['msg'] = "Error: %s" % str(e)
        msg['failed'] = True

    return msg, err
コード例 #7
0
ファイル: iDRACUpdate.py プロジェクト: kyeagles76/omsdk
 def update_from_repo(self,
                      catalog_path,
                      apply_update=True,
                      reboot_needed=False,
                      job_wait=True):
     if isinstance(catalog_path, str):
         # Catalog name
         updmgr = UpdateManager.get_instance()
         if not updmgr: return {}
         (cache_share, ignore) = updmgr.getCatalogScoper(catalog_path)
     else:
         # DRM Repo
         cache_share = catalog_path
     catalog_dir = FileOnShare(remote=cache_share.remote_folder_path,
                               isFolder=True,
                               creds=cache_share.creds)
     catalog_file = cache_share.remote_file_name
     if self.entity.use_redfish:
         if isinstance(catalog_path,
                       FileOnShare) and catalog_path.mount_point is None:
             raise ValueError("Share path or mount point does not exist")
         rjson = self.entity._update_from_repo_using_redfish(
             ipaddress=catalog_dir.remote_ipaddr,
             share_name=catalog_dir.remote.share_name,
             share_type=IFRShareTypeEnum[
                 catalog_dir.remote_share_type.name.lower()],
             username=catalog_dir.creds.username,
             password=catalog_dir.creds.password,
             reboot_needed=reboot_needed,
             catalog_file=catalog_file,
             apply_update=ApplyUpdateEnum[str(apply_update)],
             ignore_cert_warning=IgnoreCertWarnEnum['On'])
     if TypeHelper.resolve(
             catalog_dir.remote_share_type) == TypeHelper.resolve(
                 ShareTypeEnum.NFS):
         rjson = self.entity._update_repo_nfs(
             share=catalog_dir,
             creds=catalog_dir.creds,
             catalog=catalog_file,
             apply=URLApplyUpdateEnum[str(apply_update)].value,
             reboot=RebootEnum[str(reboot_needed)].value)
     else:
         rjson = self.entity._update_repo(
             share=catalog_dir,
             creds=catalog_dir.creds,
             catalog=catalog_file,
             apply=URLApplyUpdateEnum[str(apply_update)].value,
             reboot=RebootEnum[str(reboot_needed)].value)
     rjson['file'] = str(cache_share)
     if job_wait:
         rjson = self._job_mgr._job_wait(rjson['file'], rjson)
     if not self.entity.use_redfish:
         rjson['job_details'] = self.entity._update_get_repolist()
     return rjson
コード例 #8
0
def boot_to_network_iso(idrac, module):
    """
    Boot to a network ISO image

    Keyword arguments:
    idrac  -- iDRAC handle
    module -- Ansible module
    """

    msg = {}
    msg['changed'] = False
    msg['failed'] = False
    msg['msg'] = {}
    err = False

    try:
        if module.check_mode:
            msg['changed'] = True
        else:
            myshare = FileOnShare(remote=module.params['share_name'],
                                  mount_point=module.params['share_mnt'],
                                  isFolder=True,
                                  creds=UserCredentials(module.params['share_user'],
                                                        module.params['share_pwd']))
            iso_image = myshare.new_file(module.params['iso_image'])

            msg['msg'] = idrac.config_mgr.boot_to_network_iso(iso_image,
                                                              module.params['job_wait'])

            if "Status" in msg['msg']:
                if msg['msg']['Status'] == "Success":
                    msg['changed'] = True
                else:
                    msg['failed'] = True

    except Exception as e:
        err = True
        msg['msg'] = "Error: %s" % str(e)
        msg['failed'] = True

    return msg, err
コード例 #9
0
ファイル: iDRACUpdate.py プロジェクト: qwertzlbert/omsdk
    def update_from_repo(self,
                         catalog_path,
                         apply_update=True,
                         reboot_needed=False,
                         job_wait=True):
        appUpdateLookup = {True: 1, False: 0}
        rebootLookup = {True: "TRUE", False: "FALSE"}
        appUpdate = appUpdateLookup[apply_update]
        rebootNeeded = rebootLookup[reboot_needed]

        if isinstance(catalog_path, str):
            # Catalog name
            updmgr = UpdateManager.get_instance()
            if not updmgr: return {}
            (cache_share, ignore) = updmgr.getCatalogScoper(catalog_path)
        else:
            # DRM Repo
            cache_share = catalog_path
        catalog_dir = FileOnShare(remote=cache_share.remote_folder_path,
                                  isFolder=True,
                                  creds=cache_share.creds)
        catalog_file = cache_share.remote_file_name

        if self.entity.use_redfish:
            if isinstance(catalog_path,
                          FileOnShare) and catalog_path.mount_point is None:
                logger.error("Share path or mount point does not exist")
                raise ValueError("Share path or mount point does not exist")
            return self.update_from_repo_usingscp_redfish(
                catalog_dir,
                catalog_file,
                mount_point=catalog_path.mount_point.full_path,
                reboot_needed=reboot_needed,
                job_wait=job_wait)

        if TypeHelper.resolve(
                catalog_dir.remote_share_type) == TypeHelper.resolve(
                    ShareTypeEnum.NFS):
            rjson = self.entity._update_repo_nfs(share=catalog_dir,
                                                 catalog=catalog_file,
                                                 apply=appUpdate,
                                                 reboot=rebootNeeded)
        else:
            rjson = self.entity._update_repo(share=catalog_dir,
                                             creds=catalog_dir.creds,
                                             catalog=catalog_file,
                                             apply=appUpdate,
                                             reboot=rebootNeeded)

        rjson['file'] = str(cache_share)
        if job_wait:
            rjson = self._job_mgr._job_wait(rjson['file'], rjson)
        return rjson
def run_boot_to_network_iso(idrac, module):
    """
    Boot to a network ISO image
    Keyword arguments:
    idrac  -- iDRAC handle
    module -- Ansible module
    """

    logger.info(module.params['idrac_ip'] +
                ': STARTING: Boot To Network iso Method')
    msg = {}
    msg['changed'] = False
    msg['failed'] = False
    msg['msg'] = {}
    err = False

    try:
        if module.check_mode:
            msg['changed'] = True
        else:
            logger.info(module.params['idrac_ip'] +
                        ': CALLING: File on share OMSDK API')
            myshare = FileOnShare(remote=module.params['share_name'] + "/" +
                                  module.params['iso_image'],
                                  isFolder=False,
                                  creds=UserCredentials(
                                      module.params['share_user'],
                                      module.params['share_pwd']))

            logger.info(module.params['idrac_ip'] +
                        ': FINISHED: File on share OMSDK API')

            msg['msg'] = idrac.config_mgr.boot_to_network_iso(myshare, "")
            logger.info(module.params['idrac_ip'] +
                        ': FINISHED: Boot To Network iso Method:'
                        ' Invoking OMSDK Operating System Deployment API')

            if "Status" in msg['msg']:
                if msg['msg']['Status'] == "Success":
                    msg['changed'] = True
                else:
                    msg['failed'] = True

    except Exception as e:
        logger.error(module.params['idrac_ip'] +
                     ': EXCEPTION: Boot To Network iso Method: ' + str(e))
        err = True
        msg['msg'] = "Error: %s" % str(e)
        msg['failed'] = True

    logger.info(module.params['idrac_ip'] +
                ': FINISHED: Boot To Network iso Method')
    return msg, err
コード例 #11
0
ファイル: iDRACUpdate.py プロジェクト: kyeagles76/omsdk
    def update_from_repo_usingscp_redfish(self,
                                          catalog_dir,
                                          catalog_file,
                                          mount_point,
                                          apply_update=True,
                                          reboot_needed=False,
                                          job_wait=True):
        """Performs firmware update on target server using scp RepositoyUpdate attribute

        :param catalog_dir: object for Folder containing Catalog on share.
        :param catalog_dir: FileOnShare.
        :param catalog_file: Catalog file name
        :param catalog_file: str.
        :param mount_point: local share on which remote(catalog_dir) folder has been mounted
        :param mount_point: str.
        :returns: returns status of firmware update through scp

        """
        (scp_path, scp_file) = self._get_scp_path(catalog_dir)
        myshare = FileOnShare(scp_path).addcreds(catalog_dir.creds)
        # exports only that component which contains RepositoryUpdate attribute
        rjson = self.entity.config_mgr.scp_export(share_path=myshare,
                                                  target='System.Embedded.1')
        if 'Status' not in rjson or rjson['Status'] != 'Success':
            return {
                'Status': 'Failed',
                'Message': 'Export of scp failed for firmware update'
            }
        scpattrval = {'RepositoryUpdate': catalog_file}
        localfile = mount_point.share_path + os.path.sep + scp_file
        self.edit_xml_file(localfile, scpattrval)
        if reboot_needed:
            shutdown = ShutdownTypeEnum.Graceful
        else:
            shutdown = ShutdownTypeEnum.NoReboot
        rjson = self.entity.config_mgr.scp_import(share_path=myshare,
                                                  shutdown_type=shutdown,
                                                  job_wait=job_wait)
        if job_wait:
            rjson['file'] = localfile
            rjson = self._job_mgr._job_wait(rjson['file'], rjson)
        rjson['job_details'] = self.entity._update_get_repolist()
        return rjson
コード例 #12
0
    def setup_nw_share_mount(self):
        results = {}
        try:
            share_name = self.module.params.get('share_name')
            share_user = self.module.params.get('share_user')
            share_pwd  = self.module.params.get('share_pwd')
            share_mnt  = self.module.params.get('share_mnt')

            if share_name and share_user and share_pwd and share_mnt:
                nw_share = FileOnShare(remote=share_name,
                                       mount_point=share_mnt,
                                       isFolder=True,
                                       creds=UserCredentials(share_user, share_pwd))

                if nw_share:
                    return self.handle.config_mgr.set_liason_share(nw_share)
        except Exception as e:
            results['msg'] = "Error: %s" % str(e)
            self.module.fail_json(**results)

        return False
コード例 #13
0
def run_boot_to_network_iso(idrac, module):
    """Boot to a network ISO image"""
    try:
        share_name = module.params['share_name']
        if share_name is None:
            share_name = ''
        share_obj = FileOnShare(
            remote="{0}{1}{2}".format(share_name, os.sep,
                                      module.params['iso_image']),
            isFolder=False,
            creds=UserCredentials(module.params['share_user'],
                                  module.params['share_password']))
        cim_exp_duration = minutes_to_cim_format(
            module, module.params['expose_duration'])
        boot_status = idrac.config_mgr.boot_to_network_iso(
            share_obj, "", expose_duration=cim_exp_duration)
        if not boot_status.get("Status", False) == "Success":
            module.fail_json(msg=boot_status)
    except Exception as e:
        module.fail_json(msg=str(e))
    return boot_status
def run_boot_to_network_iso(idrac, module):
    """
    Boot to a network ISO image
    Keyword arguments:
    idrac  -- iDRAC handle
    module -- Ansible module
    """

    msg = {}
    msg['changed'] = False
    msg['failed'] = False
    msg['msg'] = {}
    err = False

    try:
        share_name = module.params['share_name']
        if share_name is None:
            share_name = ''
        myshare = FileOnShare(remote="{}{}{}".format(share_name, os.sep, module.params['iso_image']),
                              isFolder=False,
                              creds=UserCredentials(
                                  module.params['share_user'],
                                  module.params['share_pwd'])
                              )
        msg['msg'] = idrac.config_mgr.boot_to_network_iso(myshare, "")

        if "Status" in msg['msg']:
            if msg['msg']['Status'] == "Success":
                msg['changed'] = True
            else:
                msg['failed'] = True

    except Exception as e:
        err = True
        msg['msg'] = "Error: %s" % str(e)
        msg['failed'] = True

    return msg, err
コード例 #15
0
    def update_from_repo(self, catalog_path, apply_update = True, reboot_needed = False, job_wait = True):
        appUpdateLookup = { True : 1, False : 0 }
        rebootLookup = { True : "TRUE", False : "FALSE" }
        appUpdate = appUpdateLookup[apply_update]
        rebootNeeded = rebootLookup[reboot_needed]

        if isinstance(catalog_path, str):
            # Catalog name 
            updmgr = UpdateManager.get_instance()
            if not updmgr: return {}
            (cache_share, ignore) = updmgr.getCatalogScoper(catalog_path)
        else:
            # DRM Repo
            cache_share = catalog_path
        catalog_dir = FileOnShare(remote=cache_share.remote_folder_path,
                                  isFolder=True, creds=cache_share.creds)
        catalog_file = cache_share.remote_file_name
        rjson = self.entity._update_repo(share = catalog_dir,
                  creds = catalog_dir.creds, catalog = catalog_file,
                  apply = appUpdate, reboot = rebootNeeded)
        rjson['file'] = str(cache_share)
        if job_wait:
            rjson = self._job_mgr._job_wait(rjson['file'], rjson)
        return rjson
def run_idrac_network_config(idrac, module):
    """
    Get Lifecycle Controller status

    Keyword arguments:
    idrac  -- iDRAC handle
    module -- Ansible module
    """
    logger.info(module.params['idrac_ip'] +
                ': STARTING: iDRAC network configuration method')
    msg = {}
    msg['changed'] = False
    msg['failed'] = False
    msg['msg'] = {}
    err = False

    try:

        idrac.use_redfish = True
        logger.info(module.params['idrac_ip'] +
                    ': CALLING: File on share OMSDK API')
        upd_share = FileOnShare(remote=module.params['share_name'],
                                mount_point=module.params['share_mnt'],
                                isFolder=True,
                                creds=UserCredentials(
                                    module.params['share_user'],
                                    module.params['share_pwd']))
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: File on share OMSDK API')

        logger.info(module.params['idrac_ip'] +
                    ': CALLING: Set liasion share OMSDK API')
        set_liason = idrac.config_mgr.set_liason_share(upd_share)
        if set_liason['Status'] == "Failed":
            try:
                message = set_liason['Data']['Message']
            except (IndexError, KeyError):
                message = set_liason['Message']
            err = True
            msg['msg'] = "{}".format(message)
            msg['failed'] = True
            logger.info(module.params['idrac_ip'] +
                        ': FINISHED: {}'.format(message))
            return msg, err

        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: Set liasion share OMSDK API')

        logger.info(module.params['idrac_ip'] +
                    ': CALLING: Register DNS on iDRAC')

        if module.params['register_idrac_on_dns'] != None:
            idrac.config_mgr.configure_dns(
                register_idrac_on_dns=DNSRegister_NICTypes[
                    module.params['register_idrac_on_dns']])
        if module.params['dns_idrac_name'] != None:
            idrac.config_mgr.configure_dns(
                dns_idrac_name=module.params['dns_idrac_name'])
        if module.params['auto_config'] != None:
            idrac.config_mgr.configure_dns(
                auto_config=DNSDomainNameFromDHCP_NICTypes[
                    module.params['auto_config']])
        if module.params['static_dns'] != None:
            idrac.config_mgr.configure_dns(
                static_dns=module.params['static_dns'])
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: Register DNS on iDRAC')

        logger.info(module.params['idrac_ip'] +
                    ': CALLING: setup iDRAC vlan method')
        if module.params['setup_idrac_nic_vlan'] != None:
            idrac.config_mgr.configure_nic_vlan(
                vlan_enable=VLanEnable_NICTypes[
                    module.params['setup_idrac_nic_vlan']])
        if module.params['vlan_id'] != None:
            idrac.config_mgr.configure_nic_vlan(
                vlan_id=module.params['vlan_id'])
        if module.params['vlan_priority'] != None:
            idrac.config_mgr.configure_nic_vlan(
                vlan_priority=module.params['vlan_priority'])
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: setup iDRAC vlan method')

        logger.info(module.params["idrac_ip"] +
                    ': CALLING: Setup NIC for iDRAC')
        if module.params['enable_nic'] != None:
            idrac.config_mgr.configure_network_settings(
                enable_nic=Enable_NICTypes[module.params['enable_nic']])
        if module.params['nic_selection'] != None:
            idrac.config_mgr.configure_network_settings(
                nic_selection=Selection_NICTypes[
                    module.params['nic_selection']])
        if module.params['failover_network'] != None:
            idrac.config_mgr.configure_network_settings(
                failover_network=Failover_NICTypes[
                    module.params['failover_network']])
        if module.params['auto_detect'] != None:
            idrac.config_mgr.configure_network_settings(
                auto_detect=AutoDetect_NICTypes[module.params['auto_detect']])
        if module.params['auto_negotiation'] != None:
            idrac.config_mgr.configure_network_settings(
                auto_negotiation=Autoneg_NICTypes[
                    module.params['auto_negotiation']])
        if module.params['network_speed'] != None:
            idrac.config_mgr.configure_network_settings(
                network_speed=Speed_NICTypes[module.params['network_speed']])
        if module.params['duplex_mode'] != None:
            idrac.config_mgr.configure_network_settings(
                duplex_mode=Duplex_NICTypes[module.params['duplex_mode']])
        if module.params['nic_mtu'] != None:
            idrac.config_mgr.configure_network_settings(
                nic_mtu=module.params['nic_mtu'])
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: Setup NIC for iDRAC')

        logger.info(module.params['idrac_ip'] +
                    ': CALLING: Setup iDRAC IPv4 Configuration')

        if module.params['enable_dhcp'] != None:
            idrac.config_mgr.configure_ipv4(
                enable_dhcp=DHCPEnable_IPv4Types[module.params["enable_dhcp"]])
        if module.params['ip_address'] != None:
            idrac.config_mgr.configure_ipv4(
                ip_address=module.params["ip_address"])
        if module.params['dns_1'] != None:
            idrac.config_mgr.configure_ipv4(dns_1=module.params["dns_1"])
        if module.params['dns_2'] != None:
            idrac.config_mgr.configure_ipv4(dns_2=module.params["dns_2"])
        if module.params['dns_from_dhcp'] != None:
            idrac.config_mgr.configure_ipv4(
                dns_from_dhcp=DNSFromDHCP_IPv4Types[
                    module.params["dns_from_dhcp"]])
        if module.params['enable_ipv4'] != None:
            idrac.config_mgr.configure_ipv4(
                enable_ipv4=Enable_IPv4Types[module.params["enable_ipv4"]])
        if module.params['gateway'] != None:
            idrac.config_mgr.configure_ipv4(gateway=module.params["gateway"])
        if module.params['net_mask'] != None:
            idrac.config_mgr.configure_ipv4(net_mask=module.params["net_mask"])
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: Setup iDRAC IPv4 configuration')

        logger.info(module.params["idrac_ip"] +
                    ': CALLING: Setup iDRAC IPv4 Static configuration')
        if module.params['static_dns_from_dhcp'] != None:
            idrac.config_mgr.configure_static_ipv4(
                dns_from_dhcp=DNSFromDHCP_IPv4StaticTypes[
                    module.params["static_dns_from_dhcp"]])
        if module.params['static_dns_1'] != None:
            idrac.config_mgr.configure_static_ipv4(
                dns_1=module.params["static_dns_1"])
        if module.params['static_dns_2'] != None:
            idrac.config_mgr.configure_static_ipv4(
                dns_2=module.params["static_dns_2"])
        if module.params['static_gateway'] != None:
            idrac.config_mgr.configure_static_ipv4(
                gateway=module.params["static_gateway"])
        if module.params['static_net_mask'] != None:
            idrac.config_mgr.configure_static_ipv4(
                net_mask=module.params["static_net_mask"])
        logger.info(module.params["idrac_ip"] +
                    ':FINISHED: Setup iDRAC IPv4 Static configuration')

        msg['msg'] = idrac.config_mgr.apply_changes(reboot=False)

        if "Status" in msg['msg']:
            if msg['msg']['Status'] == "Success":
                msg['changed'] = True
                if "Message" in msg['msg']:
                    if msg['msg']['Message'] == "No changes found to commit!":
                        msg['changed'] = False
                    if "No changes were applied" in msg['msg']['Message']:
                        msg['changed'] = False
            else:
                msg['failed'] = True
    except Exception as e:
        err = True
        msg['msg'] = "Error: %s" % str(e)
        msg['failed'] = True
        logger.error(module.params['idrac_ip'] +
                     ': EXCEPTION: iDRAC network configuration method')
    logger.info(module.params['idrac_ip'] +
                ': FINISHED: iDRAC network configuration method')
    return msg, err
def update_firmware(idrac, module):
    """Update firmware from a network share and return the job details."""
    msg = {}
    msg['changed'] = False
    msg['update_msg'] = "Successfully triggered the job to update the firmware."
    try:
        share_name = module.params['share_name']
        catalog_file_name = module.params['catalog_file_name']
        share_user = module.params['share_user']
        share_pwd = module.params['share_password']
        reboot = module.params['reboot']
        job_wait = module.params['job_wait']
        ignore_cert_warning = module.params['ignore_cert_warning']
        apply_update = module.params['apply_update']
        payload = {"RebootNeeded": reboot, "CatalogFile": catalog_file_name, "ApplyUpdate": str(apply_update),
                   "IgnoreCertWarning": CERT_WARN[ignore_cert_warning]}
        if share_user is not None:
            payload['UserName'] = share_user
        if share_pwd is not None:
            payload['Password'] = share_pwd

        firmware_version = re.match(r"^\d.\d{2}", idrac.entityjson['System'][0]['LifecycleControllerVersion']).group()
        idrac.use_redfish = False
        if '14' in idrac.ServerGeneration and float(firmware_version) >= float('3.30'):
            idrac.use_redfish = True
        if share_name.lower().startswith(('http://', 'https://', 'ftp://')):
            msg['update_status'], job_details = update_firmware_url(module, idrac, share_name, catalog_file_name,
                                                                    apply_update, reboot, ignore_cert_warning,
                                                                    job_wait, payload)
            if job_details:
                msg['update_status']['job_details'] = job_details
        else:
            upd_share = FileOnShare(remote="{0}{1}{2}".format(share_name, os.sep, catalog_file_name),
                                    mount_point=module.params['share_mnt'], isFolder=False,
                                    creds=UserCredentials(share_user, share_pwd))
            payload['IPAddress'] = upd_share.remote_ipaddr
            payload['ShareName'] = upd_share.remote.share_name
            payload['ShareType'] = SHARE_TYPE[upd_share.remote_share_type.name.lower()]
            if idrac.use_redfish:
                with iDRACRedfishAPI(module.params) as obj:
                    resp = obj.invoke_request(PATH, method="POST", data=payload)
                    job_id = get_jobid(module, resp)
                    msg['update_status'] = idrac.job_mgr.get_job_status_redfish(job_id)
                    if job_wait:
                        msg['update_status'] = idrac.job_mgr.job_wait(job_id)
                    repo_based_update_list = obj.invoke_request(GET_REPO_BASED_UPDATE_LIST_PATH,
                                                                method="POST", data={})
                    msg['update_status']['job_details'] = eval(repo_based_update_list.read())
            else:
                msg['update_status'] = idrac.update_mgr.update_from_repo(upd_share, apply_update=apply_update,
                                                                         reboot_needed=reboot, job_wait=job_wait)
        json_data, repo_status = msg['update_status']['job_details'], False
        if "PackageList" not in json_data:
            job_data = json_data.get('Data')
            pkglst = job_data['body'] if 'body' in job_data else job_data.get('GetRepoBasedUpdateList_OUTPUT')
            if 'PackageList' in pkglst:
                pkglst['PackageList'], repo_status = _convert_xmltojson(pkglst)
        else:
            json_data['PackageList'], repo_status = _convert_xmltojson(json_data)
    except RuntimeError as e:
        module.fail_json(msg=str(e))
    if "Status" in msg['update_status']:
        if msg['update_status']['Status'] in ["Success", "InProgress"]:
            if module.params['job_wait'] and module.params['apply_update'] and \
                    ('job_details' in msg['update_status'] and repo_status):
                msg['changed'] = True
                msg['update_msg'] = "Successfully updated the firmware."
        else:
            module.fail_json(msg='Failed to update firmware.', update_status=msg['update_status'])
    return msg
コード例 #18
0
from omdrivers.types.iDRAC.BIOS import *
from omdrivers.types.iDRAC.RAID import *
from omdrivers.types.iDRAC.NIC import *
from omdrivers.types.iDRAC.FCHBA import *
from omdrivers.types.iDRAC.SystemConfiguration import *
from omdrivers.lifecycle.iDRAC.SCPParsers import XMLParser
from omsdk.sdkinfra import sdkinfra
from omsdk.simulator.devicesim import Simulator
logging.basicConfig(level=logging.ERROR)
from omsdk.sdkfile import FileOnShare
from omsdk.sdkprint import PrettyPrint
import logging
from omdrivers.lifecycle.iDRAC.RAIDHelper import *

myshare = FileOnShare(remote="\\\\<share>\\Share",
                      mount_point='Z:\\',
                      isFolder=True,
                      creds=UserCredentials("user@domain", "password"))

ipaddr = '192.168.0.1'
logging.basicConfig(level=logging.DEBUG)
myshare.valid = True

Simulator.start_simulating()
sd = sdkinfra()
sd.importPath()
idrac = sd.get_driver('iDRAC', ipaddr, UserCredentials('user', 'pass'))
idrac.config_mgr.set_liason_share(myshare)


def emailtest(idrac, address, expected, action=1):
    print(expected)
コード例 #19
0
if uname:
    creds.add(UserCredentials(uname, upass))
protopref = None
if pref == "WSMAN":
    protopref = ProtoPreference(ProtocolEnum.WSMAN)


@property
def not_implemented():
    print("===== not implemented ====")


if platform.system() == "Windows":
    myshare = FileOnShare(remote=nshare,
                          mount_point='Z:\\',
                          isFolder=True,
                          common_path='',
                          creds=UserCredentials(nsharename, nsharepass))
    updshare = myshare
else:
    myshare = FileOnShare(remote=nshare,
                          mount_point='/tst',
                          isFolder=True,
                          creds=UserCredentials(nsharename, nsharepass))

sd = sdkinfra()
sd.importPath()

UpdateManager.configure(updshare)
#updshare.IsValid
#print(UpdateManager.update_catalog())
コード例 #20
0
ファイル: init_device.py プロジェクト: hunter007VN/omsdk
ipaddr = _get_args('ipaddr')
driver = _get_optional('driver')
uname = _get_optional('user.name')
upass = _get_optional('user.password', '')
pref = _get_optional('protocol', 'WSMAN')
nshare = _get_optional('share')
nsharename = _get_optional('share.user.name')
nsharepass = _get_optional('share.user.password', '')
image = _get_optional('image', '')
creds = ProtocolCredentialsFactory()
if uname :
    creds.add(UserCredentials(uname, upass))

@property
def not_implemented():
    print("===== not implemented ====")


if platform.system() == "Windows":
    liason_share = FileOnShare(remote =nshare,
        mount_point='Z:\\', isFolder=True,
        creds = UserCredentials(nsharename, nsharepass))
else:
    liason_share = FileOnShare(remote =nshare,
        mount_point='/tst', isFolder=True,
        creds = UserCredentials(nsharename, nsharepass))

sd = sdkinfra()
sd.importPath()

def run_idrac_timezone_config(idrac, module):
    """
    Get Lifecycle Controller status

    Keyword arguments:
    idrac  -- iDRAC handle
    module -- Ansible module
    """
    logger.info(module.params['idrac_ip'] +
                ': STARTING: iDRAC timezone configuration method')
    msg = {}
    msg['changed'] = False
    msg['failed'] = False
    msg['msg'] = {}
    err = False

    try:

        idrac.use_redfish = True
        logger.info(module.params['idrac_ip'] +
                    ': CALLING: File on share OMSDK API')
        upd_share = FileOnShare(remote=module.params['share_name'],
                                mount_point=module.params['share_mnt'],
                                isFolder=True,
                                creds=UserCredentials(
                                    module.params['share_user'],
                                    module.params['share_pwd']))
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: File on share OMSDK API')

        logger.info(module.params['idrac_ip'] +
                    ': CALLING: Set liasion share OMSDK API')
        set_liason = idrac.config_mgr.set_liason_share(upd_share)
        if set_liason['Status'] == "Failed":
            try:
                message = set_liason['Data']['Message']
            except (IndexError, KeyError):
                message = set_liason['Message']
            err = True
            msg['msg'] = "{}".format(message)
            msg['failed'] = True
            logger.info(module.params['idrac_ip'] +
                        ': FINISHED: {}'.format(message))
            return msg, err

        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: Set liasion share OMSDK API')
        logger.info(module.params['idrac_ip'] +
                    ': CALLING: setup iDRAC timezone method')
        if module.params['setup_idrac_timezone'] != None:
            idrac.config_mgr.configure_timezone(
                module.params['setup_idrac_timezone'])
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: setup iDRAC timezone method')

        logger.info(module.params['idrac_ip'] +
                    ': CALLING: Setup iDRAC NTP Configuration')

        if module.params['enable_ntp'] != None:
            idrac.config_mgr.configure_ntp(
                enable_ntp=NTPEnable_NTPConfigGroupTypes[
                    module.params['enable_ntp']])
        if module.params['ntp_server_1'] != None:
            idrac.config_mgr.configure_ntp(
                ntp_server_1=module.params['ntp_server_1'])
        if module.params['ntp_server_2'] != None:
            idrac.config_mgr.configure_ntp(
                ntp_server_2=module.params['ntp_server_2'])
        if module.params['ntp_server_3'] != None:
            idrac.config_mgr.configure_ntp(
                ntp_server_3=module.params['ntp_server_3'])
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: Setup iDRAC NTP Configuration')

        msg['msg'] = idrac.config_mgr.apply_changes(reboot=False)

        if "Status" in msg['msg']:
            if msg['msg']['Status'] == "Success":
                msg['changed'] = True
                if "Message" in msg['msg']:
                    if msg['msg']['Message'] == "No changes found to commit!":
                        msg['changed'] = False
            else:
                msg['failed'] = True
    except Exception as e:
        err = True
        msg['msg'] = "Error: %s" % str(e)
        msg['failed'] = True
        logger.error(module.params['idrac_ip'] +
                     ': EXCEPTION: iDRAC timezone configuration method')
    logger.info(module.params['idrac_ip'] +
                ': FINISHED: iDRAC timezone configuration method')
    return msg, err
def run_setup_idrac_syslog(idrac, module):
    """
    Get Lifecycle Controller status

    Keyword arguments:
    idrac  -- iDRAC handle
    module -- Ansible module
    """
    logger.info(module.params['idrac_ip'] +
                ': STARTING: setup iDRAC syslog method')
    msg = {}
    msg['changed'] = False
    msg['failed'] = False
    msg['msg'] = {}
    err = False

    try:

        # idrac.use_redfish = True
        logger.info(module.params['idrac_ip'] +
                    ': CALLING: File on share OMSDK API')
        upd_share = FileOnShare(remote=module.params['share_name'],
                                mount_point=module.params['share_mnt'],
                                isFolder=True,
                                creds=UserCredentials(
                                    module.params['share_user'],
                                    module.params['share_pwd']))
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: File on share OMSDK API')

        logger.info(module.params['idrac_ip'] +
                    ': CALLING: Set liasion share OMSDK API')
        set_liason = idrac.config_mgr.set_liason_share(upd_share)
        if set_liason['Status'] == "Failed":
            try:
                message = set_liason['Data']['Message']
            except (IndexError, KeyError):
                message = set_liason['Message']
            err = True
            msg['msg'] = "{}".format(message)
            msg['failed'] = True
            logger.info(module.params['idrac_ip'] +
                        ': FINISHED: {}'.format(message))
            return msg, err
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: Set liasion share OMSDK API')

        logger.info(module.params['idrac_ip'] +
                    ': CALLING: setup iDRAC syslog OMSDK API')
        if module.params['syslog'] == 'Enabled':
            # Enable Syslog
            msg['msg'] = idrac.config_mgr.enable_syslog()
        elif module.params['syslog'] == 'Disabled':
            # Disable Syslog
            msg['msg'] = idrac.config_mgr.disable_syslog()

        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: setup iDRAC syslog OMSDK API')

        if "Status" in msg['msg']:
            if msg['msg']['Status'] == "Success":
                msg['changed'] = True
                if "Message" in msg['msg']:
                    if msg['msg']['Message'] == "No changes found to commit!":
                        msg['changed'] = False
            else:
                msg['failed'] = True
    except Exception as e:
        err = True
        msg['msg'] = "Error: %s" % str(e)
        msg['failed'] = True
        logger.error(module.params['idrac_ip'] +
                     ': EXCEPTION: setup iDRAC syslog OMSDK API')
    logger.info(module.params['idrac_ip'] +
                ': FINISHED: setup iDRAC syslog Method')
    return msg, err
コード例 #23
0
ファイル: scp_ops.py プロジェクト: hunter007VN/omsdk
image = get_optional(argsinfo, 'image', '')
creds = ProtocolCredentialsFactory()
if uname :
    creds.add(UserCredentials(uname, upass))
protopref = None
if pref == "WSMAN":
    protopref = ProtoPreference(ProtocolEnum.WSMAN)

@property
def not_implemented():
    print("===== not implemented ====")


if platform.system() == "Windows":
    myshare = FileOnShare(remote =nshare,
        mount_point='Z:\\', isFolder=True,
        creds = UserCredentials(nsharename, nsharepass))
    updshare = myshare
else:
    myshare = FileOnShare(remote =nshare,
        mount_point='/tst', isFolder=True,
        creds = UserCredentials(nsharename, nsharepass))
    updshare = myshare

sd = sdkinfra()
sd.importPath()

t1 = time.time()

dprint("Driver SDK", "1.03 Connect to " + ipaddr)
idrac = sd.get_driver(sd.driver_enum.iDRAC, ipaddr, creds, protopref)
def run_server_bios_config(idrac, module):
    """
    Get Lifecycle Controller status

    Keyword arguments:
    idrac  -- iDRAC handle
    module -- Ansible module
    """
    logger.info(module.params['idrac_ip'] +
                ': STARTING: server bios config method')
    msg = {}
    msg['changed'] = False
    msg['failed'] = False
    err = False
    try:

        idrac.use_redfish = True
        logger.info(module.params['idrac_ip'] +
                    ': CALLING: File on share OMSDK API')
        upd_share = FileOnShare(remote=module.params['share_name'],
                                mount_point=module.params['share_mnt'],
                                isFolder=True,
                                creds=UserCredentials(
                                    module.params['share_user'],
                                    module.params['share_pwd']))
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: File on share OMSDK API')

        logger.info(module.params['idrac_ip'] +
                    ': CALLING: Set liasion share OMSDK API')
        set_liason = idrac.config_mgr.set_liason_share(upd_share)
        if set_liason['Status'] == "Failed":
            try:
                message = set_liason['Data']['Message']
            except (IndexError, KeyError):
                message = set_liason['Message']
            err = True
            msg['msg'] = "{}".format(message)
            msg['failed'] = True
            logger.info(module.params['idrac_ip'] +
                        ': FINISHED: {}'.format(message))
            return msg, err

        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: Set liasion share OMSDK API')

        logger.info(module.params['idrac_ip'] +
                    ': CALLING: server bios config OMSDK API')

        if module.params['boot_mode']:
            logger.info(module.params['idrac_ip'] +
                        ': CALLING: server bios Boot mode OMSDK API')
            idrac.config_mgr.configure_boot_mode(
                boot_mode=BootModeTypes[module.params['boot_mode']])

        if module.params['nvme_mode']:
            logger.info(module.params['idrac_ip'] +
                        ': CALLING: server bios nvme mode OMSDK API')
            idrac.config_mgr.configure_nvme_mode(
                nvme_mode=NvmeModeTypes[module.params['nvme_mode']])

        if module.params['secure_boot_mode']:
            logger.info(module.params['idrac_ip'] +
                        ': CALLING: server bios secure boot OMSDK API')
            idrac.config_mgr.configure_secure_boot_mode(
                secure_boot_mode=SecureBootModeTypes[
                    module.params['secure_boot_mode']])

        if module.params['onetime_boot_mode']:
            logger.info(module.params['idrac_ip'] +
                        ': CALLING: server bios one time boot  mode OMSDK API')
            idrac.config_mgr.configure_onetime_boot_mode(
                onetime_boot_mode=OneTimeBootModeTypes[
                    module.params['onetime_boot_mode']])

        if module.params["boot_mode"] != None and module.params[
                "boot_sequence"] != None:
            logger.info(module.params["idrac_ip"] +
                        ': CALLING: Boot sequence configuration OMSDK API')
            idrac.config_mgr.configure_boot_sequence(
                boot_mode=BootModeEnum[module.params['boot_mode']],
                boot_sequence=module.params['boot_sequence'])

        msg['msg'] = idrac.config_mgr.apply_changes(reboot=True)

        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: server bios config OMSDK API')
        if "Status" in msg['msg']:
            if msg['msg']['Status'] == "Success":
                msg['changed'] = True
                if "Message" in msg['msg']:
                    if msg['msg']['Message'] == "No changes found to commit!":
                        msg['changed'] = False
            else:
                msg['failed'] = True
    except Exception as e:
        err = True
        msg['msg'] = "Error: %s" % str(e)
        msg['failed'] = True
        logger.error(module.params['idrac_ip'] +
                     ': EXCEPTION: server bios config OMSDK API')
    logger.info(module.params['idrac_ip'] +
                ': FINISHED: server bios config Method')
    return msg, err
def run_idrac_eventing_config(idrac, module):
    """
    Get Lifecycle Controller status

    Keyword arguments:
    idrac  -- iDRAC handle
    module -- Ansible module
    """
    logger.info(module.params['idrac_ip'] +
                ': STARTING: iDRAC eventing configuration method')
    msg = {}
    msg['changed'] = False
    msg['failed'] = False
    msg['msg'] = {}
    err = False

    try:

        idrac.use_redfish = True
        logger.info(module.params['idrac_ip'] +
                    ': CALLING: File on share OMSDK API')
        upd_share = FileOnShare(remote=module.params['share_name'],
                                mount_point=module.params['share_mnt'],
                                isFolder=True,
                                creds=UserCredentials(
                                    module.params['share_user'],
                                    module.params['share_pwd']))
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: File on share OMSDK API')

        logger.info(module.params['idrac_ip'] +
                    ': CALLING: Set liasion share OMSDK API')
        set_liason = idrac.config_mgr.set_liason_share(upd_share)
        if set_liason['Status'] == "Failed":
            try:
                message = set_liason['Data']['Message']
            except (IndexError, KeyError):
                message = set_liason['Message']
            err = True
            msg['msg'] = "{}".format(message)
            msg['failed'] = True
            logger.info(module.params['idrac_ip'] +
                        ': FINISHED: {}'.format(message))
            return msg, err

        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: Set liasion share OMSDK API')

        logger.info(module.params["idrac_ip"] +
                    ': CALLING: Configure SNMP Trap Destination')

        if module.params["destination_number"] != None:
            if module.params["destination"] != None:
                idrac.config_mgr.configure_snmp_trap_destination(
                    destination=module.params["destination"],
                    destination_number=module.params["destination_number"])
            if module.params["snmp_v3_username"] != None:
                idrac.config_mgr.configure_snmp_trap_destination(
                    snmp_v3_username=module.params["snmp_v3_username"],
                    destination_number=module.params["destination_number"])
            if module.params["snmp_trap_state"] != None:
                idrac.config_mgr.configure_snmp_trap_destination(
                    state=State_SNMPAlertTypes[
                        module.params["snmp_trap_state"]],
                    destination_number=module.params["destination_number"])

        logger.info(module.params["idrac_ip"] +
                    ': FINISHED: Configure SNMP Trap Destination')

        logger.info(module.params['idrac_ip'] +
                    ': CALLING: Configure email alerts')
        if module.params["alert_number"] != None:
            if module.params["email_alert_state"] != None:
                idrac.config_mgr.configure_email_alerts(
                    state=Enable_EmailAlertTypes[
                        module.params["email_alert_state"]],
                    alert_number=module.params["alert_number"])
            if module.params["address"] != None:
                idrac.config_mgr.configure_email_alerts(
                    address=module.params["address"],
                    alert_number=module.params["alert_number"])
            if module.params["custom_message"] != None:
                idrac.config_mgr.configure_email_alerts(
                    custom_message=module.params["custom_message"],
                    alert_number=module.params["alert_number"])

        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: Configure email alerts')

        logger.info(module.params['idrac_ip'] +
                    ': CALLING: Configure iDRAC Alerts')
        if module.params["enable_alerts"] != None:
            idrac.config_mgr.configure_idrac_alerts(
                enable_alerts=AlertEnable_IPMILanTypes[
                    module.params["enable_alerts"]], )
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: Configure iDRAC Alerts')

        logger.info(module.params['idrac_ip'] +
                    ': CALLING: Setup iDRAC SMTP authentication')

        if module.params['authentication'] != None:
            idrac.config_mgr.configure_smtp_server_settings(
                authentication=SMTPAuthentication_RemoteHostsTypes[
                    module.params['authentication']])
        if module.params['smtp_ip_address'] != None:
            idrac.config_mgr.configure_smtp_server_settings(
                smtp_ip_address=module.params['smtp_ip_address'])
        if module.params['smtp_port'] != None:
            idrac.config_mgr.configure_smtp_server_settings(
                smtp_port=module.params['smtp_port'])
        if module.params['username'] != None:
            idrac.config_mgr.configure_smtp_server_settings(
                username=module.params['username'])
        if module.params['password'] != None:
            idrac.config_mgr.configure_smtp_server_settings(
                password=module.params['password'])
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: Setup iDRAC SMTP authentication')

        msg['msg'] = idrac.config_mgr.apply_changes(reboot=False)

        if "Status" in msg['msg']:
            if msg['msg']['Status'] == "Success":
                msg['changed'] = True
                if "Message" in msg['msg']:
                    if msg['msg']['Message'] == "No changes found to commit!":
                        msg['changed'] = False
                    if "No changes were applied" in msg['msg']['Message']:
                        msg['changed'] = False
            else:
                msg['failed'] = True
    except Exception as e:
        err = True
        msg['msg'] = "Error: %s" % str(e)
        msg['failed'] = True
        logger.error(module.params['idrac_ip'] +
                     ': EXCEPTION: iDRAC eventing configuration method')
    logger.info(module.params['idrac_ip'] +
                ': FINISHED: iDRAC eventing configuration method')
    return msg, err
コード例 #26
0
def update_firmware_omsdk(idrac, module):
    """Update firmware from a network share and return the job details."""
    msg = {}
    msg['changed'], msg['failed'], msg['update_status'] = False, False, {}
    msg['update_msg'] = "Successfully triggered the job to update the firmware."
    try:
        share_name = module.params['share_name']
        catalog_file_name = module.params['catalog_file_name']
        share_user = module.params['share_user']
        share_pwd = module.params['share_password']
        reboot = module.params['reboot']
        job_wait = module.params['job_wait']
        ignore_cert_warning = module.params['ignore_cert_warning']
        apply_update = module.params['apply_update']
        payload = {
            "RebootNeeded": reboot,
            "CatalogFile": catalog_file_name,
            "ApplyUpdate": str(apply_update),
            "IgnoreCertWarning": CERT_WARN[ignore_cert_warning]
        }
        if share_user is not None:
            payload['UserName'] = share_user
        if share_pwd is not None:
            payload['Password'] = share_pwd

        if share_name.lower().startswith(('http://', 'https://', 'ftp://')):
            msg['update_status'], job_details = update_firmware_url_omsdk(
                module, idrac, share_name, catalog_file_name, apply_update,
                reboot, ignore_cert_warning, job_wait, payload)
            if job_details:
                msg['update_status']['job_details'] = job_details
        else:
            upd_share = FileOnShare(
                remote="{0}{1}{2}".format(share_name, os.sep,
                                          catalog_file_name),
                mount_point=module.params['share_mnt'],
                isFolder=False,
                creds=UserCredentials(share_user, share_pwd))
            msg['update_status'] = idrac.update_mgr.update_from_repo(
                upd_share,
                apply_update=apply_update,
                reboot_needed=reboot,
                job_wait=job_wait)
            get_check_mode_status(msg['update_status'], module)

        json_data, repo_status, failed = msg['update_status'][
            'job_details'], False, False
        if "PackageList" not in json_data:
            job_data = json_data.get('Data')
            pkglst = job_data['body'] if 'body' in job_data else job_data.get(
                'GetRepoBasedUpdateList_OUTPUT')
            if 'PackageList' in pkglst:  # Returns from OMSDK
                pkglst[
                    'PackageList'], repo_status, failed = _convert_xmltojson(
                        module, pkglst, idrac)
        else:  # Redfish
            json_data['PackageList'], repo_status, failed = _convert_xmltojson(
                module, json_data, None)

        if not apply_update and not failed:
            msg['update_msg'] = "Successfully fetched the applicable firmware update package list."
        elif apply_update and not reboot and not job_wait and not failed:
            msg['update_msg'] = "Successfully triggered the job to stage the firmware."
        elif apply_update and job_wait and not reboot and not failed:
            msg['update_msg'] = "Successfully staged the applicable firmware update packages."
            msg['changed'] = True
        elif apply_update and job_wait and not reboot and failed:
            msg['update_msg'] = "Successfully staged the applicable firmware update packages with error(s)."
            msg['failed'] = True

    except RuntimeError as e:
        module.fail_json(msg=str(e))

    if module.check_mode and not (json_data.get('PackageList') or json_data.get('Data')) and \
            msg['update_status']['JobStatus'] == 'Completed':
        module.exit_json(msg="No changes found to commit!")
    elif module.check_mode and (json_data.get('PackageList') or json_data.get('Data')) and \
            msg['update_status']['JobStatus'] == 'Completed':
        module.exit_json(msg="Changes found to commit!",
                         changed=True,
                         update_status=msg['update_status'])
    elif module.check_mode and not msg['update_status'][
            'JobStatus'] == 'Completed':
        msg['update_status'].pop('job_details')
        module.fail_json(
            msg="Unable to complete the firmware repository download.",
            update_status=msg['update_status'])
    elif not module.check_mode and "Status" in msg['update_status']:
        if msg['update_status']['Status'] in ["Success", "InProgress"]:
            if module.params['job_wait'] and module.params[
                    'apply_update'] and module.params['reboot'] and (
                        'job_details' in msg['update_status']
                        and repo_status) and not failed:
                msg['changed'] = True
                msg['update_msg'] = "Successfully updated the firmware."
            elif module.params['job_wait'] and module.params[
                    'apply_update'] and module.params['reboot'] and (
                        'job_details' in msg['update_status']
                        and repo_status) and failed:
                msg['failed'], msg['changed'] = True, False
                msg['update_msg'] = "Firmware update failed."
        else:
            failed_msg = "Firmware update failed."
            if not apply_update:
                failed_msg = "Unable to complete the repository update."
            module.fail_json(msg=failed_msg,
                             update_status=msg['update_status'])
    return msg
コード例 #27
0
def run_update_fw_from_nw_share(idrac, module):
    """
    Update firmware from a network share
    Keyword arguments:
    idrac  -- iDRAC handle
    module -- Ansible module
    """

    logger.info(module.params['idrac_ip'] + ': STARTING: Update Firmware From Network Share Method')
    msg = {}
    msg['changed'] = False
    msg['failed'] = False
    msg['msg'] = {}
    err = False

    try:
        if module.check_mode:
            msg['changed'] = True
        else:

            logger.info(module.params['idrac_ip'] + ': CALLING: File on share OMSDK API')
            upd_share = FileOnShare(remote=module.params['share_name'] + "/Catalog.xml",
                                    mount_point=module.params['share_mnt'],
                                    isFolder=False,
                                    creds=UserCredentials(
                                        module.params['share_user'],
                                        module.params['share_pwd'])
                                    )
            logger.info(module.params['idrac_ip'] + ': FINISHED: File on share OMSDK API')

            idrac.use_redfish = True
            if '12' in idrac.ServerGeneration or '13' in idrac.ServerGeneration:
                idrac.use_redfish = False

            # upd_share_file_path = upd_share.new_file("Catalog.xml")

            apply_update = True
            logger.info(module.params['idrac_ip'] + ': STARTING: Update Firmware From Network Share Method:'
                                                    ' Invoking OMSDK Firmware update API')
            msg['msg'] = idrac.update_mgr.update_from_repo(upd_share,
                                                           apply_update,
                                                           module.params['reboot'],
                                                           module.params['job_wait'])

            logger.info(module.params['idrac_ip'] + ': FINISHED: Update Firmware From Network Share Method:'
                                                    ' Invoking OMSDK Firmware update API')
            if "Status" in msg['msg']:
                if msg['msg']['Status'] == "Success":
                    if module.params['job_wait'] == True:
                        msg['changed'] = True
                else:
                    msg['failed'] = True

    except Exception as e:
        logger.error(module.params['idrac_ip'] + ': EXCEPTION: Update Firmware From Network Share Method: ' + str(e))
        err = True
        msg['msg'] = "Error: %s" % str(e)
        msg['failed'] = True

    logger.info(module.params['idrac_ip'] + ': FINISHED: Update Firmware From Network Share Method')
    return msg, err
def run_idrac_services_config(idrac, module):
    """
    Get Lifecycle Controller status

    Keyword arguments:
    idrac  -- iDRAC handle
    module -- Ansible module
    """
    logger.info(module.params['idrac_ip'] +
                ': STARTING: iDRAC services configuration method')
    msg = {}
    msg['changed'] = False
    msg['failed'] = False
    msg['msg'] = {}
    err = False

    try:

        idrac.use_redfish = True
        logger.info(module.params['idrac_ip'] +
                    ': CALLING: File on share OMSDK API')
        upd_share = FileOnShare(remote=module.params['share_name'],
                                mount_point=module.params['share_mnt'],
                                isFolder=True,
                                creds=UserCredentials(
                                    module.params['share_user'],
                                    module.params['share_pwd']))
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: File on share OMSDK API')

        logger.info(module.params['idrac_ip'] +
                    ': CALLING: Set liasion share OMSDK API')
        set_liason = idrac.config_mgr.set_liason_share(upd_share)
        if set_liason['Status'] == "Failed":
            try:
                message = set_liason['Data']['Message']
            except (IndexError, KeyError):
                message = set_liason['Message']
            err = True
            msg['msg'] = "{}".format(message)
            msg['failed'] = True
            logger.info(module.params['idrac_ip'] +
                        ': FINISHED: {}'.format(message))
            return msg, err

        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: Set liasion share OMSDK API')

        logger.info(module.params['idrac_ip'] +
                    ': CALLING: Setup iDRAC Webserver Configuration')

        if module.params['enable_web_server'] != None:
            idrac.config_mgr.configure_web_server(
                enable_web_server=Enable_WebServerTypes[
                    module.params['enable_web_server']])
        if module.params['http_port'] != None:
            idrac.config_mgr.configure_web_server(
                http_port=module.params['http_port'])
        if module.params['https_port'] != None:
            idrac.config_mgr.configure_web_server(
                https_port=module.params['https_port'])
        if module.params['timeout'] != None:
            idrac.config_mgr.configure_web_server(
                timeout=module.params['timeout'])
        if module.params['ssl_encryption'] != None:
            idrac.config_mgr.configure_web_server(
                ssl_encryption=SSLEncryptionBitLength_WebServerTypes[
                    module.params['ssl_encryption']])
        if module.params['tls_protocol'] != None:
            idrac.config_mgr.configure_web_server(
                tls_protocol=TLSProtocol_WebServerTypes[
                    module.params['tls_protocol']])
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: Setup iDRAC Webserver Configuration')

        logger.info(module.params['idrac_ip'] +
                    ': CALLING: Setup SNMP for iDRAC')
        if module.params['snmp_enable'] != None:
            idrac.config_mgr.configure_snmp(snmp_enable=AgentEnable_SNMPTypes[
                module.params['snmp_enable']])
        if module.params['community_name'] != None:
            idrac.config_mgr.configure_snmp(
                community_name=module.params['community_name'])
        if module.params['snmp_protocol'] != None:
            idrac.config_mgr.configure_snmp(
                snmp_protocol=SNMPProtocol_SNMPTypes[
                    module.params['snmp_protocol']])
        if module.params['alert_port'] != None:
            idrac.config_mgr.configure_snmp(
                alert_port=module.params['alert_port'])
        if module.params['discovery_port'] != None:
            idrac.config_mgr.configure_snmp(
                discovery_port=module.params['discovery_port'])
        if module.params['trap_format'] != None:
            idrac.config_mgr.configure_snmp(
                trap_format=module.params['trap_format'])
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: Setup SNMP for iDRAC')

        msg['msg'] = idrac.config_mgr.apply_changes(reboot=False)

        if "Status" in msg['msg']:
            if msg['msg']['Status'] == "Success":
                msg['changed'] = True
                if "Message" in msg['msg']:
                    if msg['msg']['Message'] == "No changes found to commit!":
                        msg['changed'] = False
            else:
                msg['failed'] = True
    except Exception as e:
        err = True
        msg['msg'] = "Error: %s" % str(e)
        msg['failed'] = True
        logger.error(module.params['idrac_ip'] +
                     ': EXCEPTION: iDRAC services configuration method')
    logger.info(module.params['idrac_ip'] +
                ': FINISHED: iDRAC services configuration method')
    return msg, err
def run_server_raid_config(idrac, module):
    """
    Get Lifecycle Controller status

    Keyword arguments:
    idrac  -- iDRAC handle
    module -- Ansible module
    """
    logger.info(module.params['idrac_ip'] + ': STARTING: Raid config method')
    msg = {}
    msg['changed'] = False
    msg['failed'] = False
    err = False
    try:

        idrac.use_redfish = True
        logger.info(module.params['idrac_ip'] +
                    ': CALLING: File on share OMSDK API')
        upd_share = FileOnShare(remote=module.params['share_name'],
                                mount_point=module.params['share_mnt'],
                                isFolder=True,
                                creds=UserCredentials(
                                    module.params['share_user'],
                                    module.params['share_pwd']))
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: File on share OMSDK API')

        logger.info(module.params['idrac_ip'] +
                    ': CALLING: Set liasion share OMSDK API')
        set_liason = idrac.config_mgr.set_liason_share(upd_share)
        if set_liason['Status'] == "Failed":
            try:
                message = set_liason['Data']['Message']
            except (IndexError, KeyError):
                message = set_liason['Message']
            err = True
            msg['msg'] = "{}".format(message)
            msg['failed'] = True
            logger.info(module.params['idrac_ip'] +
                        ': FINISHED: {}'.format(message))
            return msg, err
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: Set liasion share OMSDK API')

        if module.params['state'] == "present":
            # Create VD
            logger.info(
                module.params['idrac_ip'] +
                ': CALLING: Raid config : Create virtual disk  OMSDK API')

            # Physical Disk filter
            pd_filter = '((disk.parent.parent is Controller and disk.parent.parent.FQDD._value == "{0}")'.format(
                module.params['controller_fqdd'])
            pd_filter += ' or (disk.parent is Controller and disk.parent.FQDD._value == "{0}"))'.format(
                module.params['controller_fqdd'])
            pd_filter += ' and disk.MediaType == "{0}"'.format(
                module.params['media_type'])
            pd_filter += ' and disk.BusProtocol == "{0}"'.format(
                module.params['bus_protocol'])

            msg['msg'] = idrac.config_mgr.RaidHelper.new_virtual_disk(
                # VirtualDisk parameters
                Name=module.params['vd_name'],
                SpanDepth=module.params['span_depth'],
                SpanLength=module.params['span_length'],
                NumberDedicatedHotSpare=module.
                params['number_dedicated_hot_spare'],
                NumberGlobalHotSpare=module.params['number_global_hot_spare'],
                RAIDTypes=module.params['raid_level'],
                DiskCachePolicy=module.params['disk_cache_policy'],
                RAIDdefaultWritePolicy=module.params['write_cache_policy'],
                RAIDdefaultReadPolicy=module.params['read_cache_policy'],
                StripeSize=module.params['stripe_size'],
                RAIDforeignConfig="Clear",
                RAIDaction=RAIDactionTypes.Create,
                PhysicalDiskFilter=pd_filter)
            logger.info(
                module.params['idrac_ip'] +
                ': FINISHED: Raid config : Create virtual disk  OMSDK API')

        if module.params['state'] == "absent":
            # Remove VD
            logger.info(
                module.params['idrac_ip'] +
                ': CALLING: Raid config : Remove virtual disk  OMSDK API')
            if module.params['vd_name'] == None:
                message = 'Virtual disk name is a required parameter for remove virtual disk operations.'
                err = True
                msg['msg'] = "{}".format(message)
                msg['failed'] = True
                logger.info(module.params['idrac_ip'] +
                            ': FINISHED: {}'.format(message))
                return msg, err
            msg['msg'] = idrac.config_mgr.RaidHelper.delete_virtual_disk(
                Name=module.params['vd_name'])
            logger.info(
                module.params['idrac_ip'] +
                ': FINISHED: Raid config : Remove virtual disk  OMSDK API')
        if "Status" in msg['msg']:
            if msg['msg']['Status'] == "Success":
                msg['changed'] = True
                if "Message" in msg['msg']:
                    if msg['msg']['Message'] == "No changes found to commit!":
                        msg['changed'] = False
            else:
                msg['failed'] = True
    except Exception as e:
        err = True
        msg['msg'] = "Error: %s" % str(e)
        msg['failed'] = True
        logger.error(module.params['idrac_ip'] +
                     ': EXCEPTION: Raid config OMSDK API')
    logger.info(module.params['idrac_ip'] + ': FINISHED: Raid config Method')
    return msg, err
コード例 #30
0
def run_idrac_users_config(idrac, module):
    """
    Get Lifecycle Controller status
    Keyword arguments:
    idrac  -- iDRAC handle
    module -- Ansible module
    """
    logger.info(module.params['idrac_ip'] +
                ': STARTING: iDRAC users configuration method')
    msg = {}
    msg['changed'] = False
    msg['failed'] = False
    msg['msg'] = {}
    err = False

    try:

        idrac.use_redfish = True
        logger.info(module.params['idrac_ip'] +
                    ': CALLING: File on share OMSDK API')
        upd_share = FileOnShare(remote=module.params['share_name'],
                                mount_point=module.params['share_mnt'],
                                isFolder=True,
                                creds=UserCredentials(
                                    module.params['share_user'],
                                    module.params['share_pwd']))
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: File on share OMSDK API')

        logger.info(module.params['idrac_ip'] +
                    ': CALLING: Set liasion share OMSDK API')
        set_liason = idrac.config_mgr.set_liason_share(upd_share)
        if set_liason['Status'] == "Failed":
            try:
                message = set_liason['Data']['Message']
            except (IndexError, KeyError):
                message = set_liason['Message']
            err = True
            msg['msg'] = "{}".format(message)
            msg['failed'] = True
            logger.info(module.params['idrac_ip'] +
                        ': FINISHED: {}'.format(message))
            return msg, err
        logger.info(module.params['idrac_ip'] +
                    ': FINISHED: Set liasion share OMSDK API')

        enable_users = solenable_users = protocolenable_users = None
        privilege_users = ipmilanprivilege_users = ipmiserialprivilege_users = None
        if module.params['enable_users'] != None:
            enable_users = Enable_UsersTypes[module.params['enable_users']]
        if module.params['solenable_users'] != None:
            solenable_users = SolEnable_UsersTypes[
                module.params['solenable_users']]
        if module.params['protocolenable_users'] != None:
            protocolenable_users = ProtocolEnable_UsersTypes[
                module.params['protocolenable_users']]

        if module.params['privilege_users'] != None:
            privilege_users = Privilege_UsersTypes[
                module.params['privilege_users']]
        if module.params['ipmilanprivilege_users'] != None:
            ipmilanprivilege_users = IpmiLanPrivilege_UsersTypes[
                module.params['ipmilanprivilege_users']]
        if module.params['ipmiserialprivilege_users'] != None:
            ipmiserialprivilege_users = IpmiSerialPrivilege_UsersTypes[
                module.params['ipmiserialprivilege_users']]

        authenticationprotocol_users = privacyprotocol_users = None
        if module.params['authenticationprotocol_users'] != None:
            authenticationprotocol_users = AuthenticationProtocol_UsersTypes[
                module.params['authenticationprotocol_users']]
        if module.params['privacyprotocol_users'] != None:
            privacyprotocol_users = PrivacyProtocol_UsersTypes[
                module.params['privacyprotocol_users']]

        if module.params['action'] == 'create':
            logger.info(module.params['idrac_ip'] +
                        ': CALLING: create iDRAC user method')
            idrac.user_mgr.Users.new(
                UserName_Users=module.params['user_name'],
                Password_Users=module.params['user_password'],
                Privilege_Users=privilege_users,
                IpmiLanPrivilege_Users=ipmilanprivilege_users,
                IpmiSerialPrivilege_Users=ipmiserialprivilege_users,
                Enable_Users=enable_users,
                SolEnable_Users=solenable_users,
                ProtocolEnable_Users=protocolenable_users,
                AuthenticationProtocol_Users=authenticationprotocol_users,
                PrivacyProtocol_Users=privacyprotocol_users)
            logger.info(module.params['idrac_ip'] +
                        ': FINISHED: create iDRAC user method')

        if module.params['action'] == 'modify':
            logger.info(module.params['idrac_ip'] +
                        ': CALLING: modify iDRAC user method')
            user = idrac.config_mgr._sysconfig.iDRAC.Users.find_first(
                UserName_Users=module.params['user_name'])
            if user:
                if module.params['user_password'] is not None:
                    user.Password_Users.set_value(
                        module.params['user_password'])
                if privilege_users is not None:
                    user.Privilege_Users.set_value(privilege_users)
                if ipmilanprivilege_users is not None:
                    user.IpmiLanPrivilege_Users.set_value(
                        ipmilanprivilege_users)
                if ipmiserialprivilege_users is not None:
                    user.IpmiSerialPrivilege_Users.set_value(
                        ipmiserialprivilege_users)
                if enable_users is not None:
                    user.Enable_Users.set_value(enable_users)
                if solenable_users is not None:
                    user.SolEnable_Users.set_value(solenable_users)
                if protocolenable_users is not None:
                    user.ProtocolEnable_Users.set_value(protocolenable_users)
                if authenticationprotocol_users is not None:
                    user.AuthenticationProtocol_Users.set_value(
                        authenticationprotocol_users)
                if privacyprotocol_users is not None:
                    user.PrivacyProtocol_Users.set_value(privacyprotocol_users)
            else:
                message = "User: {} does not exist".format(
                    module.params['user_name'])
                err = True
                msg['msg'] = "{}".format(message)
                msg['failed'] = True
                logger.info(module.params['idrac_ip'] +
                            ': FINISHED: {}'.format(message))
                return msg, err
            logger.info(module.params['idrac_ip'] +
                        ': FINISHED: modify iDRAC user method')

        if module.params['action'] == 'delete':
            logger.info(module.params['idrac_ip'] +
                        ': CALLING: remove iDRAC user method')
            idrac.user_mgr.Users.remove(
                UserName_Users=module.params['user_name'])
            logger.info(module.params['idrac_ip'] +
                        ': FINISHED: remove iDRAC user method')

        msg['msg'] = idrac.config_mgr.apply_changes()

        if "Status" in msg['msg']:
            if msg['msg']['Status'] == "Success":
                msg['changed'] = True
                if "Message" in msg['msg']:
                    if msg['msg']['Message'] == "No changes found to commit!":
                        msg['changed'] = False
            else:
                msg['failed'] = True
    except Exception as e:
        err = True
        msg['msg'] = "Error: %s" % str(e)
        msg['failed'] = True
        logger.error(module.params['idrac_ip'] +
                     ': EXCEPTION: iDRAC users configuration method')
    logger.info(module.params['idrac_ip'] +
                ': FINISHED: iDRAC users configuration method')
    return msg, err