Here we are looking on how to use Ansible to connect to vCenters and manage VMs. The focus will be on using quick playbooks for cloning and deleting a current template VM.
We can see the playbook for the creation process for cloning and deleting VMs. The playbook creation process will involve setting up variables, tasks, and handlers, and will be broken down into simple, easy-to-follow steps. Sample playbooks will be provided as a starting point for managing VMs in vCenter using Ansible.
Clone a VM in Vcenter with Ansible Playbook
- hosts: localhost
gather_facts: no
vars:
vcenter_server: "xxx.xxx.xxx.xxx"
vcenter_user: "User-Name"
vcenter_pass: "Password"
datacenter_name: "DC-Name"
cluster_name: "xxx.xxx.xxx.xxx"
resources_pool: "RG-Name"
template_vm: "Template-Name"
serv:
- vm1
- vm2
tasks:
- name: Clone the template
vmware_guest:
hostname: "{{ vcenter_server }}"
username: "{{ vcenter_user }}"
password: "{{ vcenter_pass }}"
resource_pool: "rahul-test"
validate_certs: False
name: "{{ item }}"
template: "{{ template_vm }}"
datacenter: "{{ datacenter_name }}"
folder: /{{ datacenter_name }}/vm
state: poweredon
wait_for_ip_address: yes
register: "r"
with_items: "{{ serv }}"
- debug :
msg: "This is the Host-IPs: {{ item.instance.ipv4 }} {{ item.instance.hw_name }}"
with_items: "{{ r.results}}"
loop_control:
label: "{{ item.instance.hw_name }}"
Shutdown a VM in Vcenter with Ansible Playbook
- hosts: localhost
gather_facts: no
vars:
vcenter_server: "xxx.xxx.xxx.xxx"
vcenter_user: "User-Name"
vcenter_pass: "Password"
datacenter_name: "DC-Name"
cluster_name: "xxx.xxx.xxx.xxx"
tasks:
- name: Shutdown the template
vmware_guest:
hostname: "{{ vcenter_server }}"
username: "{{ vcenter_user }}"
password: "{{ vcenter_pass }}"
validate_certs: False
name: "{{ item}}"
datacenter: "{{ datacenter_name }}"
folder: /{{ datacenter_name }}/vm
state: poweredoff
wait_for_ip_address: yes
loop:
Delete a VM in Vcenter with Ansible Playbook
- hosts: localhost
gather_facts: no
vars:
vcenter_server: "xxx.xxx.xxx.xxx"
vcenter_user: "User-Name"
vcenter_pass: "Password"
datacenter_name: "DC-Name"
cluster_name: "xxx.xxx.xxx.xxx"
tasks:
- name: Delete the template
vmware_guest:
hostname: "{{ vcenter_server }}"
username: "{{ vcenter_user }}"
password: "{{ vcenter_pass }}"
validate_certs: False
name: "{{ item}}"
datacenter: "{{ datacenter_name }}"
folder: /{{ datacenter_name }}/vm
state: absent
wait_for_ip_address: yes
loop: