예제 #1
0
    def handle(self, hostname, *args, **options):
        validate_host(hostname)

        logger.info("Powercycling %s via HP iLO. %s", hostname, options)

        username = options.get('login', None) or settings.ILO_USERNAME
        password = options.get('password', None) or settings.ILO_PASSWORD

        ilo = hpilo.Ilo(hostname,
                        login=username,
                        password=password,
                        timeout=options['timeout'])

        power_status = ilo.get_host_power_status()
        logger.debug("Got power status %s for ilo server %s.", power_status, hostname)

        try:
            ilo.reset_server()
            logger.debug("Soft reset of ilo server %s complete.", hostname)
        except Exception as error:
            logger.debug("clean powercycle of ilo server %s failed with error: %s", hostname, error)
            ilo.set_host_power(host_power=False)
            logger.debug("hard shutdown of ilo sever %s complete.", hostname)

            logger.debug("Power is off, waiting %d seconds before turning it back on.", options['delay'])
            time.sleep(options['delay'])

            ilo.set_host_power(host_power=True)

        logger.info("Powercycle of %s completed.", hostname)
예제 #2
0
    def oob_powercycle(self, oob_username=None, oob_password=None):
        oob_return = "Unknown power status"
        ilo = hpilo.Ilo(self.get('oob_ip'), oob_username, oob_password)
        oob_return = ilo.reset_server()

        oob_return = "OK"
        return oob_return
예제 #3
0
def job(ip):
    #time.sleep(interval)
    username = "******"
    password = "******"
    print(ip, username, "password")
    ilo = hpilo.Ilo(ip, username, password)
    b = False
    try:
        print(ip, "start cold boot")
        #ilo.cold_boot_server()
        b = True
        #print(b)
        pass
    except Exception as identifier:
        if (identifier != 'The read operation timed out'):
            b = True
        #print(b)
        pass
    finally:
        if (b):
            print(ip, " cold boot successful")
        else:
            print(ip, " cold boot failed")
        log(ip + " " + ("cold boot successful" if b else "cold boot failed"))
        pass
예제 #4
0
def _login(delay=False, **kwargs):
    """
    Helper function for handling iLO credentials and establishing the connection.
    """
    if all(k in kwargs for k in ('login', 'password', 'hostname')):
        creds = {
            'login': config['login'],
            'password': config['password'],
            'hostname': config['hostname']
        }
    elif 'profile' in kwargs:
        # use the host profile
        profile = __salt__['config.option'](kwargs['profile'])
        creds = {
            'login': profile['login'],
            'password': profile['password'],
            'hostname': profile['hostname'],
        }
    else:
        # Finally use the minion configuration
        creds = {
            'login': __salt__['config.option']('hpilo.login'),
            'password': __salt__['config.option']('hpilo.password'),
            'hostname': __salt__['config.option']('hpilo.hostname'),
        }

    return hpilo.Ilo(**creds, delayed=delay)
예제 #5
0
    def __init__(self, ops, data):
        super().__init__(ops, data)
        global FABRIC_PATCHED

        if not FABRIC_PATCHED:
            Connection.open_orig = Connection.open
            Connection.open = unsafe_open
            FABRIC_PATCHED = True

        # Load configuration
        config = get_config()
        ssh_user = config.get('ssh', 'user', fallback=None)
        ssh_key_file = config.get('ssh', 'ssh_key_file', fallback=None)
        connect_kwargs = {
            'key_filename': ssh_key_file
        } if ssh_key_file else None

        ilo_user = config.get('ilo', 'user', fallback=None)
        ilo_password = config.get('ilo', 'password', fallback=None)

        # Setup SSH connection
        self._connection = Connection(self['name'],
                                      user=ssh_user,
                                      connect_kwargs=connect_kwargs)

        # Setup ILO connection
        ilo_address = self['name'].split('.')
        ilo_address.insert(1, 'ilom')
        ilo_address = '.'.join(ilo_address)
        self._ilo = hpilo.Ilo(ilo_address,
                              login=ilo_user,
                              password=ilo_password)

        self.vms_with_shutdown_policy = []
