ansible creates vmware virtual machine

Keywords: Linux Vmware ansible Python

Environment: vmware virtualization
Requirements: Business departments need dozens or even hundreds of virtual machines at a time

In the past, no matter this area, temporary needs have to be met due to the reduction of personnel.

Use ansible vmware_guest to create virtual machines, avoiding manual one-by-one creation of pure manual work
Don't talk too much nonsense. Code it.

---
- hosts: localhost   ## Execute locally
  gather_facts: No
  connection: local  ## Local connection
  vars_files:
    - myvars.yml
    - vcenter.yml
  tasks:
  - name: Create a virtual machine on given ESXi hostname
    vmware_guest:
      hostname: "{{hostname}}"
      username: "{{username}}"
      password: "{{password}}"
      validate_certs: no
      folder: /
      datacenter: "{{datacenter}}"
      name: "{{item.name}}"
      state: poweredoff
      guest_id: centos64Guest
      esxi_hostname: "{{item.esxi_hostname}}"
      disk:
      - size_gb: "{{ item.d1_size_gb}}"
        type: eagerzeroedthick    ##Thick thin and Simplified thin
        datastore: "{{item.datastore}}"  ##storage
      - size_gb: "{{ item.d2_size_gb}}"
        #type: eagerzeroedthick
        type: thin
        datastore: "{{item.datastore}}"
      hardware:
        hotadd_cpu: true
        hotremove_cpu: true
        hotadd_memory: true
        memory_mb: "{{item.memory_mb}}"
        num_cpus: "{{item.num_cpus}}"
        scsi: lsilogic  ##linux uses lsilogic, win uses lsilogicsas, and paravirtual by default is VMware's own quasi-virtual
      networks:
      - name: vlan10  ##net name
        device_type: vmxnet3  ## win uses e1000e
    with_items:
      - "{{myvms}}"
    delegate_to: localhost
    register: deploy_vm

vcenter.yml stores vcenter verification information
myvars.yml is the virtual machine information that needs to be created
The myvars.yml example is as follows

---
datacenter: zm-A10  
myvms:
 - { name: 10.20.15.99_test1, esxi_hostname: 10.20.10.26, datastore: 10-26-localradi10, d1_size_gb: 50, d2_size_gb: 30, memory_mb: 8196, num_cpus: 4 }
 - { name: 10.20.15.105_test2, esxi_hostname: 10.20.10.23, datastore: 10_23-localraid10, d1_size_gb: 50, d2_size_gb: 40, memory_mb: 8196, num_cpus: 4 }

myvars.yml can be generated directly with Python scripts

import re

outfile2 = open('myvars.yml', 'w')
file_head = ''' 
---
datacenter: zm-A10
myvms:
'''
outfile2.write(file_head)
with open('vm_list', 'r') as f:
    while 1:
        line = f.readline()
        if not line:
            break
        linetest = re.split(r'[;,\s]+', line)
        host2text = ''' - { name: %s_%s, esxi_hostname: %s, datastore: %s, d1_size_gb: %s, d2_size_gb: %s, memory_mb: %s, num_cpus: %s }''' % (linetest[0], linetest[1], linetest[2], linetest[3], linetest[6], linetest[7], linetest[5], linetest[4])
        print >> outfile2, host2text

Posted by magic-eyes on Sat, 02 Feb 2019 18:57:15 -0800