Beispiel #1
0
 def startVMWithClouldinit(self,
                           vmname,
                           fqdn,
                           address,
                           netmask,
                           gateway,
                           dns_server,
                           dns_search,
                           nicname="eth0"):
     vms_service = self.connection.system_service().vms_service()
     vm = vms_service.list(search='name=%s' % vmname)[0]
     vm_service = vms_service.vm_service(vm.id)
     vm_service.start(
         use_cloud_init=True,
         vm=types.Vm(initialization=types.Initialization(
             # user_name='root',
             # root_password='******',
             host_name=fqdn,  # 虚拟机的hostname
             nic_configurations=[
                 types.NicConfiguration(
                     name=nicname,  # 默认网卡名为eth0 ,如果多网卡指定名称,目前不支持多网卡配置地址
                     on_boot=True,  # 网卡onboot=yes
                     boot_protocol=types.BootProtocol.STATIC,
                     ip=types.Ip(
                         version=types.IpVersion.V4,
                         address=address,  # 虚拟机的ip地址
                         netmask=netmask,  # 虚拟机的地址掩码
                         gateway=gateway  # 虚拟机的网关
                     ))
             ],
             dns_servers=dns_server,  # 虚拟机DNS服务器地址
             dns_search=dns_search,  # 虚拟机dns 查找域
         )))
Beispiel #2
0
def _get_initialization(sysprep, cloud_init, cloud_init_nics):
    initialization = None
    if cloud_init or cloud_init_nics:
        initialization = otypes.Initialization(nic_configurations=[
            otypes.NicConfiguration(
                boot_protocol=otypes.BootProtocol(
                    nic.pop('nic_boot_protocol').lower())
                if nic.get('nic_boot_protocol') else None,
                name=nic.pop('nic_name', None),
                on_boot=nic.pop('nic_on_boot', None),
                ip=otypes.Ip(
                    address=nic.pop('nic_ip_address', None),
                    netmask=nic.pop('nic_netmask', None),
                    gateway=nic.pop('nic_gateway', None),
                ) if (nic.get('nic_gateway') is not None
                      or nic.get('nic_netmask') is not None
                      or nic.get('nic_ip_address') is not None) else None,
            ) for nic in cloud_init_nics
            if (nic.get('nic_gateway') is not None or nic.get('nic_netmask')
                is not None or nic.get('nic_ip_address') is not None
                or nic.get('nic_boot_protocol') is not None
                or nic.get('nic_on_boot') is not None)
        ] if cloud_init_nics else None,
                                               **cloud_init)
    elif sysprep:
        initialization = otypes.Initialization(**sysprep)
    return initialization
Beispiel #3
0
    def get_initialization(self, vm):
        if self._initialization is not None:
            return self._initialization

        sysprep = vm.get('sysprep')
        cloud_init = vm.get('cloud_init')
        cloud_init_nics = vm.get('cloud_init_nics') or []
        if cloud_init is not None:
            cloud_init_nics.append(cloud_init)

        if cloud_init or cloud_init_nics:
            self._initialization = otypes.Initialization(nic_configurations=[
                otypes.NicConfiguration(
                    boot_protocol=otypes.BootProtocol(
                        nic.pop('nic_boot_protocol').lower())
                    if nic.get('nic_boot_protocol') else None,
                    name=nic.pop('nic_name', None),
                    on_boot=nic.pop('nic_on_boot', None),
                    ip=otypes.Ip(
                        address=nic.pop('nic_ip_address', None),
                        netmask=nic.pop('nic_netmask', None),
                        gateway=nic.pop('nic_gateway', None),
                    ) if (nic.get('nic_gateway') is not None
                          or nic.get('nic_netmask') is not None
                          or nic.get('nic_ip_address') is not None) else None,
                ) for nic in cloud_init_nics
                if (nic.get('nic_gateway') is not None or nic.get(
                    'nic_netmask') is not None or nic.get('nic_ip_address')
                    is not None or nic.get('nic_boot_protocol') is not None
                    or nic.get('nic_on_boot') is not None)
            ] if cloud_init_nics else None,
                                                         **cloud_init)
        elif sysprep:
            self._initialization = otypes.Initialization(**sysprep)
        return self._initialization
