1.. _vmware_guest_from_template:
2
3****************************************
4Deploy a virtual machine from a template
5****************************************
6
7.. contents:: Topics
8
9Introduction
10============
11
12This guide will show you how to utilize Ansible to clone a virtual machine from already existing VMware template or existing VMware guest.
13
14Scenario Requirements
15=====================
16
17* Software
18
19    * Ansible 2.5 or later must be installed
20
21    * The Python module ``Pyvmomi`` must be installed on the Ansible (or Target host if not executing against localhost)
22
23    * Installing the latest ``Pyvmomi`` via ``pip`` is recommended [as the OS provided packages are usually out of date and incompatible]
24
25* Hardware
26
27    * vCenter Server with at least one ESXi server
28
29* Access / Credentials
30
31    * Ansible (or the target server) must have network access to the either vCenter server or the ESXi server you will be deploying to
32
33    * Username and Password
34
35    * Administrator user with following privileges
36
37        - ``Datastore.AllocateSpace`` on the destination datastore or datastore folder
38        - ``Network.Assign`` on the network to which the virtual machine will be assigned
39        - ``Resource.AssignVMToPool`` on the destination host, cluster, or resource pool
40        - ``VirtualMachine.Config.AddNewDisk`` on the datacenter or virtual machine folder
41        - ``VirtualMachine.Config.AddRemoveDevice`` on the datacenter or virtual machine folder
42        - ``VirtualMachine.Interact.PowerOn`` on the datacenter or virtual machine folder
43        - ``VirtualMachine.Inventory.CreateFromExisting`` on the datacenter or virtual machine folder
44        - ``VirtualMachine.Provisioning.Clone`` on the virtual machine you are cloning
45        - ``VirtualMachine.Provisioning.Customize`` on the virtual machine or virtual machine folder if you are customizing the guest operating system
46        - ``VirtualMachine.Provisioning.DeployTemplate`` on the template you are using
47        - ``VirtualMachine.Provisioning.ReadCustSpecs`` on the root vCenter Server if you are customizing the guest operating system
48
49        Depending on your requirements, you could also need one or more of the following privileges:
50
51        - ``VirtualMachine.Config.CPUCount`` on the datacenter or virtual machine folder
52        - ``VirtualMachine.Config.Memory`` on the datacenter or virtual machine folder
53        - ``VirtualMachine.Config.DiskExtend`` on the datacenter or virtual machine folder
54        - ``VirtualMachine.Config.Annotation`` on the datacenter or virtual machine folder
55        - ``VirtualMachine.Config.AdvancedConfig`` on the datacenter or virtual machine folder
56        - ``VirtualMachine.Config.EditDevice`` on the datacenter or virtual machine folder
57        - ``VirtualMachine.Config.Resource`` on the datacenter or virtual machine folder
58        - ``VirtualMachine.Config.Settings`` on the datacenter or virtual machine folder
59        - ``VirtualMachine.Config.UpgradeVirtualHardware`` on the datacenter or virtual machine folder
60        - ``VirtualMachine.Interact.SetCDMedia`` on the datacenter or virtual machine folder
61        - ``VirtualMachine.Interact.SetFloppyMedia`` on the datacenter or virtual machine folder
62        - ``VirtualMachine.Interact.DeviceConnection`` on the datacenter or virtual machine folder
63
64Assumptions
65===========
66
67- All variable names and VMware object names are case sensitive
68- VMware allows creation of virtual machine and templates with same name across datacenters and within datacenters
69- You need to use Python 2.7.9 version in order to use ``validate_certs`` option, as this version is capable of changing the SSL verification behaviours
70
71Caveats
72=======
73
74- Hosts in the ESXi cluster must have access to the datastore that the template resides on.
75- Multiple templates with the same name will cause module failures.
76- In order to utilize Guest Customization, VMware Tools must be installed on the template. For Linux, the ``open-vm-tools`` package is recommended, and it requires that ``Perl`` be installed.
77
78
79Example Description
80===================
81
82In this use case / example, we will be selecting a virtual machine template and cloning it into a specific folder in our Datacenter / Cluster.  The following Ansible playbook showcases the basic parameters that are needed for this.
83
84.. code-block:: yaml
85
86    ---
87    - name: Create a VM from a template
88      hosts: localhost
89      gather_facts: no
90      tasks:
91      - name: Clone the template
92        vmware_guest:
93          hostname: "{{ vcenter_ip }}"
94          username: "{{ vcenter_username }}"
95          password: "{{ vcenter_password }}"
96          validate_certs: False
97          name: testvm_2
98          template: template_el7
99          datacenter: "{{ datacenter_name }}"
100          folder: /DC1/vm
101          state: poweredon
102          cluster: "{{ cluster_name }}"
103          wait_for_ip_address: yes
104
105
106Since Ansible utilizes the VMware API to perform actions, in this use case we will be connecting directly to the API from our localhost. This means that our playbooks will not be running from the vCenter or ESXi Server. We do not necessarily need to collect facts about our localhost, so the ``gather_facts`` parameter will be disabled. You can run these modules against another server that would then connect to the API if your localhost does not have access to vCenter. If so, the required Python modules will need to be installed on that target server.
107
108To begin, there are a few bits of information we will need. First and foremost is the hostname of the ESXi server or vCenter server. After this, you will need the username and password for this server. For now, you will be entering these directly, but in a more advanced playbook this can be abstracted out and stored in a more secure fashion using  :ref:`ansible-vault` or using `Ansible Tower credentials <https://docs.ansible.com/ansible-tower/latest/html/userguide/credentials.html>`_. If your vCenter or ESXi server is not setup with proper CA certificates that can be verified from the Ansible server, then it is necessary to disable validation of these certificates by using the ``validate_certs`` parameter. To do this you need to set ``validate_certs=False`` in your playbook.
109
110Now you need to supply the information about the virtual machine which will be created. Give your virtual machine a name, one that conforms to all VMware requirements for naming conventions.  Next, select the display name of the template from which you want to clone new virtual machine. This must match what's displayed in VMware Web UI exactly. Then you can specify a folder to place this new virtual machine in. This path can either be a relative path or a full path to the folder including the Datacenter. You may need to specify a state for the virtual machine.  This simply tells the module which action you want to take, in this case you will be ensure that the virtual machine exists and is powered on.  An optional parameter is ``wait_for_ip_address``, this will tell Ansible to wait for the virtual machine to fully boot up and VMware Tools is running before completing this task.
111
112
113What to expect
114--------------
115
116- You will see a bit of JSON output after this playbook completes. This output shows various parameters that are returned from the module and from vCenter about the newly created VM.
117
118.. code-block:: yaml
119
120    {
121        "changed": true,
122        "instance": {
123            "annotation": "",
124            "current_snapshot": null,
125            "customvalues": {},
126            "guest_consolidation_needed": false,
127            "guest_question": null,
128            "guest_tools_status": "guestToolsNotRunning",
129            "guest_tools_version": "0",
130            "hw_cores_per_socket": 1,
131            "hw_datastores": [
132                "ds_215"
133            ],
134            "hw_esxi_host": "192.0.2.44",
135            "hw_eth0": {
136                "addresstype": "assigned",
137                "ipaddresses": null,
138                "label": "Network adapter 1",
139                "macaddress": "00:50:56:8c:19:f4",
140                "macaddress_dash": "00-50-56-8c-19-f4",
141                "portgroup_key": "dvportgroup-17",
142                "portgroup_portkey": "0",
143                "summary": "DVSwitch: 50 0c 5b 22 b6 68 ab 89-fc 0b 59 a4 08 6e 80 fa"
144            },
145            "hw_files": [
146                "[ds_215] testvm_2/testvm_2.vmx",
147                "[ds_215] testvm_2/testvm_2.vmsd",
148                "[ds_215] testvm_2/testvm_2.vmdk"
149            ],
150            "hw_folder": "/DC1/vm",
151            "hw_guest_full_name": null,
152            "hw_guest_ha_state": null,
153            "hw_guest_id": null,
154            "hw_interfaces": [
155                "eth0"
156            ],
157            "hw_is_template": false,
158            "hw_memtotal_mb": 512,
159            "hw_name": "testvm_2",
160            "hw_power_status": "poweredOff",
161            "hw_processor_count": 2,
162            "hw_product_uuid": "420cb25b-81e8-8d3b-dd2d-a439ee54fcc5",
163            "hw_version": "vmx-13",
164            "instance_uuid": "500cd53b-ed57-d74e-2da8-0dc0eddf54d5",
165            "ipv4": null,
166            "ipv6": null,
167            "module_hw": true,
168            "snapshots": []
169        },
170        "invocation": {
171            "module_args": {
172                "annotation": null,
173                "cdrom": {},
174                "cluster": "DC1_C1",
175                "customization": {},
176                "customization_spec": null,
177                "customvalues": [],
178                "datacenter": "DC1",
179                "disk": [],
180                "esxi_hostname": null,
181                "folder": "/DC1/vm",
182                "force": false,
183                "guest_id": null,
184                "hardware": {},
185                "hostname": "192.0.2.44",
186                "is_template": false,
187                "linked_clone": false,
188                "name": "testvm_2",
189                "name_match": "first",
190                "networks": [],
191                "password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
192                "port": 443,
193                "resource_pool": null,
194                "snapshot_src": null,
195                "state": "present",
196                "state_change_timeout": 0,
197                "template": "template_el7",
198                "username": "administrator@vsphere.local",
199                "uuid": null,
200                "validate_certs": false,
201                "vapp_properties": [],
202                "wait_for_ip_address": true
203            }
204        }
205    }
206
207- State is changed to ``True`` which notifies that the virtual machine is built using given template. The module will not complete until the clone task in VMware is finished. This can take some time depending on your environment.
208
209- If you utilize the ``wait_for_ip_address`` parameter, then it will also increase the clone time as it will wait until virtual machine boots into the OS and an IP Address has been assigned to the given NIC.
210
211
212
213Troubleshooting
214---------------
215
216Things to inspect
217
218- Check if the values provided for username and password are correct
219- Check if the datacenter you provided is available
220- Check if the template specified exists and you have permissions to access the datastore
221- Ensure the full folder path you specified already exists. It will not create folders automatically for you
222
223