ansible创建vmware虚拟机

时间:2022-04-23 00:04:24

环境:vmware 虚拟化
需求:如果业务部门一次提几十台甚至几百台虚拟机需求,一个个的手动创建肯定耗时

使用ansible vmware_guest 创建虚拟机,避免手动一台一台创建的纯手工 工作
废话不多说,上代码

---
- hosts: localhost ## 在本机执行
gather_facts: No
connection: local ## 本地连接
vars_files:
- myvars.yml
- vcenter.yml
tasks:
- name: Create a virtual machine from a template
vmware_guest:
hostname: "{{hostname}}"
username: "{{username}}"
password: "{{password}}"
validate_certs: no
folder: /
datacenter: "{{datacenter}}"
name: "{{item.name}}"
state: poweredon
esxi_hostname: "{{item.esxi_hostname}}"
template: "{{item.sys_ver}}"
disk:
- size_gb: 51
type: eagerzeroedthick ## eagerzeroedthick厚置备零延迟 thin 精简置备
datastore: "{{item.datastore}}" ##存储
- size_gb: "{{ item.d2_size_gb}}"
#type: eagerzeroedthick
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用lsilogic,win用lsilogicsas, 默认使用paravirtual 这是VMware自己的准虚拟
networks:
- name: "{{item.vlan}}" ##网络名
device_type: vmxnet3 ## win使用e1000e
ip: "{{item.ip}}"
netmask: 255.255.255.0
gateway: "{{item.gw}}"
customization:
hostname: "{{item.hostname}}"
dns_servers:
- "{{item.dns1}}"
- "{{item.dns2}}"
with_items:
- "{{myvms}}"
delegate_to: localhost
register: deploy

  

vcenter.yml 存放vcenter验证信息
myvars.yml 是需要创建的虚拟机信息
myvars.yml 示例如下

 ---
datacenter: zm-A10
myvms: - name: x.x.x.x_xx
esxi_hostname: x.x.x.x
datastore: x
d1_size_gb: 50
d2_size_gb: 100
memory_mb: 16384
num_cpus: 8
ip:
gw:
dns1:
dns2:
vlan: vlan14
hostname: xxxx
sys_ver: centos6_moban - name: xxx
esxi_hostname: xx
datastore: xx
d1_size_gb: 50
d2_size_gb: 100
memory_mb: 8192
num_cpus: 4
ip:
gw:
dns1:
dns2:
vlan: vlan14
hostname: x
sys_ver: centos7_moban

  

myvars.yml 可以直接用Python脚本生成

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)
if linetest[12] is not None and linetest[12] != '' and linetest[12] == 'centos6':
sys_version = 'centos6_moban'
elif linetest[12] is not None and linetest[12] != '' and linetest[12] == 'centos7':
sys_version = 'centos7_moban'
else:
sys_version = 'win2012_moban'
if linetest[5] is not None and linetest[5].isdigit():
memory = int(linetest[5]) * 1024
host2text = '''
- name: {0}_{1}
esxi_hostname: {2}
datastore: {3}
d1_size_gb: {4}
d2_size_gb: {5}
memory_mb: {6}
num_cpus: {7}
ip: {8}
gw: {9}
dns1: {10}
dns2: {11}
vlan: {12}
hostname: {13}
sys_ver: {14}'''.format(linetest[0], linetest[1], linetest[2], linetest[3], linetest[6], linetest[7], memory, linetest[4], linetest[0], linetest[8], linetest[9], linetest[10], linetest[11], linetest[1], sys_version)
print >> outfile2, host2text