def _get_initialization(sysprep, cloud_init):
    initialization = None
    if cloud_init:
        initialization = otypes.Initialization(
            nic_configurations=[
                otypes.NicConfiguration(
                    boot_protocol=otypes.BootProtocol(
                        cloud_init.pop('nic_boot_protocol').lower()
                    ) if cloud_init.get('nic_boot_protocol') else None,
                    name=cloud_init.pop('nic_name'),
                    on_boot=cloud_init.pop('nic_on_boot'),
                    ip=otypes.Ip(
                        address=cloud_init.pop('nic_ip_address'),
                        netmask=cloud_init.pop('nic_netmask'),
                        gateway=cloud_init.pop('nic_gateway'),
                    ) if (
                        cloud_init.get('nic_gateway') is not None or
                        cloud_init.get('nic_netmask') is not None or
                        cloud_init.get('nic_ip_address') is not None
                    ) else None,
                )
            ] if (
                cloud_init.get('nic_gateway') is not None or
                cloud_init.get('nic_netmask') is not None or
                cloud_init.get('nic_ip_address') is not None or
                cloud_init.get('nic_boot_protocol') is not None or
                cloud_init.get('nic_on_boot') is not None
            ) else None,
            **cloud_init
        )
    elif sysprep:
        initialization = otypes.Initialization(
            **sysprep
        )
    return  initialization
def vm_run(prefix, api):
    host_names = [h.name() for h in prefix.virt_env.host_vms()]

    vms_service = api.system_service().vms_service()
    vm = vms_service.list(search='name=%s' % VM0_NAME)[0]

    gw_ip = test_utils.get_management_net(prefix).gw()
    vm_params = types.Vm(
        placement_policy=types.VmPlacementPolicy(hosts=[
            types.Host(name="{}.{}".format(sorted(host_names)[0], DOMAIN_NAME))
        ], ),
        initialization=types.Initialization(user_name=VM_USER_NAME,
                                            root_password=VM_PASSWORD))

    vm_params.initialization.host_name = 'VM0'
    vm_params.initialization.dns_search = DOMAIN_NAME
    vm_params.initialization.domain = DOMAIN_NAME
    vm_params.initialization.dns_servers = gw_ip
    vm_params.initialization.nic_configurations = [
        types.NicConfiguration(
            name='eth0',
            boot_protocol=types.BootProtocol.STATIC,
            on_boot=True,
            ip=types.Ip(address=test_utils.get_vm0_ip_address(prefix),
                        netmask='255.255.255.0',
                        gateway=gw_ip))
    ]

    vm_service = vms_service.vm_service(vm.id)
    vm_service.start(use_cloud_init=True, vm=vm_params)

    testlib.assert_true_within_long(
        lambda: (vms_service.list(search='name=%s' % VM0_NAME)[0]).status ==
        types.VmStatus.UP, )
def bucle2():
    try:
        vm_service.start(
            use_cloud_init=True,
            vm=types.Vm(
                initialization=types.Initialization(
                    nic_configurations=[
                        types.NicConfiguration(
                            name='eth0',
                            on_boot=True,
                            boot_protocol=types.BootProtocol.STATIC,
                            ip=types.Ip(
                                version=types.IpVersion.V4,
                                address=sys.argv[2],
                                netmask='255.255.255.0',
                                gateway='10.6.134.50'
                            )
                        )
                    ]
                )
            )
        )
    except:
	    time.sleep(100)
        bucle2()
