def _ssh_credentials(self, name): user = '******' ip = None nova = self.nova try: vm = nova.servers.find(name=name) except: return None, None try: vm = nova.servers.find(name=name) except: common.pprint("VM %s not found" % name, color='red') return None, None if 'id' in vm.image: template = self.glance.images.get(vm.image['id']).name user = common.get_user(template) for key in list(vm.addresses): entry1 = vm.addresses[key] for entry2 in entry1: if entry2['OS-EXT-IPS:type'] == 'floating': ip = entry2['addr'] if ip is None: print("No ip found. Cannot ssh...") return None, None return user, ip
def _list(self): """ :return: """ k = self.k tunnel = self.tunnel metadata = {'_meta': {'hostvars': {}}} hostvalues = metadata['_meta']['hostvars'] for vm in k.list(): name = vm.get('name') status = vm.get('status') ip = vm.get('ip', '') image = vm.get('image') plan = vm.get('plan', 'kvirt') if plan == '': plan = 'kvirt' profile = vm.get('profile', '') if plan not in metadata: metadata[plan] = {"hosts": [name], "vars": {"plan": plan, "profile": profile}} else: metadata[plan]["hosts"].append(name) hostvalues[name] = {'status': status} if tunnel and self.type in ['kvm', 'kubevirt']: hostvalues[name]['ansible_ssh_common_args'] = \ "-o ProxyCommand='ssh -p %s -W %%h:%%p %s@%s'" % (self.port, self.user, self.host) if ip != '': hostvalues[name]['ansible_host'] = ip if image != '': user = get_user(image) hostvalues[name]['ansible_user'] = user return metadata
def _ssh_credentials(self, name): user = '******' nova = self.nova try: vm = nova.servers.find(name=name) except: return None, None vm = [v for v in self.list() if v[0] == name][0] template = vm[3] if template != '': user = common.get_user(template) ip = vm[2] if ip == '': print("No ip found. Cannot ssh...") user = common.get_user(template) return user, ip
def get(self, name): """ :return: """ k = self.k tunnel = self.tunnel metadata = {} vm = k.info(name) for entry in ['name', 'template', 'plan', 'profile', 'ip']: metadata[entry] = vm.get(entry) if metadata['plan'] == '': metadata['plan'] = 'kvirt' if tunnel and self.type in ['kvm', 'kubevirt']: metadata['ansible_ssh_common_args'] = \ "-o ProxyCommand='ssh -p %s -W %%h:%%p %s@%s'" % (self.port, self.user, self.host) ip = metadata['ip'] if ip != '': if self.type == 'vbox': metadata['ansible_host'] = '127.0.0.1' metadata['ansible_port'] = ip else: metadata['ansible_host'] = ip template = metadata['template'] if template != '': user = get_user(template) metadata['ansible_user'] = user return metadata
def info(self, name, vm=None, debug=False): nova = self.nova cinder = self.cinder if vm is None: try: vm = nova.servers.find(name=name) except: common.pprint("VM %s not found" % name, color='red') return {} if debug: print(vars(vm)) yamlinfo = {'name': vm.name, 'status': vm.status, 'project': self.project} if vm.status.lower() == 'error': try: yamlinfo['error'] = vm.fault['message'] except: pass source = self.glance.images.get(vm.image['id']).name if 'id' in vm.image else '' yamlinfo['image'] = source yamlinfo['user'] = common.get_user(source) flavor = nova.flavors.get(vm.flavor['id']) yamlinfo['flavor'] = flavor.name yamlinfo['memory'] = flavor.ram yamlinfo['cpus'] = flavor.vcpus yamlinfo['nets'] = [] index = 0 for key in list(vm.addresses): entry1 = vm.addresses[key] for entry2 in entry1: mac = entry2['OS-EXT-IPS-MAC:mac_addr'] if entry2['OS-EXT-IPS:type'] == 'floating': yamlinfo['ip'] = entry2['addr'] else: net = {'device': 'eth%s' % index, 'mac': mac, 'net': key, 'type': entry2['addr']} if index == 0: yamlinfo['privateip'] = entry2['addr'] yamlinfo['nets'].append(net) index += 1 if 'ip' not in yamlinfo: yamlinfo['ip'] = yamlinfo['privateip'] disks = [] for disk in vm._info['os-extended-volumes:volumes_attached']: diskid = disk['id'] volume = cinder.volumes.get(diskid) disksize = volume.size devname = volume.name disks.append({'device': devname, 'size': disksize, 'format': '', 'type': '', 'path': diskid}) if disks: yamlinfo['disks'] = disks metadata = vm.metadata if metadata is not None: if 'plan' in metadata: yamlinfo['plan'] = metadata['plan'] if 'profile' in metadata: yamlinfo['profile'] = metadata['profile'] if 'loadbalancer' in metadata: yamlinfo['loadbalancer'] = metadata['loadbalancer'] return yamlinfo
def info(self, name, output='plain', fields=[], values=False, vm=None, debug=False): """ :param name: :param output: :param fields: :param values: :return: """ if vm is None: vm = self._foremando(who=name) if self.debug: print(vars(vm)) yamlinfo = {'name': name} plan, profile = 'N/A', 'N/A' state = 'up' cpus = 2 memory = 1024 image = vm['hostgroup_name'] user = common.get_user(image) yamlinfo = { 'name': name, 'image': image, 'plan': plan, 'profile': profile, 'status': state, 'cpus': cpus, 'memory': memory, 'user': user } yamlinfo['created_at'] = vm['created_at'] yamlinfo['owner_name'] = vm['owner_name'] yamlinfo['id'] = vm['id'] nets = [] if 'interfaces' in vm: for interface in vm['interfaces']: device = interface['identifier'] mac = interface['mac'] network = interface.get('subnet_name', 'N/A') network_type = interface.get('type', 'N/A') if 'ip' in interface: yamlinfo['ip'] = vm['ip'] nets.append({ 'device': device, 'mac': mac, 'net': network, 'type': network_type }) if nets: yamlinfo['nets'] = nets return yamlinfo
def _ssh_credentials(self, name): ip, user = None, 'root' vm = self._foremando(who=name) image = vm['hostgroup_name'] if image is not None: user = common.get_user(image) for interface in vm['interfaces']: if 'ip' in interface: ip = vm['ip'] break return user, ip
def info(self, name, output='plain', fields=[], values=False, vm=None, debug=False): translation = {'poweredOff': 'down', 'poweredOn': 'up', 'suspended': 'suspended'} yamlinfo = {} si = self.si dc = self.dc vmFolder = dc.vmFolder if vm is None: vm = findvm(si, vmFolder, name) if vm is None: error("VM %s not found" % name) return {} summary = vm.summary yamlinfo['name'] = name yamlinfo['id'] = summary.config.instanceUuid yamlinfo['cpus'] = vm.config.hardware.numCPU yamlinfo['memory'] = vm.config.hardware.memoryMB yamlinfo['status'] = translation[vm.runtime.powerState] yamlinfo['nets'] = [] yamlinfo['disks'] = [] devices = vm.config.hardware.device mainmac = None for number, dev in enumerate(devices): if "addressType" in dir(dev): network = dev.backing.deviceName device = dev.deviceInfo.label networktype = 'N/A' mac = dev.macAddress if mainmac is None: mainmac = mac net = {'device': device, 'mac': mac, 'net': network, 'type': networktype} yamlinfo['nets'].append(net) if type(dev).__name__ == 'vim.vm.device.VirtualDisk': device = "disk%s" % dev.unitNumber disksize = convert(1000 * dev.capacityInKB, GB=False) diskformat = dev.backing.diskMode drivertype = 'thin' if dev.backing.thinProvisioned else 'thick' path = dev.backing.datastore.name disk = {'device': device, 'size': int(disksize), 'format': diskformat, 'type': drivertype, 'path': path} yamlinfo['disks'].append(disk) if vm.runtime.powerState == "poweredOn": yamlinfo['host'] = vm.runtime.host.name for nic in vm.guest.net: currentmac = nic.macAddress currentips = nic.ipAddress if currentmac == mainmac and currentips: yamlinfo['ip'] = currentips[0] for entry in vm.config.extraConfig: if entry.key in METADATA_FIELDS: yamlinfo[entry.key] = entry.value if entry.key == 'image': yamlinfo['user'] = common.get_user(entry.value) if debug: yamlinfo['debug'] = vm.config.extraConfig return yamlinfo
def _ssh_credentials(self, name): conn = self.conn try: Filters = {'Name': "tag:Name", 'Values': [name]} vm = conn.describe_instances( Filters=[Filters])['Reservations'][0]['Instances'][0] except: print("VM %s not found" % name) return '', '' vm = [v for v in self.list() if v[0] == name][0] template = vm[3] if template != '': user = common.get_user(template) ip = vm[2] if ip == '': print("No ip found. Cannot ssh...") return user, ip
def _ssh_credentials(self, name): conn = self.conn resource = self.resource try: Filters = {'Name': "tag:Name", 'Values': [name]} vm = conn.describe_instances(Filters=[Filters])['Reservations'][0]['Instances'][0] except: print("VM %s not found" % name) return '', '' amid = vm['ImageId'] image = resource.Image(amid) template = os.path.basename(image.image_location) if template != '': user = common.get_user(template) ip = vm['PublicIpAddress'] if 'PublicIpAddress' in vm else '' if ip == '': print("No ip found. Cannot ssh...") return user, ip
def _ssh_credentials(self, name): # user = '******' # ip = self.ip(name) # return (user, ip) conn = self.conn try: vm = conn.describe_instances(InstanceIds=[name])['Reservations'][0]['Instances'][0] except: print(("VM %s not found" % name)) return '', '' vm = [v for v in self.list() if v[0] == name][0] template = vm[3] if template != '': user = common.get_user(template) ip = vm[2] if ip == '': print("No ip found. Cannot ssh...") return user, ip
def _ssh_credentials(self, name): ip = '' vmsearch = self.vms_service.list(search='name=%s' % name) if not vmsearch: common.pprint("VM %s not found" % name, color='red') return 'root', None vm = vmsearch[0] template = self.conn.follow_link(vm.template) user = common.get_user(template.name) ips = [] devices = self.vms_service.vm_service( vm.id).reported_devices_service().list() for device in devices: if device.ips: for i in device.ips: if str(i.version) == 'v4' and i.address not in [ '172.17.0.1', '127.0.0.1' ]: ips.append(i.address) if not ips: common.print("No ip found. Cannot ssh...", color='red') else: ip = ips[-1] return user, ip
def info(self, name, output='plain', fields=[], values=False, vm=None, debug=False): """ :param name: :param output: :param fields: :param values: :return: """ devices = [ d for d in self.conn.list_devices(self.project) if d.hostname == name ] if devices: device = devices[0] else: error("VM %s not found" % name) return {} if debug: print(vars(device)) name = device.hostname deviceid = device.id state = device.state nets = [] ip = None for entry in device.ip_addresses: if entry['public'] and entry['address_family'] == 4: ip = entry['address'] dev = 'bond0' mac = entry['address'] network = entry['network'] networktype = 'public' if entry['public'] else 'private' nets.append({ 'device': dev, 'mac': mac, 'net': network, 'type': networktype }) if device.network_ports is not None: for entry in device.network_ports: if entry['type'] == 'NetworkBondPort': continue dev = entry['name'] bonded = entry['data']['bonded'] networktype = 'bonded' if bonded else 'vlan' network = 'default' if not bonded: virtual_networks = entry['virtual_networks'] virtual_network_ids = [ os.path.basename(vn['href']) for vn in virtual_networks ] vlans = [] for vlan in self.conn.list_vlans(self.project): if vlan.id in virtual_network_ids: vlans.append(vlan.description if vlan.description is not None else vlan.vxlan) network = ','.join(vlans) mac = entry['data']['mac'] nets.append({ 'device': dev, 'mac': mac, 'net': network, 'type': networktype }) kernel = None source = device.operating_system['slug'] flavor = device.plan flavorname = device.plan['slug'] disks = [] for index0, entry in enumerate(flavor['specs']['drives']): for index1 in range(entry['count']): dev = "disk%s_%s" % (index0, index1) disksize = entry['size'].replace('GB', '') if 'TB' in entry['size']: disksize = int(float(disksize.replace('TB', '')) * 1000) else: disksize = int(disksize) diskformat = entry['type'] drivertype = entry['category'] path = '' disks.append({ 'device': dev, 'size': disksize, 'format': diskformat, 'type': drivertype, 'path': path }) for volume in device.volumes: volumeid = os.path.basename(volume['href']) volumeinfo = self.conn.get_volume(volumeid) dev = volumeinfo.name disksize = volumeinfo.size drivertype = 'volume' diskformat = '' path = volumeinfo.description if volumeinfo.description is not None else volumeinfo.name disks.append({ 'device': dev, 'size': disksize, 'format': diskformat, 'type': drivertype, 'path': path }) numcpus = int(flavor['specs']['cpus'][0]['count']) memory = int(flavor['specs']['memory']['total'].replace('GB', '')) * 1024 creationdate = device.created_at yamlinfo = { 'name': name, 'instanceid': deviceid, 'status': state, 'ip': ip, 'nets': nets, 'disks': disks, 'flavor': flavorname, 'cpus': numcpus, 'memory': memory, 'creationdate': creationdate } if ip is not None: yamlinfo['ip'] = ip yamlinfo['user'] = common.get_user( kernel) if kernel is not None else 'root' if device.tags: for tag in device.tags: if '_' in tag and len(tag.split('_')) == 2: key, value = tag.split('_') yamlinfo[key] = value if key == 'kernel': kernel = value yamlinfo[ 'image'] = kernel if kernel is not None and source == 'custom_ipxe' else source # for entry in device.network_ports: # print(entry) return yamlinfo
def create(self, name, virttype='kvm', profile='', flavor=None, plan='kvirt', cpumodel='Westmere', cpuflags=[], numcpus=2, memory=512, guestid='guestrhel764', pool='default', template=None, disks=[{ 'size': 10 }], disksize=10, diskthin=True, diskinterface='virtio', nets=['default'], iso=None, vnc=False, cloudinit=True, reserveip=False, reservedns=False, reservehost=False, start=True, keys=None, cmds=[], ips=None, netmasks=None, gateway=None, nested=True, dns=None, domain=None, tunnel=False, files=[], enableroot=True, alias=[], overrides={}, tags=None): """ :param name: :param virttype: :param profile: :param flavor: :param plan: :param cpumodel: :param cpuflags: :param numcpus: :param memory: :param guestid: :param pool: :param template: :param disks: :param disksize: :param diskthin: :param diskinterface: :param nets: :param iso: :param vnc: :param cloudinit: :param reserveip: :param reservedns: :param reservehost: :param start: :param keys: :param cmds: :param ips: :param netmasks: :param gateway: :param nested: :param dns: :param domain: :param tunnel: :param files: :param enableroot: :param alias: :param overrides: :param tags: :return: """ clone = not diskthin templateobject = types.Template(name=template) if template else None console = types.Console(enabled=True) try: vm = self.vms_service.add(types.Vm( name=name, cluster=types.Cluster(name=self.cluster), template=templateobject, console=console), clone=clone) vm_service = self.vms_service.vm_service(vm.id) except Exception as e: if self.debug: print(e) return {'result': 'failure', 'reason': e} timeout = 0 while True: vm = vm_service.get() if vm.status == types.VmStatus.DOWN: break else: timeout += 5 sleep(5) common.pprint("Waiting for vm to be ready", color='green') if timeout > 60: return { 'result': 'failure', 'reason': 'timeout waiting for vm to be ready' } profiles_service = self.conn.system_service().vnic_profiles_service() netprofiles = {} for prof in profiles_service.list(): netprofiles[prof.name] = prof.id if 'default' not in netprofiles and 'ovirtmgmt' in netprofiles: netprofiles['default'] = netprofiles['ovirtmgmt'] nics_service = self.vms_service.vm_service(vm.id).nics_service() nic_configurations = [] for index, net in enumerate(nets): netname = None netmask = None mac = None if isinstance(net, str): netname = net elif isinstance(net, dict) and 'name' in net: netname = net['name'] ip = None mac = net.get('mac') netmask = next( (e for e in [net.get('mask'), net.get('netmask')] if e is not None), None) gateway = net.get('gateway') noconf = net.get('noconf') if noconf is not None: continue if 'ip' in net: ip = net['ip'] # if 'alias' in net: # alias = net['alias'] if ips and len(ips) > index and ips[index] is not None: ip = ips[index] if ip is not None and netmask is not None and gateway is not None: nic_configuration = types.NicConfiguration( name='eth%s' % index, on_boot=True, boot_protocol=types.BootProtocol.STATIC, ip=types.Ip(version=types.IpVersion.V4, address=ip, netmask=netmask, gateway=gateway)) nic_configurations.append(nic_configuration) if netname is not None and netname in netprofiles: profile_id = netprofiles[netname] nics_service.add( types.Nic(name='eth%s' % index, mac=mac, vnic_profile=types.VnicProfile(id=profile_id))) for index, disk in enumerate(disks): diskpool = pool diskthin = True disksize = '10' if index == 0 and template is not None: continue if isinstance(disk, int): disksize = disk elif isinstance(disk, str) and disk.isdigit(): disksize = int(disk) elif isinstance(disk, dict): disksize = disk.get('size', disksize) diskpool = disk.get('pool', pool) diskthin = disk.get('thin', diskthin) self.add_disk(name, disksize, pool=diskpool, thin=diskthin) initialization = None if cloudinit: custom_script = '' if files: data = common.process_files(files=files, overrides=overrides) if data != '': custom_script += "write_files:\n" custom_script += data cmds.append('sleep 60') if template.lower().startswith('centos'): cmds.append('yum -y install centos-release-ovirt42') if template.lower().startswith('centos') or template.lower().startswith('fedora')\ or template.lower().startswith('rhel'): cmds.append('yum -y install ovirt-guest-agent-common') cmds.append('systemctl enable ovirt-guest-agent') cmds.append('systemctl start ovirt-guest-agent') if template.lower().startswith('debian'): cmds.append( 'echo "deb http://download.opensuse.org/repositories/home:/evilissimo:/deb/Debian_7.0/ ./" ' '>> /etc/apt/sources.list') cmds.append( 'gpg -v -a --keyserver http://download.opensuse.org/repositories/home:/evilissimo:/deb/' 'Debian_7.0/Release.key --recv-keys D5C7F7C373A1A299') cmds.append('gpg --export --armor 73A1A299 | apt-key add -') cmds.append('apt-get update') cmds.append('apt-get -Y install ovirt-guest-agent') cmds.append('service ovirt-guest-agent enable') cmds.append('service ovirt-guest-agent start') if [x for x in common.ubuntus if x in template.lower()]: cmds.append( 'echo deb http://download.opensuse.org/repositories/home:/evilissimo:/ubuntu:/16.04/' 'xUbuntu_16.04/ /') cmds.append( 'wget http://download.opensuse.org/repositories/home:/evilissimo:/ubuntu:/16.04/' 'xUbuntu_16.04//Release.key') cmds.append('apt-key add - < Release.key') cmds.append('apt-get update') cmds.append('apt-get -Y install ovirt-guest-agent') data = common.process_cmds(cmds=cmds, overrides=overrides) custom_script += "runcmd:\n" custom_script += data custom_script = None if custom_script == '' else custom_script user_name = common.get_user(template) root_password = None dns_servers = '8.8.8.8 1.1.1.1' key = get_home_ssh_key() initialization = types.Initialization( user_name=user_name, root_password=root_password, regenerate_ssh_keys=True, authorized_ssh_keys=key, host_name=name, nic_configurations=nic_configurations, dns_servers=dns_servers, dns_search=domain, custom_script=custom_script) tags_service = self.conn.system_service().tags_service() existing_tags = [tag.name for tag in tags_service.list()] if "profile_%s" % profile not in existing_tags: tags_service.add(types.Tag(name="profile_%s" % profile)) if "plan_%s" % plan not in existing_tags: tags_service.add(types.Tag(name="plan_%s" % plan)) tags_service = vm_service.tags_service() tags_service.add(tag=types.Tag(name="profile_%s" % profile)) tags_service.add(tag=types.Tag(name="plan_%s" % plan)) vm_service.start(use_cloud_init=cloudinit, vm=types.Vm(initialization=initialization)) return {'result': 'success'}
def info(self, name, vm=None, debug=False): yamlinfo = {} conn = self.conn resource = self.resource if vm is None: try: if name.startswith('i-'): vm = conn.describe_instances( InstanceIds=[name])['Reservations'][0]['Instances'][0] else: Filters = {'Name': "tag:Name", 'Values': [name]} vm = conn.describe_instances( Filters=[Filters])['Reservations'][0]['Instances'][0] except: error("VM %s not found" % name) return {} instanceid = vm['InstanceId'] name = instanceid state = vm['State']['Name'] ip = vm['PublicIpAddress'] if 'PublicIpAddress' in vm else '' amid = vm['ImageId'] az = vm['Placement']['AvailabilityZone'] image = resource.Image(amid) source = os.path.basename(image.image_location) plan = '' profile = '' if 'Tags' in vm: for tag in vm['Tags']: yamlinfo[tag['Key']] = tag['Value'] if tag['Key'] == 'Name': name = tag['Value'] yamlinfo['name'] = name yamlinfo['status'] = state yamlinfo['az'] = az yamlinfo['ip'] = ip machinetype = vm['InstanceType'] yamlinfo['flavor'] = machinetype if machinetype in staticf: yamlinfo['cpus'] = staticf[machinetype]['cpus'] yamlinfo['memory'] = staticf[machinetype]['memory'] # yamlinfo['autostart'] = vm['scheduling']['automaticRestart'] yamlinfo['image'] = source yamlinfo['user'] = common.get_user(yamlinfo['image']) # yamlinfo['creationdate'] = dateparser.parse(vm['creationTimestamp']).strftime("%d-%m-%Y %H:%M") yamlinfo['plan'] = plan yamlinfo['profile'] = profile yamlinfo['instanceid'] = instanceid nets = [] for interface in vm['NetworkInterfaces']: network = interface['VpcId'] device = interface['NetworkInterfaceId'] mac = interface['MacAddress'] private_ip = interface['PrivateIpAddresses'][0]['PrivateIpAddress'] nets.append({ 'device': device, 'mac': mac, 'net': network, 'type': private_ip }) yamlinfo['privateip'] = private_ip if nets: yamlinfo['nets'] = nets disks = [] for index, disk in enumerate(vm['BlockDeviceMappings']): devname = disk['DeviceName'] volumeid = disk['Ebs']['VolumeId'] volume = conn.describe_volumes(VolumeIds=[volumeid])['Volumes'][0] disksize = volume['Size'] diskformat = volume['AvailabilityZone'] drivertype = volume['VolumeType'] path = volumeid disks.append({ 'device': devname, 'size': disksize, 'format': diskformat, 'type': drivertype, 'path': path }) if disks: yamlinfo['disks'] = disks if debug: yamlinfo['debug'] = vm return yamlinfo