summaryrefslogtreecommitdiff
path: root/roles/vm-install
diff options
context:
space:
mode:
Diffstat (limited to 'roles/vm-install')
-rw-r--r--roles/vm-install/library/wait_for_virt.py176
-rw-r--r--roles/vm-install/tasks/main.yaml110
-rw-r--r--roles/vm-install/templates/libvirt-domain.xml.j270
-rw-r--r--roles/vm-install/templates/preseed_stretch.cfg.j2101
4 files changed, 457 insertions, 0 deletions
diff --git a/roles/vm-install/library/wait_for_virt.py b/roles/vm-install/library/wait_for_virt.py
new file mode 100644
index 00000000..b5e244ef
--- /dev/null
+++ b/roles/vm-install/library/wait_for_virt.py
@@ -0,0 +1,176 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import, division, print_function
+__metaclass__ = type
+
+
+import traceback
+import time
+
+try:
+ import libvirt
+except ImportError:
+ HAS_VIRT = False
+else:
+ HAS_VIRT = True
+
+from ansible.module_utils.basic import AnsibleModule
+from ansible.module_utils._text import to_native
+
+
+VIRT_FAILED = 1
+VIRT_SUCCESS = 0
+VIRT_UNAVAILABLE=2
+
+VIRT_STATE_NAME_MAP = {
+ 0 : "running",
+ 1 : "running",
+ 2 : "running",
+ 3 : "paused",
+ 4 : "shutdown",
+ 5 : "shutdown",
+ 6 : "crashed"
+}
+
+class VMNotFound(Exception):
+ pass
+
+class LibvirtConnection(object):
+
+ def __init__(self, uri, module):
+
+ self.module = module
+
+ cmd = "uname -r"
+ rc, stdout, stderr = self.module.run_command(cmd)
+
+ if "xen" in stdout:
+ conn = libvirt.open(None)
+ elif "esx" in uri:
+ auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT], [], None]
+ conn = libvirt.openAuth(uri, auth)
+ else:
+ conn = libvirt.open(uri)
+
+ if not conn:
+ raise Exception("hypervisor connection failure")
+
+ self.conn = conn
+
+ def find_vm(self, vmid):
+ """
+ Extra bonus feature: vmid = -1 returns a list of everything
+ """
+ conn = self.conn
+
+ vms = []
+
+ # this block of code borrowed from virt-manager:
+ # get working domain's name
+ ids = conn.listDomainsID()
+ for id in ids:
+ vm = conn.lookupByID(id)
+ vms.append(vm)
+ # get defined domain
+ names = conn.listDefinedDomains()
+ for name in names:
+ vm = conn.lookupByName(name)
+ vms.append(vm)
+
+ if vmid == -1:
+ return vms
+
+ for vm in vms:
+ if vm.name() == vmid:
+ return vm
+
+ raise VMNotFound("virtual machine %s not found" % vmid)
+
+ def get_status(self, vmid):
+ state = self.find_vm(vmid).info()[0]
+ return VIRT_STATE_NAME_MAP.get(state,"unknown")
+
+
+class Virt(object):
+
+ def __init__(self, uri, module):
+ self.module = module
+ self.uri = uri
+
+ def __get_conn(self):
+ self.conn = LibvirtConnection(self.uri, self.module)
+ return self.conn
+
+ def status(self, vmid):
+ """
+ Return a state suitable for server consumption. Aka, codes.py values, not XM output.
+ """
+ self.__get_conn()
+ return self.conn.get_status(vmid)
+
+def core(module):
+
+ states = module.params.get('states', None)
+ guest = module.params.get('name', None)
+ uri = module.params.get('uri', None)
+ delay = module.params.get('delay', None)
+ sleep = module.params.get('sleep', None)
+ timeout = module.params.get('timeout', None)
+
+ v = Virt(uri, module)
+ res = {'changed': False}
+
+ if delay > 0:
+ time.sleep(delay)
+
+ for _ in range(0, timeout, sleep):
+ state = v.status(guest)
+ if state in states:
+ res['state'] = state
+ res['msg'] = "guest '%s' has reached state: %s" % (guest, state)
+ return VIRT_SUCCESS, res
+
+ time.sleep(sleep)
+
+ res['failed'] = True
+ res['msg'] = "timeout waiting for guest '%s' to reach one of states: %s" % (guest, ', '.join(states))
+ return VIRT_FAILED, res
+
+
+def main():
+
+ module = AnsibleModule(argument_spec=dict(
+ name = dict(aliases=['guest'], required=True),
+ states = dict(type='list', required=True),
+ uri = dict(default='qemu:///system'),
+ delay=dict(type='int', default=0),
+ sleep=dict(type='int', default=1),
+ timeout=dict(type='int', default=300),
+ ))
+
+ if not HAS_VIRT:
+ module.fail_json(
+ msg='The `libvirt` module is not importable. Check the requirements.'
+ )
+
+ for state in module.params.get('states', None):
+ if state not in set(VIRT_STATE_NAME_MAP.values()):
+ module.fail_json(
+ msg="states contains invalid state '%s', must be one of %s" % (state, ', '.join(set(VIRT_STATE_NAME_MAP.values())))
+ )
+
+ rc = VIRT_SUCCESS
+ try:
+ rc, result = core(module)
+ except Exception as e:
+ module.fail_json(msg=to_native(e), exception=traceback.format_exc())
+
+ if rc != 0: # something went wrong emit the msg
+ module.fail_json(rc=rc, msg=result)
+ else:
+ module.exit_json(**result)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/roles/vm-install/tasks/main.yaml b/roles/vm-install/tasks/main.yaml
new file mode 100644
index 00000000..214db25a
--- /dev/null
+++ b/roles/vm-install/tasks/main.yaml
@@ -0,0 +1,110 @@
+---
+- name: generate preseed file
+ template:
+ src: "preseed_{{ vmdistro }}.cfg.j2"
+ dest: "/home/rhadmin/ansible/preseed/vm-{{ inventory_hostname }}-{{ vmdistro }}.cfg"
+ owner: rhadmin
+ group: rhadmin
+ delegate_to: ansible
+
+- name: create disks for vm
+ with_dict: "{{ vm_install.disks.virtio | default({}) | combine(vm_install.disks.scsi | default({})) }}"
+ lvol:
+ vg: "{{ item.value.vg }}"
+ lv: "{{ item.value.lv }}"
+ size: "{{ item.value.size }}"
+ delegate_to: "{{ vm_install.host }}"
+
+- name: check if vm already exists
+ virt:
+ name: "{{ inventory_hostname }}"
+ command: info
+ delegate_to: "{{ vm_install.host }}"
+ register: vmhost_info
+
+- name: destroy exisiting vm
+ virt:
+ name: "{{ inventory_hostname }}"
+ state: destroyed
+ delegate_to: "{{ vm_install.host }}"
+ when: inventory_hostname in vmhost_info
+
+- name: wait for vm to be destroyed
+ wait_for_virt:
+ name: "{{ inventory_hostname }}"
+ states: shutdown,crashed
+ timeout: 5
+ delegate_to: "{{ vm_install.host }}"
+ when: inventory_hostname in vmhost_info
+
+- name: undefining exisiting vm
+ virt:
+ name: "{{ inventory_hostname }}"
+ command: undefine
+ delegate_to: "{{ vm_install.host }}"
+ when: inventory_hostname in vmhost_info
+
+- name: enable installer in VM config
+ set_fact:
+ run_installer: True
+
+- name: define new installer vm
+ virt:
+ name: "{{ inventory_hostname }}"
+ command: define
+ xml: "{{ lookup('template', 'libvirt-domain.xml.j2') }}"
+ delegate_to: "{{ vm_install.host }}"
+
+- name: start vm
+ virt:
+ name: "{{ inventory_hostname }}"
+ state: running
+ delegate_to: "{{ vm_install.host }}"
+
+- name: wait for installer to start
+ wait_for_virt:
+ name: "{{ inventory_hostname }}"
+ states: running
+ timeout: 10
+ delegate_to: "{{ vm_install.host }}"
+
+- debug:
+ msg: "you can check on the status of the installer running this command 'virsh console {{ inventory_hostname }}' on host {{ vm_install.host }}."
+
+- name: wait for installer to finish or crash
+ wait_for_virt:
+ name: "{{ inventory_hostname }}"
+ states: shutdown,crashed
+ timeout: 600
+ delegate_to: "{{ vm_install.host }}"
+ register: installer_result
+ failed_when: installer_result.state == "crashed"
+
+- name: undefining installer vm
+ virt:
+ name: "{{ inventory_hostname }}"
+ command: undefine
+ delegate_to: "{{ vm_install.host }}"
+
+- name: disable installer in VM config
+ set_fact:
+ run_installer: False
+
+- name: define new production vm
+ virt:
+ name: "{{ inventory_hostname }}"
+ command: define
+ xml: "{{ lookup('template', 'libvirt-domain.xml.j2') }}"
+ delegate_to: "{{ vm_install.host }}"
+
+- name: start vm
+ virt:
+ name: "{{ inventory_hostname }}"
+ state: running
+ autostart: "{{ vm_install.autostart | default(omit) }}"
+ delegate_to: "{{ vm_install.host }}"
+
+- name: wait for vm to start up
+ wait_for_connection:
+ delay: 5
+ timeout: 120
diff --git a/roles/vm-install/templates/libvirt-domain.xml.j2 b/roles/vm-install/templates/libvirt-domain.xml.j2
new file mode 100644
index 00000000..c95019eb
--- /dev/null
+++ b/roles/vm-install/templates/libvirt-domain.xml.j2
@@ -0,0 +1,70 @@
+<domain type='kvm'>
+ <name>{{ inventory_hostname }}</name>
+ <memory>{{ vm_install.mem * 1024 }}</memory>
+ <currentMemory>{{ vm_install.mem * 1024 }}</currentMemory>
+ <vcpu>{{ vm_install.numcpu }}</vcpu>
+ <os>
+ <type arch='x86_64' machine='pc-0.12'>hvm</type>
+{% if run_installer %}
+ <kernel>/home/rhadmin/installer/{{ vmdistro }}/{{ vm_install.arch | default('amd64') }}/linux</kernel>
+ <initrd>/home/rhadmin/installer/{{ vmdistro }}/{{ vm_install.arch | default('amd64') }}/initrd.gz</initrd>
+ <cmdline>console=ttyS0,115200n8 auto=true interface=auto url=http://ansible.helsinki.at/preseed/vm-{{ inventory_hostname }}-{{ vmdistro }}.cfg netcfg/choose_interface=enp1s1 netcfg/disable_autoconfig=true netcfg/get_ipaddress={{ srv_network.internal.ip }} netcfg/get_netmask=255.255.255.0 netcfg/get_gateway=192.168.1.254 netcfg/get_nameservers=192.168.1.254 netcfg/confirm_static=true netcfg/get_hostname={{ inventory_hostname }} netcfg/get_domain=helsinki.at</cmdline>
+{% endif %}
+ <boot dev='hd'/>
+ </os>
+ <features>
+ <acpi/>
+ <apic/>
+ <pae/>
+ </features>
+ <clock offset='utc'/>
+ <on_poweroff>destroy</on_poweroff>
+{% if run_installer %}
+ <on_reboot>destroy</on_reboot>
+ <on_crash>destroy</on_crash>
+{% else %}
+ <on_reboot>restart</on_reboot>
+ <on_crash>restart</on_crash>
+{% endif %}
+ <devices>
+ <emulator>/usr/bin/kvm</emulator>
+
+{% if 'virtio' in vm_install.disks %}
+{% for device, lv in vm_install.disks.virtio.items() %}
+ <disk type='block' device='disk'>
+ <driver name='qemu' type='raw' cache='none' discard='unmap'/>
+ <source dev='/dev/mapper/{{ lv.vg }}-{{ lv.lv }}'/>
+ <target dev='{{ device }}' bus='virtio'/>
+ </disk>
+{% endfor %}
+{% endif %}
+
+{% if 'scsi' in vm_install.disks %}
+ <controller type='scsi' index='0' model='virtio-scsi'/>
+{% for device, lv in vm_install.disks.scsi.items() %}
+ <disk type='block' device='disk'>
+ <driver name='qemu' type='raw' cache='none' discard='unmap'/>
+ <source dev='/dev/mapper/{{ lv.vg }}-{{ lv.lv }}'/>
+ <target dev='{{ device }}' bus='scsi'/>
+ </disk>
+{% endfor %}
+{% endif %}
+
+{% if vm_install.interfaces %}
+{% for if in vm_install.interfaces %}
+ <interface type='bridge'>
+ <source bridge='{{ if.bridge }}'/>
+ <model type='virtio'/>
+ <address type='pci' domain='0x0000' bus='0x01' slot='0x0{{ if.idx }}' function='0x0'/>
+ </interface>
+{% endfor %}
+{% endif %}
+
+ <serial type='pty'>
+ <target port='0'/>
+ </serial>
+ <console type='pty'>
+ <target type='serial' port='0'/>
+ </console>
+ </devices>
+</domain>
diff --git a/roles/vm-install/templates/preseed_stretch.cfg.j2 b/roles/vm-install/templates/preseed_stretch.cfg.j2
new file mode 100644
index 00000000..b197395e
--- /dev/null
+++ b/roles/vm-install/templates/preseed_stretch.cfg.j2
@@ -0,0 +1,101 @@
+#########################################################################
+# Radio Helsinki preseed file for Debian stretch based VMs
+#########################################################################
+
+d-i debian-installer/language string en
+d-i debian-installer/country string AT
+d-i debian-installer/locale string de_AT.UTF-8
+d-i keyboard-configuration/xkb-keymap select de
+
+
+#d-i netcfg/choose_interface select enp1s1
+#d-i netcfg/disable_autoconfig boolean false
+#d-i netcfg/get_ipaddress string {{ srv_network.internal.ip }}
+#d-i netcfg/get_netmask string 255.255.255.0
+#d-i netcfg/get_gateway string 192.168.1.254
+#d-i netcfg/get_nameservers string 192.168.1.254
+#d-i netcfg/confirm_static boolean true
+
+d-i netcfg/get_hostname string {{ inventory_hostname }}
+d-i netcfg/get_domain string helsinki.at
+d-i netcfg/wireless_wep string
+
+
+d-i mirror/country string manual
+d-i mirror/http/hostname string apt
+d-i mirror/http/directory string /debian
+d-i mirror/http/proxy string
+
+
+d-i passwd/make-user boolean false
+d-i passwd/root-password password this-very-very-secure-password-will-be-removed-by-latecommand
+d-i passwd/root-password-again password this-very-very-secure-password-will-be-removed-by-latecommand
+
+
+d-i clock-setup/utc boolean true
+d-i time/zone string Europe/Vienna
+d-i clock-setup/ntp boolean false
+
+
+d-i partman-auto/disk string /dev/{{ vm_install.disks.primary }}
+d-i partman-auto/method string lvm
+d-i partman-lvm/device_remove_lvm boolean true
+d-i partman-md/device_remove_md boolean true
+
+d-i partman-lvm/confirm boolean true
+d-i partman-lvm/confirm_nooverwrite boolean true
+
+d-i partman-auto/expert_recipe string \
+ boot-root :: \
+ 1000 10000 -1 ext4 \
+ $defaultignore{ } $primary{ } $bootable{ } \
+ method{ lvm } vg_name{ {{ inventory_hostname }} } \
+ . \
+ 1536 10000 2048 ext4 \
+ $lvmok{ } in_vg{ {{ inventory_hostname }} } \
+ lv_name { root } \
+ method{ format } format{ } \
+ use_filesystem{ } filesystem{ ext4 } \
+ mountpoint{ / } \
+ . \
+ 1024 11000 1280 ext4 \
+ $lvmok{ } in_vg{ {{ inventory_hostname }} } \
+ lv_name { var } \
+ method{ format } format{ } \
+ use_filesystem{ } filesystem{ ext4 } \
+ mountpoint{ /var } \
+ . \
+ 768 10000 768 ext4 \
+ $lvmok{ } in_vg{ {{ inventory_hostname }} } \
+ lv_name { varlog } \
+ method{ format } format{ } \
+ use_filesystem{ } filesystem{ ext4 } \
+ mountpoint{ /var/log } \
+ options/nodev{ nodev } options/noatime{ noatime } \
+ options/noexec{ noexec } \
+ .
+
+d-i partman-auto-lvm/no_boot boolean true
+d-i partman-basicfilesystems/no_swap true
+d-i partman-partitioning/confirm_write_new_label boolean true
+d-i partman/choose_partition select finish
+d-i partman/confirm boolean true
+d-i partman/confirm_nooverwrite boolean true
+
+
+d-i base-installer/install-recommends boolean false
+d-i apt-setup/security_host string apt
+
+tasksel tasksel/first multiselect
+d-i pkgsel/include string openssh-server python
+d-i pkgsel/upgrade select safe-upgrade
+popularity-contest popularity-contest/participate boolean false
+
+d-i grub-installer/choose_bootdev string /dev/{{ vm_install.disks.primary }}
+d-i grub-installer/only_debian boolean true
+d-i grub-installer/with_other_os boolean false
+
+d-i finish-install/reboot_in_progress note
+
+
+d-i preseed/late_command string in-target bash -c "passwd -d root; passwd -l root; umask 077; mkdir -p /root/.ssh/; echo 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDSWnaaAe6PwzB+XaU4kLUnc7BaUbg6wtgLv3M9JkUix ansible config-management' > /root/.ssh/authorized_keys"