Beispiel #7
0
 def start_vm_cloud_init(self, vm_service, vm, use_cloud_init=True):
     vm_service.start(use_cloud_init=use_cloud_init,
                      vm=types.Vm(initialization=types.Initialization(
                          nic_configurations=[
                              types.NicConfiguration(
                                  name='eth0',
                                  on_boot=True,
                                  boot_protocol=types.BootProtocol.STATIC,
                                  ip=types.Ip(version=types.IpVersion.V4,
                                              address=vm.ip.ip,
                                              netmask=vm.ip.netmask,
                                              gateway=vm.ip.gateway))
                          ],
                          dns_servers='8.8.8.8',
                      )))
 def _to_ip_address_assignment(self, ip_assignment):
     """
     :param ip_assignment: netattachlib.IpAssignment
     :return: types.IpAddressAssignment
     """
     ip_address_assignment = types.IpAddressAssignment(
         assignment_method=ip_assignment.boot_protocol,
         ip=types.Ip(
             address=ip_assignment.address,
             netmask=ip_assignment.netmask,
             gateway=ip_assignment.gateway,
             version=ip_assignment.version,
         ),
     )
     return ip_address_assignment
Beispiel #9
0
def test_run_vms(prefix):
    engine = prefix.virt_env.engine_vm().get_api_v4().system_service()

    vm_params = types.Vm(initialization=types.Initialization(
        user_name=VM_USER_NAME, root_password=VM_PASSWORD))

    vm_params.initialization.host_name = BACKUP_VM_NAME
    backup_vm_service = test_utils.get_vm_service(engine, BACKUP_VM_NAME)
    backup_vm_service.start(use_cloud_init=True, vm=vm_params)

    vm_params.initialization.host_name = VM2_NAME
    vm2_service = test_utils.get_vm_service(engine, VM2_NAME)
    vm2_service.start(use_cloud_init=True, vm=vm_params)

    gw_ip = test_utils.get_management_net(prefix).gw()

    vm_params.initialization.host_name = VM0_NAME
    vm_params.initialization.dns_search = 'lago.local'
    vm_params.initialization.domain = 'lago.local'
    vm_params.initialization.dns_servers = gw_ip
    vm_params.initialization.nic_configurations = [
        types.NicConfiguration(
            name='eth0',
            boot_protocol=types.BootProtocol.STATIC,
            on_boot=True,
            ip=types.Ip(address=test_utils.get_vm0_ip_address(prefix),
                        netmask='255.255.255.0',
                        gateway=gw_ip))
    ]
    vm0_service = test_utils.get_vm_service(engine, VM0_NAME)
    vm0_service.start(use_cloud_init=True, vm=vm_params)

    for vm_name in [VM0_NAME, BACKUP_VM_NAME]:
        _verify_vm_state(engine, vm_name, types.VmStatus.UP)

    assert_vm0_is_alive(prefix)
