def main(): module = AnsibleModule( argument_spec=dict( url=dict(default=None), hostname=dict(default=None), username=dict(default=None), password=dict(default=None, no_log=True), ca_file=dict(default=None, type='path'), insecure=dict(required=False, type='bool', default=None), timeout=dict(required=False, type='int', default=0), compress=dict(required=False, type='bool', default=True), kerberos=dict(required=False, type='bool', default=False), headers=dict(required=False, type='dict'), state=dict(default='present', choices=['present', 'absent']), token=dict(default=None), ovirt_auth=dict(required=None, type='dict'), ), required_if=[ ('state', 'absent', ['ovirt_auth']), ], supports_check_mode=True, ) check_sdk(module) state = module.params.get('state') if state == 'present': params = module.params elif state == 'absent': params = module.params['ovirt_auth'] def get_required_parameter(param, env_var, required=False): var = params.get(param) or os.environ.get(env_var) if not var and required and state == 'present': module.fail_json(msg="'%s' is a required parameter." % param) return var url = get_required_parameter('url', 'OVIRT_URL', required=False) hostname = get_required_parameter('hostname', 'OVIRT_HOSTNAME', required=False) if url is None and hostname is None: module.fail_json(msg="You must specify either 'url' or 'hostname'.") if url is None and hostname is not None: url = 'https://{0}/ovirt-engine/api'.format(hostname) username = get_required_parameter('username', 'OVIRT_USERNAME') password = get_required_parameter('password', 'OVIRT_PASSWORD') token = get_required_parameter('token', 'OVIRT_TOKEN') ca_file = get_required_parameter('ca_file', 'OVIRT_CAFILE') insecure = params.get('insecure') if params.get( 'insecure') is not None else not bool(ca_file) connection = sdk.Connection( url=url, username=username, password=password, ca_file=ca_file, insecure=insecure, timeout=params.get('timeout'), compress=params.get('compress'), kerberos=params.get('kerberos'), headers=params.get('headers'), token=token, ) try: token = connection.authenticate() module.exit_json(changed=False, ansible_facts=dict(ovirt_auth=dict( token=token, url=url, ca_file=ca_file, insecure=insecure, timeout=params.get('timeout'), compress=params.get('compress'), kerberos=params.get('kerberos'), headers=params.get('headers'), ) if state == 'present' else dict())) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: # Close the connection, but don't revoke token connection.close(logout=state == 'absent')
if args.password_file: with open(args.password_file) as f: return f.readline().rstrip('\n') else: return getpass.getpass() args = parse_args() # Create the connection to the server: print("Connecting...") connection = sdk.Connection( url=args.engine_url + '/ovirt-engine/api', username=args.username, password=read_password(args), ca_file=args.cafile, debug=True, log=logging.getLogger(), ) # Get the reference to the root service: system_service = connection.system_service() # Get the reference to the disks service: disks_service = connection.system_service().disks_service() # Find the disk we want to download by the id: disk_service = disks_service.disk_service(args.disk_uuid) disk = disk_service.get() print("Creating a transfer session...")
def verify_manager_connection(manager): connection = sdk.Connection(url=str(manager.url), username=str(manager.username), password=str(manager.password), insecure=True) return connection.test()
# import logging import ovirtsdk4 as sdk import ovirtsdk4.types as types logging.basicConfig(level=logging.DEBUG, filename='example.log') # This example will connect to the server and create a new virtual machine: # Create the connection to the server: connection = sdk.Connection( url='https://engine.localdomain/ovirt-engine/api', username='******', password='******', ca_file='ca.crt', debug=True, log=logging.getLogger(), ) # Get the reference to the "vms" service: vms_service = connection.system_service().vms_service() # Use the "add" method to create a new virtual machine: ovf_file_path = '/data/ovirtbackup/winxp-e55cebcc-f354-4b66-b858-a11e1c647f1a.ovf' ovf_data = open(ovf_file_path, 'r').read() vm = vms_service.add( types.Vm( cluster=types.Cluster(name='Default', ), initialization=types.Initialization(configuration=types.Configuration(
def main(): module = AnsibleModule( argument_spec=dict( url=dict(default=None), username=dict(default=None), password=dict(default=None, no_log=True), ca_file=dict(default=None, type='path'), insecure=dict(required=False, type='bool', default=False), timeout=dict(required=False, type='int', default=0), compress=dict(required=False, type='bool', default=True), kerberos=dict(required=False, type='bool', default=False), headers=dict(required=False, type='dict'), state=dict(default='present', choices=['present', 'absent']), token=dict(default=None), ovirt_auth=dict(required=None, type='dict'), ), required_if=[ ('state', 'absent', ['ovirt_auth']), ], supports_check_mode=True, ) check_sdk(module) state = module.params.get('state') if state == 'present': params = module.params elif state == 'absent': params = module.params['ovirt_auth'] url = params.get('url') or os.environ.get('OVIRT_URL') username = params.get('username') or os.environ.get('OVIRT_USERNAME') password = params.get('password') or os.environ.get('OVIRT_PASSWORD') ca_file = params.get('ca_file') or os.environ.get('OVIRT_CAFILE') insecure = params.get('insecure') or ca_file is None token = params.get('token') or os.environ.get('OVIRT_TOKEN') connection = sdk.Connection( url=url, username=username, password=password, ca_file=ca_file, insecure=insecure, timeout=params.get('timeout'), compress=params.get('compress'), kerberos=params.get('kerberos'), headers=params.get('headers'), token=token, ) try: token = connection.authenticate() module.exit_json(changed=False, ansible_facts=dict(ovirt_auth=dict( token=token, url=url, ca_file=ca_file, insecure=insecure, timeout=params.get('timeout'), compress=params.get('compress'), kerberos=params.get('kerberos'), headers=params.get('headers'), ) if state == 'present' else dict())) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: # Close the connection, but don't revoke token connection.close(logout=state == 'absent')
import configparser import datetime import logging import os import mysql.connector import ovirtsdk4 as sdk logging.basicConfig(level=logging.DEBUG, filename='example.log') config = configparser.ConfigParser(interpolation=None) config.read('/etc/workloadmgr/workloadmgr.conf') rhv_connection = sdk.Connection( url=str(config['ovirt_authtoken']['rhv_auth_url'] + "/api"), username=str(config['ovirt_authtoken']['rhv_username']), password=base64.b85decode( config['ovirt_authtoken']['rhv_password']).decode("utf-8"), insecure=True, ca_file="", ) db_url = config['DEFAULT']['sql_connection'] user = db_url.split("//")[1].split(":")[0] password = db_url.split("@")[0].split(":")[-1] host = db_url.split("@")[1].split("/")[0] database = db_url.split("/")[-1].split("?")[0] mydb = mysql.connector.connect(host=host, user=user, passwd=password, database=database)
url = cfg.get('bkp', 'url') user = cfg.get('bkp', 'user') password = cfg.get('bkp', 'password') ca_file = cfg.get('bkp', 'ca_file') bckdir = cfg.get('bkp', 'bckdir') bkpvm = cfg.get('bkp', 'bkpvm') vmname = sys.argv[2] date = str((time.strftime("%Y-%m-%d-%H"))) vmid = "" snapname = "BACKUP" + "_" + date + "h" try: # Create a connection to the server: connection = sdk.Connection(url=url, username=user, password=password, ca_file=ca_file) printf.OK("Connection to oVIrt API success %s" % url) except Exception as ex: printf.ERROR("Connection to oVirt API has failed") #print "Unexpected error: %s" % ex # Funcion para obtener el id de la vm buscandola por el nombre # Function to get VM_ID from VM name def get_id_vm(vmname): vm_service = connection.service("vms") vms = vm_service.list() for vm in vms: if vm.name == vmname: return vm.id
args = parser.parse_args() VMName = args.VMName SnapName = args.SnapName SnapName = args.SnapName ApiPass = args.ApiPass logging.basicConfig(level=logging.DEBUG, filename='vms_stat.log') log_file = open("log.txt", "w") ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') ##### Создаем подключение connection = sdk.Connection( url='https://ovirt.localhost.ru/ovirt-engine/api', username='******', password=ApiPass, ca_file='cert_ca.crt', debug=True, log=logging.getLogger(), ) system_service = connection.system_service() vms_service = system_service.vms_service() vm = vms_service.list(search=VMName)[0] ## Имя виртуальной машины vm_service = vms_service.vm_service(vm.id) snaps_service = vm_service.snapshots_service() snapshots = snaps_service.list() for snapshot in snapshots: if snapshot.description == SnapName: ## Название снапшота
# # # This script is based on the oVirt sdk example scripts from Red Hat, Inc: # https://github.com/oVirt/ovirt-engine-sdk/tree/master/sdk/examples # from time import sleep import ovirtsdk4 as sdk import ovirtsdk4.types as types connection = sdk.Connection( url='https://example.org/ovirt-engine/api', username='******', password='******', ca_file='/etc/pki/ovirt-engine/ca.pem', debug=True, ) vms_service = connection.system_service().vms_service() vms = vms_service.list() shutdown_list = [] for vm in vms: if vm.status == types.VmStatus.UP: shutdown_list.append(vm.id) service = vms_service.vm_service(vm.id) print("Stopping VM: {}".format(vm.name))
def connect(self): return sdk.Connection(url=self.url, username=self.username, password=self.password, ca_file=self.ca_file, debug=self.debug)
using the Ovirt Python SDK against faked-vdsm """ import logging import time import ovirtsdk4 as sdk import ovirtsdk4.types as types from common import track_status logging.basicConfig(level=logging.DEBUG, filename='test.log') connection = sdk.Connection( url='https://laptop.emesika.com:8443/ovirt-engine/api', username='******', password='******', insecure=True, debug=True, log=logging.getLogger(), ) # Get the reference to the "vms" service: vms_service = connection.system_service().vms_service() def run_vm(pname, wait_for_up): print('Running VM : ' + pname + '...') # Find the virtual machine: vm = vms_service.list(search='name=' + pname)[0] # Locate the service that manages the virtual machine, as that is where # the action methods are defined:
VMComment = "mycomment" VMDescription = "my Description" VMCores = 4 VMSockets = 1 VMCluster = "Default" VMTemplate = "Blank" #VMTemplate = "RH83-Template" VMMemory = 8 * 2**30 VMMemoryGuaranteed = 1 * 2**30 VMCapacity = 64 * 2**30 VMDomain = 'hosted_storage' VMNetwork = 'ovirtmgmt' connection = sdk.Connection( url='https://' + RHVMURL + '/ovirt-engine/api', username=RHVMUser, password=RHVMPass, ca_file='/etc/pki/vdsm/certs/cacert.pem', ) # Get the reference to the "vms" service: vms_service = connection.system_service().vms_service() vm = types.Vm() vm.name = VMName vm.comment = VMComment vm.description = VMDescription cpu = types.CpuTopology(cores=VMCores, sockets=VMSockets) vm.cpu = types.Cpu(topology=cpu) vm.cluster = types.Cluster(name=VMCluster) vm.template = types.Template(name=VMTemplate) vm.os = types.OperatingSystem(boot=types.Boot(devices=[types.BootDevice.HD]),
import logging import time import ovirtsdk4 as sdk import ovirtsdk4.types as types class OVIRT(): def _init_(self) self.logger = logging.getLogger('THOR.PowerCTL.ovirt') def connect(self) connection = sdk.Connection(url, username, password, ca_file) return connection.system_service().vms_service() def stop_vm(self, name, vms_service) vm = vms_service.list(search='name='+ name)[0] vm_service = vms_service.vm_service(vm.id) vm_service.stop() logger.info("VM '%s' turning off" % (name)) connection.close() def start_vm(self, name, vms_service) vm = vms_service.list(search='name='+name)[0] vm_service = vms_service.vm_service(vm.id) vm_service.stop() logger.info("VM '%s' turning on" % (name)) connection.close()
import ConfigParser as configparser except ImportError: import configparser if __name__ == '__main__': config = configparser.ConfigParser() config.read('/root/.ovirtshellrc') url = config.get('ovirt-shell', 'url') username = config.get('ovirt-shell', 'username') password = config.get('ovirt-shell', 'password') # open a connection to the server connection = sdk.Connection(url=url, username=username, password=password, insecure=True, debug=True) # services that manage data and virtual machines system_service = connection.system_service() events_service = system_service.events_service() # use time as unique event id event_id = int(time.time()) # send an event to the system events_service.add(event=types.Event(origin='test-application', severity=types.LogSeverity.NORMAL, custom_id=event_id, description="Authentication test"))
#!/usr/bin/env python # -*- coding: utf-8 -*- import ovirtsdk4 as sdk # set variables engine_url = 'https://host.example.com/ovirt-engine/api' engine_user = '******' engine_password = '******' engine_cafile = 'CA_FILE_PATH' cluster = 'cluster_name' # Create the connection to the server: connection = sdk.Connection( url=engine_url, username=engine_user, password=engine_password, ca_file=engine_cafile ) def get_storage_domain(): storage_domain = None # Create the Clusters Service clusters_service = connection.system_service().clusters_service() # Get the list of Storage Domains for the service that Match the Cluser Name clstr = clusters_service.list(search=f'name={cluster}', max=1, follow='data_center.storage_domains') clstr = clstr[0] for sd in clstr.data_center.storage_domains: if storage_domain is None:
import argparse parser = argparse.ArgumentParser() parser.add_argument("affinitygroup") parser.add_argument("vm_name_search") parser.add_argument("ovirt_url") parser.add_argument("ovirt_username") parser.add_argument("ovirt_password") args = parser.parse_args() print(args) # Create the connection to the server: connection = sdk.Connection( url=args.ovirt_url, username=args.ovirt_username, password=args.ovirt_password, debug=True, log=logging.getLogger(), ) # Locate the clusters service and use it to find the cluster clusters_service = connection.system_service().clusters_service() cluster = clusters_service.list(search='name=default')[0] cluster_service = clusters_service.cluster_service(cluster.id) cluster_affinitygroups_service = cluster_service.affinity_groups_service() cluster_service = clusters_service.cluster_service(cluster.id) cluster_affinitygroups_service = cluster_service.affinity_groups_service() # could create the affinity group?
output_password = fp.read() output_password = output_password.rstrip() # Read the OVF document. with open(sys.argv[2], 'r') as fp: ovf = fp.read() # Parse out the username from the output_conn URL. parsed = urlparse(params['output_conn']) username = parsed.username or "admin@internal" # Connect to the server. connection = sdk.Connection( url=params['output_conn'], username=username, password=output_password, ca_file=params['rhv_cafile'], log=logging.getLogger(), insecure=params['insecure'], ) system_service = connection.system_service() # Get the cluster. cluster = system_service.clusters_service().cluster_service(params['rhv_cluster_uuid']) cluster = cluster.get() vms_service = system_service.vms_service() vm = vms_service.add( types.Vm( cluster=cluster, initialization=types.Initialization(
def open(readonly): # Parse out the username from the output_conn URL. parsed = urlparse(params['output_conn']) username = parsed.username or "admin@internal" # Read the password from file. with builtins.open(params['output_password'], 'r') as fp: password = fp.read() password = password.rstrip() # Connect to the server. connection = sdk.Connection( url=params['output_conn'], username=username, password=password, ca_file=params['rhv_cafile'], log=logging.getLogger(), insecure=params['insecure'], ) system_service = connection.system_service() # Create the disk. disks_service = system_service.disks_service() if params['disk_format'] == "raw": disk_format = types.DiskFormat.RAW else: disk_format = types.DiskFormat.COW disk = disks_service.add(disk=types.Disk( name=params['disk_name'], description="Uploaded by virt-v2v", format=disk_format, initial_size=params['disk_size'], provisioned_size=params['disk_size'], # XXX Ignores params['output_sparse']. # Handling this properly will be complex, see: # https://www.redhat.com/archives/libguestfs/2018-March/msg00177.html sparse=True, storage_domains=[types.StorageDomain(name=params['output_storage'], )], )) # Wait till the disk is up, as the transfer can't start if the # disk is locked: disk_service = disks_service.disk_service(disk.id) debug("disk.id = %r" % disk.id) endt = time.time() + timeout while True: time.sleep(5) disk = disk_service.get() if disk.status == types.DiskStatus.OK: break if time.time() > endt: raise RuntimeError("timed out waiting for disk to become unlocked") # Get a reference to the transfer service. transfers_service = system_service.image_transfers_service() # Create a new image transfer, using the local host is possible. host = find_host(connection) if params['rhv_direct'] else None transfer = transfers_service.add( types.ImageTransfer( disk=types.Disk(id=disk.id), host=host, inactivity_timeout=3600, )) debug("transfer.id = %r" % transfer.id) # Get a reference to the created transfer service. transfer_service = transfers_service.image_transfer_service(transfer.id) # After adding a new transfer for the disk, the transfer's status # will be INITIALIZING. Wait until the init phase is over. The # actual transfer can start when its status is "Transferring". endt = time.time() + timeout while True: time.sleep(5) transfer = transfer_service.get() if transfer.phase != types.ImageTransferPhase.INITIALIZING: break if time.time() > endt: raise RuntimeError("timed out waiting for transfer status " + "!= INITIALIZING") # Now we have permission to start the transfer. if params['rhv_direct']: if transfer.transfer_url is None: raise RuntimeError("direct upload to host not supported, " + "requires ovirt-engine >= 4.2 and only works " + "when virt-v2v is run within the oVirt/RHV " + "environment, eg. on an oVirt node.") destination_url = urlparse(transfer.transfer_url) else: destination_url = urlparse(transfer.proxy_url) context = ssl.create_default_context() context.load_verify_locations(cafile=params['rhv_cafile']) http = HTTPSConnection(destination_url.hostname, destination_url.port, context=context) # The first request is to fetch the features of the server. # Authentication was needed only for GET and PUT requests when # communicating with old imageio-proxy. needs_auth = not params['rhv_direct'] can_flush = False can_trim = False can_zero = False unix_socket = None http.request("OPTIONS", destination_url.path) r = http.getresponse() data = r.read() if r.status == 200: # New imageio never needs authentication. needs_auth = False j = json.loads(data) can_flush = "flush" in j['features'] can_trim = "trim" in j['features'] can_zero = "zero" in j['features'] unix_socket = j.get('unix_socket') # Old imageio servers returned either 405 Method Not Allowed or # 204 No Content (with an empty body). If we see that we leave # all the features as False and they will be emulated. elif r.status == 405 or r.status == 204: pass else: raise RuntimeError("could not use OPTIONS request: %d: %s" % (r.status, r.reason)) debug("imageio features: flush=%r trim=%r zero=%r unix_socket=%r" % (can_flush, can_trim, can_zero, unix_socket)) # If we are connected to imageio on the local host and the # transfer features a unix_socket then we can reconnect to that. if host is not None and unix_socket is not None: try: http = UnixHTTPConnection(unix_socket) except Exception as e: # Very unlikely failure, but we can recover by using the https # connection. debug("cannot create unix socket connection, using https: %s" % e) else: debug("optimizing connection using unix socket %r" % unix_socket) # Save everything we need to make requests in the handle. return { 'can_flush': can_flush, 'can_trim': can_trim, 'can_zero': can_zero, 'connection': connection, 'disk': disk, 'disk_service': disk_service, 'failed': False, 'highestwrite': 0, 'http': http, 'needs_auth': needs_auth, 'path': destination_url.path, 'transfer': transfer, 'transfer_service': transfer_service, }
while true; do dd if=/dev/urandom of=/mnt/test/random bs=1M count=100; done """ # Name of the VM for which snapshots will be taken. VM_NAME = "test-cirros" # Number of runs of create/merge snapshots. NUM_RUNS = 101 logging.basicConfig(stream=sys.stdout, level=logging.INFO) log = logging.getLogger("snapshots") connection = sdk.Connection( url='https://ovirt-bz.local/ovirt-engine/api', username='******', password='******', ca_file='ca.pem', debug=True, log=logging.getLogger(), ) def wait_for_snapshot(snap_service): log.info("Waiting for snapshot to be ready") while True: if snap_service.get().snapshot_status == types.SnapshotStatus.OK: break time.sleep(1) def wait_for_removal(snap_service): log.info("Waiting for snapshot removal")
# the identifiers and the values are the objects. We will use it to create # indexes that we can use to speed up things like finding the disks # corresponding to a virtual machine, given their identifiers. def index(vals): return {item.id: item for item in vals} # In order to download large collections of objects, it is convenient to use a # different HTTP connection for each of them, so that they are downloaded in # parallel. To achieve that we need to configure the connection so that it uses # multiple HTTP connections, but not pipelining, as otherwise those requests # will be pipelined and executed serially by the server. connection = sdk.Connection( url='https://engine41.example.com/ovirt-engine/api', username='******', password='******', debug=True, ca_file='ca.pem', log=logging.getLogger(), connections=connections, pipeline=0, ) # Get the reference to root of the services tree: system_service = connection.system_service() # Send requests for all the collections, but don't wait for the results. This # way the requests will be sent simultaneously, using the multiple connections print('Requesting data...') dcs_future = system_service.data_centers_service().list(wait=False) clusters_future = system_service.clusters_service().list(wait=False) sds_future = system_service.storage_domains_service().list(wait=False) nets_future = system_service.networks_service().list(wait=False)
import logging import time import ovirtsdk4 as sdk import ovirtsdk4.types as types logging.basicConfig(level=logging.DEBUG, filename='example.log') # This example will connect to the server and start a virtual machine. # Create the connection to the server: connection = sdk.Connection( url='https://engine40.example.com/ovirt-engine/api', username='******', password='******', ca_file='ca.pem', debug=True, log=logging.getLogger(), ) # Get the reference to the "vms" service: vms_service = connection.system_service().vms_service() # Find the virtual machine: vm = vms_service.list(search='name=myvm')[0] # Locate the service that manages the virtual machine, as that is where # the action methods are defined: vm_service = vms_service.vm_service(vm.id) # Call the "start" method of the service to start it:
def main(): parser = option_parser() args = parser.parse_args() if not early_option_check(args): sys.exit(-1) # Create the connection to the server: connection = sdk.Connection( url='https://@ENGINE_FQDN@/ovirt-engine/api', username='******', password=base64.b64decode('@ENGINEPASS_BASE64@'), ca_file='@CA_PEM@', debug=False, ) vms_service = connection.system_service().vms_service() cluster = connection.system_service().clusters_service().list()[0] clustername = cluster.name dcs_service = connection.system_service().data_centers_service() dc = dcs_service.list(search='Clusters.name=%s' % cluster.name)[0] networks_service = dcs_service.service(dc.id).networks_service() profiles_service = connection.system_service().vnic_profiles_service() if not later_option_check(args, connection): connection.close() sys.exit(-1) shorthand = { 'rhel6': 'rhel_6x64', 'rhel7': 'rhel_7x64', 'rhel8': 'rhel_8x64', 'ubuntu': 'ubuntu_14_04', 'debian': 'debian_7', } vmtype = { 'server': types.VmType.SERVER, 'desktop': types.VmType.DESKTOP, 'high_performance': types.VmType.HIGH_PERFORMANCE } # Creating new virtual machine vm = types.Vm() vm.name = args.name vm.cluster = types.Cluster(name=clustername) vm.template = types.Template(name=args.template) if args.os in shorthand.keys(): vm.os = types.OperatingSystem(type=shorthand[args.os]) else: vm.os = types.OperatingSystem(type=args.os) vm.memory = args.memory * 1024 * 1024 if args.balloon == 0: vm.memory_policy = types.MemoryPolicy( max=args.max_memory * 1024 * 1024, guaranteed=args.guaranteed_memory * 1024 * 1024) else: vm.memory_policy = types.MemoryPolicy( max=args.max_memory * 1024 * 1024, guaranteed=args.guaranteed_memory * 1024 * 1024, ballooning=True if args.balloon == 1 else False) vm.cpu = types.Cpu() vm.cpu.architecture = types.Architecture.X86_64 vm.cpu.topology = types.CpuTopology(cores=1, sockets=args.cpu, threads=1) if args.sound != 0: vm.soundcard_enabled = True if args.sound == 1 else False vm.type = vmtype[args.type] print("Creating New Virtual Machine:{0}".format(args.name)) vm = vms_service.add(vm) while vms_service.list(search=args.name)[0].status != types.VmStatus.DOWN: time.sleep(1) # Attach network interface(s) nics_service = vms_service.vm_service(vm.id).nics_service() nicnum = 0 for netname in args.vmnet: network = next( (n for n in networks_service.list() if n.name == netname), None) profile_id = None for profile in profiles_service.list(): if profile.name == netname: profile_id = profile.id break if profile_id != None: nicnum = nicnum + 1 print("Attaching nic{0}(Network:{1})".format(nicnum, netname)) nics_service.add( types.Nic( name="nic{0}".format(nicnum), vnic_profile=types.VnicProfile(id=profile_id, ), ), ) # Create and attach disk(s) disk_attachments_service = vms_service.vm_service( vm.id).disk_attachments_service() disks_service = connection.system_service().disks_service() disknum = 0 for d in args.vmdisk: disknum += 1 new_disk = types.DiskAttachment() new_disk.disk = types.Disk() new_disk.disk.name = "{0}_Disk{1}".format(args.name, disknum) new_disk.disk.provisioned_size = int(d.split(':')[1]) * 2**30 new_disk.disk.storage_domains = [ types.StorageDomain(name=d.split(':')[0]) ] if d.split(':')[2] == "RAW": new_disk.disk.format = types.DiskFormat.RAW else: new_disk.disk.format = types.DiskFormat.COW new_disk.interface = types.DiskInterface.VIRTIO_SCSI new_disk.active = True if disknum == 1: new_disk.bootable = True print( "Attaching Disk{0}(Domain:{1}, Size:{2}GB, DiskFormat:{3})".format( disknum, d.split(':')[0], d.split(':')[1], d.split(':')[2])) disk_attachment = disk_attachments_service.add(new_disk) disk_service = disks_service.disk_service(disk_attachment.disk.id) # wait disk attach finish time.sleep(5) while disk_service.get().status != types.DiskStatus.OK: print("Waiting disk attach complete") time.sleep(5) if args.ks != None or args.ps != None or args.ai != None: # one-shot VM configuration for Kickstart/preseed one_vm = types.Vm() one_vm.os = types.OperatingSystem() one_vm.os.kernel = 'iso://' + args.kernel one_vm.os.initrd = 'iso://' + args.initrd one_vm.run_once = True one_vm.cdroms = list() one_vm.cdroms.append(types.Cdrom()) one_vm.cdroms[0].file = types.File() one_vm.cdroms[0].file.id = args.iso if args.dns == None: args.dns = "" elif args.os == 'rhel6': args.dns = 'dns=' + args.dns else: args.dns = 'nameserver=' + args.dns if args.os == 'rhel6': ksdev = args.network.split(':')[5] ksip = args.network.split(':')[0] ksnm = calc_netmask(int(args.network.split(':')[3])) ksgw = args.network.split(':')[2] args.network = "ksdevice={0} ip={1} netmask={2} gateway={3}".format( ksdev, ksip, ksnm, ksgw) if args.ks != None: if args.os == 'rhel6': one_vm.os.cmdline = args.network + " " + args.dns + " ks=" + args.ks else: one_vm.os.cmdline = args.network + " " + args.dns + " inst.ks=" + args.ks if args.ps != None: one_vm.os.cmdline = "auto=true url=" + args.ps if args.ai != None: one_vm.os.cmdline = "autoinstall ds=nocloud-net;s=" + args.ai vm_service = vms_service.vm_service(vm.id) print("Starting automatic OS installation on {0}".format(args.name)) vm_service.start(vm=one_vm, volatile=True) # Close the connection to the server: connection.close()