Skip to content

Instantly share code, notes, and snippets.

@sky-joker sky-joker/clone_vm.yml
Last active Mar 22, 2019

Embed
What would you like to do?
ESXi single clone vm sample playbook(ref: http://ur2.link/vIFg)
---
- name: ESXi single clone vm demo
hosts: all
gather_facts: no
vars:
vm_password: !vault |
$ANSIBLE_VAULT;1.1;AES256
(snip)
tasks:
- name: Get datastore infomation
vmware_datastore_facts:
hostname: "{{ vm_hostname }}"
username: "{{ vm_username }}"
password: "{{ vm_password }}"
validate_certs: no
datacenter: ha-datacenter
delegate_to: localhost
register: datastore_result
- name: Set datastore path variable
set_fact:
datastore_path: "{{ item.url }}"
loop: "{{ datastore_result.datastores }}"
when: item.name == datastore
- block:
- name: Create a directory to store virtual machines
file:
path: "{{ datastore_path }}/{{ item.name }}"
state: directory
loop: "{{ clone_vms }}"
- name: Copy vmdk file(Multiple file support)
shell: >-
for vmdk in $(find {{ datastore_path }}/{{ source_vm }} -name "*.vmdk" | grep -v flat | awk -F / '{print $(NF)}') ; do
rename_vmdk=`echo $vmdk | sed -e "s/{{ source_vm}}\(.*\)/{{ item.name }}\1/g"`
vmkfstools -i {{ datastore_path }}/{{ source_vm }}/$vmdk -d {{ disk_type }} {{ datastore_path }}/{{ item.name }}/$rename_vmdk
done
loop: "{{ clone_vms }}"
- name: Copy vmx file
copy:
src: "{{ datastore_path }}/{{ source_vm }}/{{ source_vm }}.vmx"
dest: "{{ datastore_path }}/{{ item.name }}/{{ item.name }}.vmx"
remote_src: yes
loop: "{{ clone_vms }}"
- name: Replace vmx file parameter
replace:
path: "{{ datastore_path }}/{{ item.name }}/{{ item.name }}.vmx"
regexp: "{{ source_vm }}(\\.vmdk|\\.nvram|\"$)"
replace: "{{ item.name }}\\1"
loop: "{{ clone_vms }}"
- name: Register VM to inventory
vmware_guest_register_operation:
hostname: "{{ vm_hostname }}"
username: "{{ vm_username }}"
password: "{{ vm_password }}"
validate_certs: no
esxi_hostname: "{{ esxi_hostname }}"
name: "{{ item.name }}"
path: "[NFS] {{ item.name }}/{{ item.name }}.vmx"
state: present
delegate_to: localhost
loop: "{{ clone_vms }}"
- name: VM power operation
vmware_guest_powered_on_operation_question:
hostname: "{{ vm_hostname }}"
username: "{{ vm_username }}"
password: "{{ vm_password }}"
validate_certs: no
name: "{{ item.name }}"
state: poweredon
delegate_to: localhost
loop: "{{ clone_vms }}"
when: datastore_path is defined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.