Beispiel #10
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(aliases=['host'], required=True),
        bond=dict(default=None, type='dict'),
        interface=dict(default=None),
        networks=dict(default=None, type='list'),
        labels=dict(default=None, type='list'),
        check=dict(default=None, type='bool'),
        save=dict(default=None, type='bool'),
    )
    module = AnsibleModule(argument_spec=argument_spec)

    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        hosts_service = connection.system_service().hosts_service()
        host_networks_module = HostNetworksModule(
            connection=connection,
            module=module,
            service=hosts_service,
        )

        host = host_networks_module.search_entity()
        if host is None:
            raise Exception("Host '%s' was not found." % module.params['name'])

        bond = module.params['bond']
        interface = module.params['interface']
        networks = module.params['networks']
        labels = module.params['labels']
        nic_name = bond.get('name') if bond else module.params['interface']

        host_service = hosts_service.host_service(host.id)
        nics_service = host_service.nics_service()
        nic = search_by_name(nics_service, nic_name)

        network_names = [network['name'] for network in networks or []]
        state = module.params['state']
        if (state == 'present'
                and (nic is None or host_networks_module.has_update(
                    nics_service.service(nic.id)))):
            # Remove networks which are attached to different interface then user want:
            attachments_service = host_service.network_attachments_service()

            # Append attachment ID to network if needs update:
            for a in attachments_service.list():
                current_network_name = get_link_name(connection, a.network)
                if current_network_name in network_names:
                    for n in networks:
                        if n['name'] == current_network_name:
                            n['id'] = a.id

            # Check if we have to break some bonds:
            removed_bonds = []
            if nic is not None:
                for host_nic in nics_service.list():
                    if host_nic.bonding and nic.id in [
                            slave.id for slave in host_nic.bonding.slaves
                    ]:
                        removed_bonds.append(otypes.HostNic(id=host_nic.id))

            # Assign the networks:
            host_networks_module.action(
                entity=host,
                action='setup_networks',
                post_action=host_networks_module._action_save_configuration,
                check_connectivity=module.params['check'],
                removed_bonds=removed_bonds if removed_bonds else None,
                modified_bonds=[
                    otypes.HostNic(
                        name=bond.get('name'),
                        bonding=otypes.Bonding(
                            options=get_bond_options(bond.get('mode'),
                                                     bond.get('options')),
                            slaves=[
                                otypes.HostNic(name=i)
                                for i in bond.get('interfaces', [])
                            ],
                        ),
                    ),
                ] if bond else None,
                modified_labels=[
                    otypes.NetworkLabel(
                        id=str(name),
                        host_nic=otypes.HostNic(
                            name=bond.get('name') if bond else interface),
                    ) for name in labels
                ] if labels else None,
                modified_network_attachments=[
                    otypes.NetworkAttachment(
                        id=network.get('id'),
                        network=otypes.Network(
                            name=network['name']) if network['name'] else None,
                        host_nic=otypes.HostNic(
                            name=bond.get('name') if bond else interface),
                        ip_address_assignments=[
                            otypes.IpAddressAssignment(
                                assignment_method=otypes.BootProtocol(
                                    network.get('boot_protocol', 'none')),
                                ip=otypes.Ip(
                                    address=network.get('address'),
                                    gateway=network.get('gateway'),
                                    netmask=network.get('netmask'),
                                    version=otypes.IpVersion(
                                        network.get('version'))
                                    if network.get('version') else None,
                                ),
                            ),
                        ],
                    ) for network in networks
                ] if networks else None,
            )
        elif state == 'absent' and nic:
            attachments = []
            nic_service = nics_service.nic_service(nic.id)

            attached_labels = set([
                str(lbl.id)
                for lbl in nic_service.network_labels_service().list()
            ])
            if networks:
                attachments_service = nic_service.network_attachments_service()
                attachments = attachments_service.list()
                attachments = [
                    attachment for attachment in attachments if get_link_name(
                        connection, attachment.network) in network_names
                ]

            # Remove unmanaged networks:
            unmanaged_networks_service = host_service.unmanaged_networks_service(
            )
            unmanaged_networks = [(u.id, u.name)
                                  for u in unmanaged_networks_service.list()]
            for net_id, net_name in unmanaged_networks:
                if net_name in network_names:
                    if not module.check_mode:
                        unmanaged_networks_service.unmanaged_network_service(
                            net_id).remove()
                    host_networks_module.changed = True

            # Need to check if there are any labels to be removed, as backend fail
            # if we try to send remove non existing label, for bond and attachments it's OK:
            if (labels and set(labels).intersection(attached_labels)
                ) or bond or attachments:
                host_networks_module.action(
                    entity=host,
                    action='setup_networks',
                    post_action=host_networks_module.
                    _action_save_configuration,
                    check_connectivity=module.params['check'],
                    removed_bonds=[
                        otypes.HostNic(name=bond.get('name'), ),
                    ] if bond else None,
                    removed_labels=[
                        otypes.NetworkLabel(id=str(name)) for name in labels
                    ] if labels else None,
                    removed_network_attachments=attachments
                    if attachments else None,
                )

        nic = search_by_name(nics_service, nic_name)
        module.exit_json(
            **{
                'changed': host_networks_module.changed,
                'id': nic.id if nic else None,
                'host_nic': get_dict_of_struct(nic),
            })
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
 def __init__(self, version, addr, mask, gateway=None, boot_protocol=None):
     self._ip = types.Ip(addr, gateway, mask, version)
     self._boot_protocol = boot_protocol