예제 #6
0
    def __new__(cls, name, bases, attrs):
        attrs['ilos'] = {}
        config = ConfigParser.ConfigParser()
        config.read(os.path.expanduser(os.path.join('~', '.ilo.conf')))
        login = config.get('ilo', 'login')
        password = config.get('ilo', 'password')
        methods = []
        for attr in list(attrs.keys()):
            if attr.startswith('test_') and callable(attrs[attr]):
                attrs['_' + attr] = attrs.pop(attr)
                methods.append(attr[5:])

        for section in config.sections():
            if not section.startswith('test '):
                continue
            key = section.split()[1]
            hostname = config.get(section, 'ilo')
            ilo = hpilo.Ilo(hostname, login, password)
            ilo.firmware_version = firmware_cache[ilo]
            if not ilo.protocol:
                ilo.protocol = hpilo.ILO_RAW if ilo.firmware_version[
                    'management_processor'].lower() in (
                        'ilo', 'ilo2') else hpilo.ILO_HTTP

            ilo.save_response = os.path.join(testroot,
                                             'hpilo_test_debug_output')
            attrs['ilos'][key] = ilo
            for method in methods:
                fname = re.sub('[^a-zA-Z0-9_]', '_',
                               'test_%s_%s' % (key, method))
                attrs[fname] = eval(
                    "lambda self: self._test_%s(self.ilos['%s'])" %
                    (method, key))
        return super(IloTestCaseMeta, cls).__new__(cls, name, bases, attrs)
예제 #7
0
    def get_oob_netmacs(self, oob_username=None, oob_password=None):
        ilo = hpilo.Ilo(self.get('oob_ip'), oob_username, oob_password)
        data = ilo.get_host_data()

        for item in data:
            if 'MAC' in item:
                self.netmac[item['Port']]=item['MAC']
        return self.netmac
예제 #8
0
def get_temp(host,ilo_user,ilo_pass):
	ilo = hpilo.Ilo(host,ilo_user,ilo_pass)
	health = ilo.get_embedded_health()
	#get the current Inlet Ambient temp from the sensor, in Celcius
	temp_c = health['temperature']['01-Inlet Ambient']['currentreading'][0]
	#convert to fahrenheit
	temp_f = int(temp_c) * 9/5 + 32
        return temp_f
