Automating VM Deployment in VMware vSphere with Ansible

This post aimed to provide a clear understanding of how the Ansible playbook functions for creating multiple VMs in a VMware vSphere environment.

· 4 min read
Automating VM Deployment in VMware vSphere with Ansible

Whether you're deploying a handful of virtual machines (VMs) or managing a large-scale virtual environment, automation tools like Ansible can significantly reduce manual overhead, minimize errors, and ensure consistency across your infrastructure. Today, we'll explore an Ansible playbook designed to automate the deployment of multiple VMs in a VMware vSphere environment, complete with specified names and hostnames.

If you want to know more about Ansible, you can read this short post, I made it easy for you not looking around 😄
What is Ansible?
I’ve been tired of cloning my Ubuntu template to build again and again some Docker Swarm and Kubernetese node so I was looking for a quick and cheap way to automate these tasks. This is an ideal tool for homelab, it’s lightweight and free !

and if you want to install Ansible, which is fairly easy you can head over here :

Installing Ansible on Ubuntu
Quick post to run through Ansible installation on an Ubuntu OS.

Understanding the Playbook

This playbook is composed of a series of tasks executed on localhost, targeting a VMware vSphere environment to create VMs based on a specified template. It's ideal for scenarios where consistent VM configuration is needed, such as setting up a series of test environments or deploying multiple VMs for a new project.

Here's an overview of the playbook structure and its key components:

  • Hosts: The playbook runs on localhost since it interacts directly with the VMware vSphere API, rather than running commands on a remote host.
  • Variables: Essential for customization, variables in this playbook include vCenter details (vcenter_server, vcenter_username, vcenter_password), the target datacenter, datastore, network, and resource pool, as well as the VM template to use. Additionally, it defines a naming convention for the VMs to be created.
  • Tasks: The playbook includes two main tasks. The first task creates the VMs using the vmware_guest module, and the second sets the hostnames for each VM, tailoring them to specific needs.

To run this playbook :

ansible-playbook NameOfTheFileYouWant.yaml

Here is the playbook

---
- name: Create multiple VMs with specified names and hostnames
  hosts: localhost
  gather_facts: no
  vars:
    vcenter_server: "vcenter.example.com"
    vcenter_username: "administrator@vsphere.local"
    vcenter_password: "Password123!"
    datacenter: "DC1"
    datastore: "DS1"
    network: "VM Network"
    resource_pool: "Resources/compute-resource-pool"
    template: "centos7-template"
    vm_name_prefix: "testvm"
    vm_count: 5
    vm_hostname_suffix: ".example.com"
    esxi_host: "esxi01.example.com"

  tasks:
    - name: Create virtual machines with specified names and hostnames
      vmware_guest:
        hostname: "{{ vcenter_server }}"
        username: "{{ vcenter_username }}"
        password: "{{ vcenter_password }}"
        validate_certs: no
        datacenter: "{{ datacenter }}"
        folder: "/"
        name: "{{ vm_name_prefix }}-{{ item }}"
        state: present
        template: "{{ template }}"
        cluster: "{{ resource_pool }}"
        datastore: "{{ datastore }}"
        disk:
          - size_gb: 20
            type: thin
        network_interfaces:
          - network: "{{ network }}"
            type: "e1000"
        hardware:
          memory_mb: 2048
          num_cpus: 2
      register: vm_facts
      delegate_to: localhost
      with_sequence: start=1 end={{ vm_count }}

    - name: Set hostnames for virtual machines
      vmware_guest:
        hostname: "{{ vcenter_server }}"
        username: "{{ vcenter_username }}"
        password: "{{ vcenter_password }}"
        validate_certs: no
        name: "{{ vm_name_prefix }}-{{ item }}{{ vm_hostname_suffix }}"
        customization:
          hostname: "{{ vm_name_prefix }}-{{ item }}"
        state: present
      delegate_to: localhost
      with_sequence: start=1 end={{ vm_count }}

Breaking Down the Tasks

Task 1: Create Virtual Machines

The first task uses the vmware_guest module, a powerful tool for managing VMs in vSphere environments. It specifies the connection details to the vCenter server and sets various VM parameters such as the datacenter, datastore, and template to use. Importantly, it iterates over a defined range (vm_count), creating multiple VMs according to the naming convention (vm_name_prefix and sequence number).

This task also configures each VM's disk size and type, network interface, and hardware specifications, including memory and CPU count, ensuring each VM is provisioned with the desired resources.

Task 2: Set Hostnames

After creating the VMs, the playbook sets their hostnames using the same vmware_guest module, this time focusing on customization. By specifying the hostname for each VM, it ensures that the VMs are not only created but also individually recognizable and configurable within the network, matching the specified naming convention (vm_name_prefix, sequence number, and vm_hostname_suffix).

Key Features and Flexibility

This playbook demonstrates several best practices and features of Ansible:

  • Idempotency: Running the playbook multiple times won't create additional VMs unnecessarily. Instead, it ensures the desired state is maintained.
  • Scalability: By adjusting the vm_count variable, you can control the number of VMs created, making the playbook scalable to the project's needs.
  • Customization: Through variables and Ansible's templating capabilities, the playbook can be easily customized for different environments or requirements.

before using this playbook, you need to have the vmware_guest module installed, you can do it with this command line :

ansible-galaxy collection install community.vmware

Final Thoughts

By automating VM deployment with Ansible, organizations can achieve more with less effort, reduce the potential for human error, and ensure a consistent and repeatable process for infrastructure provisioning. This playbook serves as a foundation for automating VM creation in VMware vSphere environments, illustrating the power and flexibility of Ansible in managing modern IT infrastructure.

As with any automation, testing in a non-production environment is crucial before rolling out to production, ensuring that the playbook performs as expected in your specific environment.