Beispiel #12
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['present', 'absent'],
            default='present',
        ),
        name=dict(default=None, aliases=['host'], required=True),
        bond=dict(default=None, type='dict'),
        interface=dict(default=None),
        networks=dict(default=None, type='list'),
        labels=dict(default=None, type='list'),
        check=dict(default=None, type='bool'),
        save=dict(default=None, type='bool'),
    )
    module = AnsibleModule(argument_spec=argument_spec)
    check_sdk(module)

    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        hosts_service = connection.system_service().hosts_service()
        host_networks_module = HostNetworksModule(
            connection=connection,
            module=module,
            service=hosts_service,
        )

        host = host_networks_module.search_entity()
        if host is None:
            raise Exception("Host '%s' was not found." % module.params['name'])

        bond = module.params['bond']
        interface = module.params['interface']
        networks = module.params['networks']
        labels = module.params['labels']
        nic_name = bond.get('name') if bond else module.params['interface']

        nics_service = hosts_service.host_service(host.id).nics_service()
        nic = search_by_name(nics_service, nic_name)

        state = module.params['state']
        if (state == 'present'
                and (nic is None or host_networks_module.has_update(
                    nics_service.service(nic.id)))):
            host_networks_module.action(
                entity=host,
                action='setup_networks',
                post_action=host_networks_module._action_save_configuration,
                check_connectivity=module.params['check'],
                modified_bonds=[
                    otypes.HostNic(
                        name=bond.get('name'),
                        bonding=otypes.Bonding(
                            options=[
                                otypes.Option(
                                    name="mode",
                                    value=str(bond.get('mode')),
                                )
                            ],
                            slaves=[
                                otypes.HostNic(name=i)
                                for i in bond.get('interfaces', [])
                            ],
                        ),
                    ),
                ] if bond else None,
                modified_labels=[
                    otypes.NetworkLabel(
                        id=str(name),
                        host_nic=otypes.HostNic(
                            name=bond.get('name') if bond else interface),
                    ) for name in labels
                ] if labels else None,
                modified_network_attachments=[
                    otypes.NetworkAttachment(
                        network=otypes.Network(
                            name=network['name']) if network['name'] else None,
                        host_nic=otypes.HostNic(
                            name=bond.get('name') if bond else interface),
                        ip_address_assignments=[
                            otypes.IpAddressAssignment(
                                assignment_method=otypes.BootProtocol(
                                    network.get('boot_protocol', 'none')),
                                ip=otypes.Ip(
                                    address=network.get('address'),
                                    gateway=network.get('gateway'),
                                    netmask=network.get('netmask'),
                                    version=otypes.IpVersion(
                                        network.get('version'))
                                    if network.get('version') else None,
                                ),
                            ),
                        ],
                    ) for network in networks
                ] if networks else None,
            )
        elif state == 'absent' and nic:
            attachments_service = nics_service.nic_service(
                nic.id).network_attachments_service()
            attachments = attachments_service.list()
            if networks:
                network_names = [network['name'] for network in networks]
                attachments = [
                    attachment for attachment in attachments if get_link_name(
                        connection, attachment.network) in network_names
                ]
            if labels or bond or attachments:
                host_networks_module.action(
                    entity=host,
                    action='setup_networks',
                    post_action=host_networks_module.
                    _action_save_configuration,
                    check_connectivity=module.params['check'],
                    removed_bonds=[
                        otypes.HostNic(name=bond.get('name'), ),
                    ] if bond else None,
                    removed_labels=[
                        otypes.NetworkLabel(name=str(name), )
                        for name in labels
                    ] if labels else None,
                    removed_network_attachments=list(attachments),
                )

        nic = search_by_name(nics_service, nic_name)
        module.exit_json(
            **{
                'changed': host_networks_module.changed,
                'id': nic.id if nic else None,
                'host_nic': get_dict_of_struct(nic),
            })
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
Beispiel #13
0
#
# Refer to the README and COPYING files for full details of the license

from ovirtsdk4 import types


class IpVersion(object):

    V4 = types.IpVersion.V4
    V6 = types.IpVersion.V6