예제 #9
0
    def get_the_data_subType(self, dev, type):
        try:
            ipaddress = dev.pluginProps.get('ipaddress', "")
            username = dev.pluginProps.get('username', "")
            password = dev.pluginProps.get('password', "")
            self.logger.debug(u"Connecting to IP " + unicode(ipaddress) +
                              " with username" + unicode(username) +
                              " and password:"******"health":
                health = ilo.get_embedded_health()
                self.process_data(dev, health, type)
            elif type == "fw_version":
                fw_version = ilo.get_fw_version()
                self.process_data(dev, fw_version, type)
            elif type == "poweron":
                timeon = ilo.get_server_power_on_time()
                self.logger.debug("Timeon:" + unicode(timeon))
                self.process_data(dev, timeon, type)
            elif type == "hostdata":
                host_data = ilo.get_host_data()
                self.process_data(dev, host_data, type)
            elif type == "power":
                power_readings = ilo.get_power_readings()
                self.process_data(dev, power_readings, "power")
            elif type == "power_status":
                power_status = ilo.get_host_power_status()
                self.process_data(dev, power_status, "power_status")

            return info

        except hpilo.IloCommunicationError:
            self.logger.exception("Error communicating with HP iLO")
            dev.updateStateOnServer('deviceIsOnline', value=False)
            return None
        except hpilo.IloLoginFailed:
            self.logger.info(
                "Login to iLO failed - check Password Username security settings"
            )
            dev.updateStateOnServer('deviceIsOnline', value=False)
            return None
        except hpilo.IloFeatureNotSupported:
            self.logger.debug("Some Features not supported. Ignored.")
            pass
        except Exception:
            self.logger.exception("Exception Found")
            dev.updateStateOnServer('deviceIsOnline', value=False)
            return None
예제 #10
0
    def oob_powerup(self, oob_username=None, oob_password=None):

        oob_return = "Unknown"
        ilo = hpilo.Ilo(self.get('oob_ip'), oob_username, oob_password)

        oob_return = ilo.set_host_power(host_power=True)
        oob_return = "OK"

        return oob_return
예제 #11
0
def ilo3_128(hostname, login, password, ilo3):
    print('[+] Upgrading ' + hostname + ' to v1.28')
    ilobin = 'ilo3_128.bin'
    ilo = hpilo.Ilo(hostname, login, password)
    ilo.update_rib_firmware(filename='ilobins/' + ilobin,
                            progress=print_progress)
    print('\n[*] Waiting 2 Minutes for iLO to reset before upgrading to ' +
          ilo3)
    time.sleep(120)
    return
예제 #12
0
    def login(self):
        # signal.signal(signal.SIGALRM,self.signal_handler)
        # signal.alarm(10)
        self.ilo = hpilo.Ilo(self.server, self.username, self.password)
        try:
            self.ilo.get_fw_version()
        except Exception as e:
            return {'status': 0, 'msg': e}

        return {'status': 1, 'msg': 'login ok'}
def connect(host, user, pwd):
    if not (host or user or pwd):
        print("Could not connect! Parameters were not all provided")
    ilo = hpilo.Ilo(host,
                    login=user,
                    password=pwd,
                    timeout=120,
                    port=443,
                    protocol=None)
    return ilo
예제 #14
0
    def update(self):
        """Get the latest data from HP ILO."""
        import hpilo

        try:
            self.data = hpilo.Ilo(
                hostname=self._host, login=self._login,
                password=self._password, port=self._port)
        except (hpilo.IloError, hpilo.IloCommunicationError,
                hpilo.IloLoginFailed) as error:
            raise ValueError("Unable to init HP ILO, %s", error)
예제 #15
0
def spp(target, login, password, url, key):
    ilo = hpilo.Ilo(target, login, password)
    print('[+] Applying SPP to ' + target)
    #check if anything mounted get_vm_status(device='CDROM')
    #if not install the key
    try:
        media_state = (ilo.get_vm_status(device='CDROM')['image_inserted'])
        #print media_state
    except:
        ilo.activate_license(key)
        media_state = (ilo.get_vm_status(device='CDROM')['image_inserted'])
        print('[+] iLO Advanced was not present but has been applied to ' +
              target)

    #dismount anything that might already be there eject_virtual_media(device='cdrom')
    if media_state == 'YES':
        ilo.eject_virtual_media(device='cdrom')

    #mount cdrom to url insert_virtual_media(cdrom, url)
    try:
        ilo.insert_virtual_media('cdrom', url)
    except:
        print('******************************')
        print('[-] Could not insert media on ' + target)
        print('******************************')
        return

    #set boot set_vm_status(device='cdrom', boot_option='boot_once', write_protect=True
    try:
        ilo.set_vm_status(device='cdrom',
                          boot_option='boot_once',
                          write_protect=True)
    except:
        print('******************************')
        print('[-] Could not set boot status on ' + target)
        print('******************************')
        return

    #check if server is on get_host_power_status()
    power = ilo.get_host_power_status()
    #print power

    #if off boot server press_pwr_btn()
    if power == 'OFF':
        ilo.press_pwr_btn()
    elif power == 'ON':
        print('[-] ' + target + ' is currently powered on')
        print('    Attempting ACPI shutdown')
        ilo.press_pwr_btn()
        print('[*] Waiting 60 seconds')
        if ilo.get_host_power_status() == 'OFF':
            print('[-] ACPI shutdown unsuccessful')
            print('[!] Forcing cold boot')
            ilo.cold_boot_server()
예제 #16
0
    def get_ilo(self):
        """ Get an instance of hpilo.Ilo() that represents this host.

         Example Usage:
           model_ilo = IloHost(hostname='x', login='******', password='******')
           actual_ilo = model_ilo.get_ilo()
           actual_ilo.get_host_data()

        """
        ilo = hpilo.Ilo(hostname=self.address, login=self.username, password=self.password)
        return ilo
def AddIloUser(args):
    ilo_ip, username, password = args
    ilo = hpilo.Ilo(ilo_ip, username, password)
    ilo.add_user(virtual_media_priv=False,
                 reset_server_priv=False,
                 config_ilo_priv=True,
                 user_login="******",
                 remote_cons_priv=False,
                 admin_priv=False,
                 password="******",
                 user_name="username")
예제 #18
0
def main(hosts):
    parser = argparse.ArgumentParser(description='Do the stuff.')
    parser.add_argument('--os_username',
                        type=str,
                        default=os.environ.get('OS_USERNAME'),
                        help='Ironic username')
    parser.add_argument('--os_tenant',
                        type=str,
                        default=os.environ.get('OS_TENANT_NAME'),
                        help='Ironic tenant name')
    parser.add_argument('--os_password',
                        type=str,
                        default=os.environ.get('OS_PASSWORD'),
                        help='Ironic password')
    parser.add_argument('--os_auth_url',
                        type=str,
                        default=os.environ.get('OS_AUTH_URL'),
                        help='Ironic auth URL')

    args = parser.parse_args()
    if (not args.os_username or not args.os_tenant or not args.os_password
            or not args.os_auth_url):
        print('You must supply all details')
        parser.print_help()
        sys.exit(1)

    ironic = get_ironic_client(args.os_username, args.os_password,
                               args.os_auth_url, args.os_tenant)

    clients = {}

    import jiocloud.enroll
    mac_to_uuid = {}
    for _port in ironic.port.list():
        mac_to_uuid[_port.address.lower()] = _port.uuid

    for host in ironic.node.list():
        node_obj = ironic.node.get(host.uuid)
        if node_obj.properties['cpus'] != 24:
            continue
        iloconn = hpilo.Ilo(node_obj.driver_info['ipmi_address'],
                            node_obj.driver_info['ipmi_username'],
                            node_obj.driver_info['ipmi_password'])
        host_data = jiocloud.enroll.get_host_data(iloconn)
        macs = jiocloud.enroll.extract_macs(
            jiocloud.enroll.extract_net_info(host_data))
        mac = macs['3']
        try:
            if mac not in mac_to_uuid:
                continue
            ironic.port.delete(mac_to_uuid[mac])
        except HTTPServiceUnavailable, e:
            print e
예제 #19
0
def node_status_irs(ilo_ip):
    logger = logging.getLogger("node_status_irs")

    try:
        ilo = hpilo.Ilo(ilo_ip, ilo_username, ilo_password)
        ilo_irs_settings = ilo.get_ers_settings()
        logger.info("NODE_STATUS: checking the status of %s", ilo_ip)
        return json_response(200,
                             status='success',
                             irs_settings=ilo_irs_settings)
    except Exception as err:
        return json_response(500, status='error', ilo_response=str(err))
예제 #20
0
    def get_oob_powerstate(self, oob_username=None, oob_password=None):
        ilo = hpilo.Ilo(self.get('oob_ip'), oob_username, oob_password)
        oob_return = ilo.get_host_power_status()

        # standardize the response

        if "ON" in oob_return:
            oob_return = "ON"

        if "OFF" in oob_return:
            oob_return = "OFF"

        return oob_return
예제 #21
0
def add_user(hostname, ilo_username, ilo_password, username, password):

    ilo = hpilo.Ilo(hostname, ilo_username, ilo_password)

    print('Connected!')
    print username, password

    # add the the user
    ilo.add_user(user_name=username,
                 user_login=username,
                 password=password,
                 admin_priv=True)
    print('Added ', username)
예제 #22
0
def connect_hp_server(host,user,password):
    """
    This function wil make connection to
    HP standalone or blade server by hpilo
    """

    ilo = hpilo.Ilo(host,user,password)
    host_data = ilo.get_host_data()

    server_lst = []
    server = {'name': ilo.get_server_name(), 'product_name':host_data[1]['Product Name'], 'serial':host_data[1]['Serial Number'],'ip_address':ilo.get_network_settings()['ip_address']}
    server_lst.append(server)
    return server_lst
예제 #23
0
def GetIloLogs(args):
    ilo_ip, username, password = args
    ilo = hpilo.Ilo(ilo_ip, username, password)
    iml_logs = ilo.get_server_event_log()
    logfile_url = "/data/hpilo_log/" + ilo_ip
    with open(logfile_url, 'a+') as logfile:
        for iml_log in iml_logs:
            format_log = iml_log['last_update'] + ' ' + ilo_ip + ' ' + iml_log['severity'] + \
                ' ' + iml_log['class'] + ' ' + iml_log['description'] + '\n'
            if not CheckIfExist(logfile_url, format_log):
                logfile.write(format_log)
                with open(newlogfile_url, 'a') as newlog:
                    iml_log['host'] = ilo_ip
                    newlog.write(str(iml_log) + '\n')
예제 #24
0
def ilogo(hostname, login, password, ilo2, ilo3, ilo4):
    # Set the iLo variable
    ilo = hpilo.Ilo(hostname, login, password)

    #Check current iLO version
    try:
        ilo_fw_version = ilo.get_fw_version()
    except:
        print('[-] Cannot connect to ' + hostname)
        return

    ilo_version = ilo_fw_version['management_processor']
    firmware_version = ilo_fw_version['firmware_version']
    print('[*] Checking ' + hostname)
    print('[*] iLO type: ' + ilo_version)
    print('[*] Current firmware: ' + firmware_version)

    checkilo = ilo_version.lower() + '_' + firmware_version.replace(
        '.', '') + '.bin'
    #print (checkilo)

    if checkilo == ilo2 or checkilo == ilo3 or checkilo == ilo4:
        print('[+] Current firmare at target version')
    else:
        print('[-] Firmware will be updated')
        if ilo_version == 'iLO2':
            ilobin = ilo2

        elif ilo_version == 'iLO3':
            # Problems upgrading from versions before 1.28
            # if ilo3 lower than 1.28 detected, force upgrade to 1.28 first
            if float(firmware_version) < 1.28:
                print('[-] Current version too old.')
                print('    ' + hostname +
                      ' MUST upgrade to v1.28 before proceeding')
                ilo3_128(hostname, login, password, ilo3)
            ilobin = ilo3

        elif ilo_version == 'iLO4':
            ilobin = ilo4

        print('[+] Updating ' + hostname)
        try:
            ilo.update_rib_firmware(filename='ilobins/' + ilobin,
                                    progress=print_progress)
        except:
            print('\n[-] An error occured whilst updating ' + hostname)
            print('\n    Please try this host again')
        print('')
예제 #25
0
 def update(self):
     """Get the latest data from HP iLO."""
     try:
         self.data = hpilo.Ilo(
             hostname=self._host,
             login=self._login,
             password=self._password,
             port=self._port,
         )
     except (
         hpilo.IloError,
         hpilo.IloCommunicationError,
         hpilo.IloLoginFailed,
     ) as error:
         raise ValueError(f"Unable to init HP ILO, {error}") from error
예제 #26
0
def del_irs(ilo_ip):
    logger = logging.getLogger("del_irs")
    # Basic validation
    if ilo_ip is None:
        abort(404)
    try:
        ilo = hpilo.Ilo(ilo_ip, ilo_username, ilo_password)
        ilo_disable_ers = ilo.disable_ers()
        logger.info(
            "DEL_IRS: User just disconnected %s node from its IRS instance.",
            ilo_ip)
        return json_response(200,
                             status='success',
                             irs_disable_ers=ilo_disable_ers)
    except Exception as err:
        return json_response(500, status='error', ilo_response=str(err))
예제 #27
0
def main(hosts):
    parser = argparse.ArgumentParser(description='Do the stuff.')
    parser.add_argument('--os_username',
                        type=str,
                        default=os.environ.get('OS_USERNAME'),
                        help='Ironic username')
    parser.add_argument('--os_tenant',
                        type=str,
                        default=os.environ.get('OS_TENANT_NAME'),
                        help='Ironic tenant name')
    parser.add_argument('--os_password',
                        type=str,
                        default=os.environ.get('OS_PASSWORD'),
                        help='Ironic password')
    parser.add_argument('--os_auth_url',
                        type=str,
                        default=os.environ.get('OS_AUTH_URL'),
                        help='Ironic auth URL')

    args = parser.parse_args()
    if (not args.os_username or not args.os_tenant or not args.os_password
            or not args.os_auth_url):
        print('You must supply all details')
        parser.print_help()
        sys.exit(1)

    ironic = get_ironic_client(args.os_username, args.os_password,
                               args.os_auth_url, args.os_tenant)

    clients = {}

    import jiocloud.enroll
    for host in ironic.node.list():
        node_obj = ironic.node.get(host.uuid)
        if node_obj.properties['cpus'] != 24:
            continue
        iloconn = hpilo.Ilo(node_obj.driver_info['ipmi_address'],
                            node_obj.driver_info['ipmi_username'],
                            node_obj.driver_info['ipmi_password'])
        host_data = jiocloud.enroll.get_host_data(iloconn)
        macs = jiocloud.enroll.extract_macs(
            jiocloud.enroll.extract_net_info(host_data))
        for idx in '3 4'.split(' '):
            try:
                ironic.port.create(address=macs[idx], node_uuid=host.uuid)
            except HTTPConflict, e:
                print e
def main(hosts):
    parser = argparse.ArgumentParser(description='Do the stuff.')
    parser.add_argument('--os_username',
                        type=str,
                        default=os.environ.get('OS_USERNAME'),
                        help='Ironic username')
    parser.add_argument('--os_tenant',
                        type=str,
                        default=os.environ.get('OS_TENANT_NAME'),
                        help='Ironic tenant name')
    parser.add_argument('--os_password',
                        type=str,
                        default=os.environ.get('OS_PASSWORD'),
                        help='Ironic password')
    parser.add_argument('--os_auth_url',
                        type=str,
                        default=os.environ.get('OS_AUTH_URL'),
                        help='Ironic auth URL')

    args = parser.parse_args()
    if (not args.os_username or not args.os_tenant or not args.os_password
            or not args.os_auth_url):
        print('You must supply all details')
        parser.print_help()
        sys.exit(1)

    ironic = get_ironic_client(args.os_username, args.os_password,
                               args.os_auth_url, args.os_tenant)

    clients = {}

    for host in ironic.node.list():
        node_obj = ironic.node.get(host.uuid)
        client = hpilo.Ilo(node_obj.driver_info['ipmi_address'],
                           node_obj.driver_info['ipmi_username'],
                           node_obj.driver_info['ipmi_password'])
        sn = [
            x for x in client.get_host_data(decoded_only=True)
            if x['type'] == 226
        ][0]['Serial Number'].strip()
        print '%s has serial number %s. Storing that in Ironic.' % (host.uuid,
                                                                    sn)
        ironic.node.update(node_obj.uuid, [{
            'op': 'add',
            'path': '/properties/serial_number',
            'value': sn
        }])
예제 #29
0
def add_irs(ilo_ip):
    logger = logging.getLogger("add_irs")
    data = json.loads(request.data)

    if not 'ers_destination_url' in data:
        abort(400)
    else:
        ers_destination_url = data['ers_destination_url']
        try:
            ilo = hpilo.Ilo(ilo_ip, ilo_username, ilo_password)
            ilo_ers_irs_connect = ilo.set_ers_irs_connect(
                data['ers_destination_url'], ers_destination_port)
            logger.info(
                "ADD_IRS: User just connected %s node to %s IRS instance.",
                ilo_ip, ers_destination_url)
            return json_response(200,
                                 status='success',
                                 ilo_ers_irs_connect=ilo_ers_irs_connect)
        except hpilo.IloError as ilo_error:
            return json_response(500,
                                 status='error',
                                 ilo_response=str(ilo_error))
예제 #30
0
def main():

    module = AnsibleModule(argument_spec=dict(
        host=dict(type='str', required=True),
        login=dict(type='str', default='Administrator'),
        password=dict(type='str', default='admin', no_log=True),
        media=dict(type='str',
                   choices=[
                       'cdrom', 'floppy', 'rbsu', 'hdd', 'network', 'normal',
                       'usb'
                   ]),
        image=dict(type='str'),
        state=dict(type='str',
                   default='boot_once',
                   choices=[
                       'boot_always', 'boot_once', 'connect', 'disconnect',
                       'no_boot', 'poweroff'
                   ]),
        force=dict(type='bool', default=False),
        ssl_version=dict(
            type='str',
            default='TLSv1',
            choices=['SSLv3', 'SSLv23', 'TLSv1', 'TLSv1_1', 'TLSv1_2']),
    ))

    if not HAS_HPILO:
        module.fail_json(msg='The hpilo python module is required')

    host = module.params['host']
    login = module.params['login']
    password = module.params['password']
    media = module.params['media']
    image = module.params['image']
    state = module.params['state']
    force = module.params['force']
    ssl_version = getattr(
        hpilo.ssl, 'PROTOCOL_' +
        module.params.get('ssl_version').upper().replace('V', 'v'))

    ilo = hpilo.Ilo(host,
                    login=login,
                    password=password,
                    ssl_version=ssl_version)
    changed = False
    status = {}
    power_status = 'UNKNOWN'

    if media and state in ('boot_always', 'boot_once', 'connect', 'disconnect',
                           'no_boot'):

        # Workaround for: Error communicating with iLO: Problem manipulating EV
        try:
            ilo.set_one_time_boot(media)
        except hpilo.IloError:
            time.sleep(60)
            ilo.set_one_time_boot(media)

        # TODO: Verify if image URL exists/works
        if image:
            ilo.insert_virtual_media(media, image)
            changed = True

        if media == 'cdrom':
            ilo.set_vm_status('cdrom', state, True)
            status = ilo.get_vm_status()
            changed = True
        elif media in ('floppy', 'usb'):
            ilo.set_vf_status(state, True)
            status = ilo.get_vf_status()
            changed = True

    # Only perform a boot when state is boot_once or boot_always, or in case we want to force a reboot
    if state in ('boot_once', 'boot_always') or force:

        power_status = ilo.get_host_power_status()

        if not force and power_status == 'ON':
            module.fail_json(
                msg=
                'HP iLO (%s) reports that the server is already powered on !' %
                host)

        if power_status == 'ON':
            ilo.warm_boot_server()
            #            ilo.cold_boot_server()
            changed = True
        else:
            ilo.press_pwr_btn()
            #            ilo.reset_server()
            #            ilo.set_host_power(host_power=True)
            changed = True

    elif state in ('poweroff'):

        power_status = ilo.get_host_power_status()

        if not power_status == 'OFF':
            ilo.hold_pwr_btn()
            #            ilo.set_host_power(host_power=False)
            changed = True

    module.exit_json(changed=changed, power=power_status, **status)