Пример #1
0
 def build_entity(self):
     return otypes.Tag(
         name=self._module.params['name'],
         description=self._module.params['description'],
         parent=otypes.Tag(name=self._module.params['parent'], )
         if self._module.params['parent'] else None,
     )
Пример #2
0
    def _update_tag_assignments(self, entity, name):
        if self._module.params[name] is None:
            return

        entities_service = getattr(self._connection.system_service(), '%s_service' % name)()
        current_vms = [
            vm.name
            for vm in entities_service.list(search='tag=%s' % self._module.params['name'])
        ]
        # Assign tags:
        for entity_name in self._module.params[name]:
            entity = search_by_name(entities_service, entity_name)
            tags_service = entities_service.service(entity.id).tags_service()
            current_tags = [tag.name for tag in tags_service.list()]
            # Assign the tag:
            if self._module.params['name'] not in current_tags:
                if not self._module.check_mode:
                    tags_service.add(
                        tag=otypes.Tag(
                            name=self._module.params['name'],
                        ),
                    )
                self.changed = True

        # Unassign tags:
        for entity_name in [e for e in current_vms if e not in self._module.params[name]]:
            if not self._module.check_mode:
                entity = search_by_name(entities_service, entity_name)
                tags_service = entities_service.service(entity.id).tags_service()
                tag_id = [tag.id for tag in tags_service.list() if tag.name == self._module.params['name']][0]
                tags_service.tag_service(tag_id).remove()
            self.changed = True
Пример #3
0
    def _update_tag_assignments(self, entity, name):
        if self._module.params[name] is None:
            return

        state = self.param('state')
        entities_service = getattr(self._connection.system_service(),
                                   '%s_service' % name)()
        current_vms = [
            vm.name
            for vm in entities_service.list(search='tag=%s' %
                                            self._module.params['name'])
        ]
        # Assign tags:
        if state in ['present', 'attached', 'detached']:
            for entity_name in self._module.params[name]:
                entity_id = get_id_by_name(entities_service, entity_name)
                tags_service = entities_service.service(
                    entity_id).tags_service()
                current_tags = [tag.name for tag in tags_service.list()]
                # Assign the tag:
                if state in ['attached', 'present']:
                    if self._module.params['name'] not in current_tags:
                        if not self._module.check_mode:
                            tags_service.add(tag=otypes.Tag(
                                name=self._module.params['name'], ), )
                        self.changed = True
                # Detach the tag:
                elif state == 'detached':
                    if self._module.params['name'] in current_tags:
                        tag_id = get_id_by_name(tags_service,
                                                self.param('name'))
                        if not self._module.check_mode:
                            tags_service.tag_service(tag_id).remove()
                        self.changed = True

        # Unassign tags:
        if state == 'present':
            for entity_name in [
                    e for e in current_vms
                    if e not in self._module.params[name]
            ]:
                if not self._module.check_mode:
                    entity_id = get_id_by_name(entities_service, entity_name)
                    tags_service = entities_service.service(
                        entity_id).tags_service()
                    tag_id = get_id_by_name(tags_service, self.param('name'))
                    tags_service.tag_service(tag_id).remove()
                self.changed = True
Пример #4
0
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 new tag:
# 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 tags service:
tags_service = connection.system_service().tags_service()

# Use the "add" method to create new tag:
tag = tags_service.add(types.Tag(
    name='mytag',
    description='My custom tag',
), )

# Close the connection to the server:
connection.close()
Пример #5
0
 def build_entity(self):
     return otypes.Tag(name=self._module.params['name'],
                       description=self._module.params['description'])
Пример #6
0
    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'}
Пример #7
0
    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=myvm0')[0]

# Find the service that manages the vm:
vm_service = vms_service.vm_service(vm.id)

# Locate the service that manages the tags of the vm:
tags_service = vm_service.tags_service()

# Assign tag to virtual machine:
tags_service.add(
    tag=types.Tag(
        name='mytag',
    )
)

# Close the connection to the server:
connection.close()