DYNAMIC_IP_CONFIG = [
    types.IpAddressAssignment(assignment_method=types.BootProtocol.DHCP),
    types.IpAddressAssignment(assignment_method=types.BootProtocol.DHCP,
                              ip=types.Ip(version=IpVersion.V6))
]


class IpAssignment(object):

    def __init__(self, addr, mask, gateway=None, version=IpVersion.V4,
                 boot_protocol=None):
        self._ip = types.Ip(addr, gateway, mask, version)
        self._boot_protocol = boot_protocol

    @property
    def address(self):
        return self._ip.address

    @property
Beispiel #14
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'}
Beispiel #15
0
  - content: |
      Hello, world!
    path: /tmp/greeting.txt
    permissions: '0644'
"""

# Start the virtual machine enabling cloud-init and providing the
# password for the `root` user and the network configuration:
vm_service.start(
    use_cloud_init=True,
    vm=types.Vm(initialization=types.Initialization(
        user_name='root',
        root_password='******',
        host_name='myvm.example.com',
        nic_configurations=[
            types.NicConfiguration(name='eth0',
                                   on_boot=True,
                                   boot_protocol=types.BootProtocol.STATIC,
                                   ip=types.Ip(version=types.IpVersion.V4,
                                               address='192.168.0.100',
                                               netmask='255.255.255.0',
                                               gateway='192.168.0.1'))
        ],
        dns_servers='192.168.0.1 192.168.0.2 192.168.0.3',
        dns_search='example.com',
        custom_script=my_script,
    )))

# Close the connection to the server:
connection.close()
Beispiel #16
0
vms_service = connection.system_service().vms_service()
vm = vms_service.list(search='name='+sys.argv[1])[0]

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

# Start the virtual machine enabling cloud-init and providing the
# password for the `root` user and the network configuration:
vm_service.start(
    use_cloud_init=True,
    vm=types.Vm(
        initialization=types.Initialization(
            nic_configurations=[
                types.NicConfiguration(
                    name='eth0',
                    on_boot=True,
                    boot_protocol=types.BootProtocol.STATIC,
                    ip=types.Ip(
                        version=types.IpVersion.V4,
                        address=sys.argv[2],
                        netmask='255.255.255.0'
                    )
                )
            ]
        )
    )
)

# Close the connection to the server:
connection.close()
Beispiel #17
0
def create_static_ip_config_assignment(addr, mask, gateway=None,
                                       version=IpVersion.V4):
    ip = types.Ip(address=addr, netmask=mask,
                  version=version, gateway=gateway)
    return types.IpAddressAssignment(
        assignment_method=types.BootProtocol.STATIC, ip=ip)
import ovirtsdk4.types as types
import conexion as conn
import sys

connection = conn.createconnection()

# Find the virtual machine:
vms_service = connection.system_service().vms_service()
vm = vms_service.list(search='name=' + sys.argv[1])[0]

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

# Start the virtual machine enabling cloud-init and providing the
# password for the `root` user and the network configuration:
vm_service.start(
    use_cloud_init=True,
    vm=types.Vm(initialization=types.Initialization(nic_configurations=[
        types.NicConfiguration(name='eth0',
                               on_boot=True,
                               boot_protocol=types.BootProtocol.STATIC,
                               ip=types.Ip(version=types.IpVersion.V4,
                                           address=sys.argv[2],
                                           netmask='255.255.255.0',
                                           gateway='10.6.134.50'))
    ])))

# Close the connection to the server:
connection.close()
Beispiel #19
0
                slaves=[
                    types.HostNic(name='eth1', ),
                    types.HostNic(name='eth2', ),
                ],
            ),
        ),
    ],
    modified_network_attachments=[
        types.NetworkAttachment(
            network=types.Network(name='mynetwork', ),
            host_nic=types.HostNic(name='bond0', ),
            ip_address_assignments=[
                types.IpAddressAssignment(
                    assignment_method=types.BootProtocol.STATIC,
                    ip=types.Ip(
                        address='192.168.122.100',
                        netmask='255.255.255.0',
                    ),
                ),
            ],
        ),
    ],
)

# After modifying the network configuration it is very important to make it
# persistent:
host_service.commit_net_config()

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