There are lots of ways to enable self-service VMs within an organisation - what some might call 'a private cloud'. However, these usually require layers and layers of complex software. What if you could leverage your existing hypervisor and 15 lines of code to do the same? And what if those 15 lines became an even simpler single click?

Ansible Core contains a module for managing virtual machines in VMware vSphere environments called vsphere_guest. Using this one module we can talk to an existing vSphere instance to create new VMs, clone VM templates, and control and delete VMs. Couple up a simple playbook with Ansible Tower and we can do some pretty amazing things with very little effort.

Here's our playbook to create a new virtual machine from a template in vSphere:

- hosts: vmcreate
  gather_facts: false
  connection: local
  vars:
    vcenter_hostname: 10.10.10.1
    esxhost: 10.10.20.1
    datastore: NFS001
    network: VLAN001
    vmtemplate: CentOS7
    vmcluster: AppsDev
    notes: Created by Ansible
  tasks:
    - name: Check for required variables
      fail: msg="Must pass name to -e"
      when: name is not defined

    - name: Check for vSphere access parameters
      fail: msg="Must set vcenter_user and vcenter_pass in a Vault"
      when: (vcenter_user is not defined) or (vcenter_pass is not defined)

    - name: Create VM from template
      vsphere_guest:
        vcenter_hostname: "{{ vcenter_hostname }}"
        username: "{{ vcenter_user }}"
        password: "{{ vcenter_pass }}"
        guest: "{{ name }}"
        from_template: yes
        template_src: "{{ vmtemplate }}"
        cluster: "{{ vmcluster  }}"
        resource_pool: "/Resources"
        vm_extra_config:
          notes: "{{ notes }}"
        esxi:
          datacenter: Dev
          hostname: "{{ esxhost }}"

The really important bit that's doing the work is the 15 lines associated with the 'Create VM from template' task. Note the extensive use of variables in this play to give us lots of flexibility. We'll make use of this in Tower in just a moment.

Tower 2.1 introduced 'Surveys', which are a great way to create interactive forms for a given play. The form can prompt for variable information to make running a flexible play simpler:

Setting up multiple choice questions is also really easy:

Here's a short video of the Job Templates in action:

There are many more ways to extend this simple functionality - Tower's job scheduler could automatically run a play to 'scavenge' unused VMs, for example (put a fact on the host to say it's done with, and you protect against automatically killing a VM still in use).

(This post originally appeared on ansible.com)


Comments

comments powered by Disqus