| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) 2017, IBM Corp |
| 5 |
# Author(s): Andreas Nafpliotis <[email protected]> |
| 6 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 7 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 8 |
|
| 9 |
from __future__ import absolute_import, division, print_function |
| 10 |
__metaclass__ = type |
| 11 |
|
| 12 |
|
| 13 |
DOCUMENTATION = r''' |
| 14 |
--- |
| 15 |
module: vmware_cfg_backup |
| 16 |
short_description: Backup / Restore / Reset ESXi host configuration |
| 17 |
description: |
| 18 |
- This module can be used to perform various operations related to backup, restore and reset of ESXi host configuration. |
| 19 |
author: |
| 20 |
- Andreas Nafpliotis (@nafpliot-ibm) |
| 21 |
notes: |
| 22 |
- Works only for ESXi hosts |
| 23 |
- For configuration load or reset, the host will be switched automatically to maintenance mode. |
| 24 |
options: |
| 25 |
esxi_hostname: |
| 26 |
description: |
| 27 |
- Name of ESXi server. This is required only if authentication against a vCenter is done. |
| 28 |
required: false |
| 29 |
type: str |
| 30 |
dest: |
| 31 |
description: |
| 32 |
- The destination where the ESXi configuration bundle will be saved. Can be a folder or a file. |
| 33 |
- If a folder, the backup file will be saved in the folder with the default filename generated from the ESXi server. |
| 34 |
- If a file, the backup file will be saved with that filename. The file extension will always be .tgz. |
| 35 |
type: path |
| 36 |
src: |
| 37 |
description: |
| 38 |
- The file containing the ESXi configuration that will be restored. |
| 39 |
type: path |
| 40 |
state: |
| 41 |
description: |
| 42 |
- If V(saved), the .tgz backup bundle will be saved in O(dest). |
| 43 |
- If V(absent), the host configuration will be reset to default values. |
| 44 |
- If V(loaded), the backup file in O(src) will be loaded to the ESXi host rewriting the hosts settings. |
| 45 |
choices: [saved, absent, loaded] |
| 46 |
type: str |
| 47 |
required: true |
| 48 |
extends_documentation_fragment: |
| 49 |
- vmware.vmware.base_options |
| 50 |
|
| 51 |
''' |
| 52 |
|
| 53 |
EXAMPLES = r''' |
| 54 |
- name: Save the ESXi configuration locally by authenticating directly against the ESXi host |
| 55 |
community.vmware.vmware_cfg_backup: |
| 56 |
hostname: '{{ esxi_hostname }}' |
| 57 |
username: '{{ esxi_username }}' |
| 58 |
password: '{{ esxi_password }}' |
| 59 |
state: saved |
| 60 |
dest: /tmp/ |
| 61 |
delegate_to: localhost |
| 62 |
|
| 63 |
- name: Save the ESXi configuration locally by authenticating against the vCenter and selecting the ESXi host |
| 64 |
community.vmware.vmware_cfg_backup: |
| 65 |
hostname: '{{ vcenter_hostname }}' |
| 66 |
esxi_hostname: '{{ esxi_hostname }}' |
| 67 |
username: '{{ esxi_username }}' |
| 68 |
password: '{{ esxi_password }}' |
| 69 |
state: saved |
| 70 |
dest: /tmp/ |
| 71 |
delegate_to: localhost |
| 72 |
''' |
| 73 |
|
| 74 |
RETURN = r''' |
| 75 |
dest_file: |
| 76 |
description: The full path of where the file holding the ESXi configurations was stored |
| 77 |
returned: changed |
| 78 |
type: str |
| 79 |
sample: /tmp/configBundle-esxi.host.domain.tgz |
| 80 |
''' |
| 81 |
|
| 82 |
import os |
| 83 |
try: |
| 84 |
from pyVmomi import vim |
| 85 |
except ImportError: |
| 86 |
pass |
| 87 |
|
| 88 |
from ansible_collections.community.vmware.plugins.module_utils.vmware import get_all_objs, wait_for_task, PyVmomi |
| 89 |
from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec |
| 90 |
from ansible.module_utils.basic import AnsibleModule |
| 91 |
from ansible.module_utils.urls import open_url |
| 92 |
from urllib.error import HTTPError |
| 93 |
from ansible.module_utils.common.text.converters import to_native |
| 94 |
|
| 95 |
|
| 96 |
class VMwareConfigurationBackup(PyVmomi): |
| 97 |
def __init__(self, module): |
| 98 |
super(VMwareConfigurationBackup, self).__init__(module) |
| 99 |
self.state = self.module.params['state'] |
| 100 |
self.dest = self.module.params['dest'] |
| 101 |
self.src = self.module.params['src'] |
| 102 |
self.hostname = self.module.params['hostname'] |
| 103 |
self.username = self.module.params['username'] |
| 104 |
self.password = self.module.params['password'] |
| 105 |
self.validate_certs = self.module.params['validate_certs'] |
| 106 |
self.esxi_hostname = self.module.params.get('esxi_hostname', None) |
| 107 |
self.host = self.find_host_system() |
| 108 |
|
| 109 |
# discard vim returned hostname if endpoint is a standalone ESXi host |
| 110 |
self.cfg_hurl = self.hostname if (self.content.about.apiType == "HostAgent") else self.host.name |
| 111 |
|
| 112 |
def find_host_system(self): |
| 113 |
if self.esxi_hostname: |
| 114 |
host_system_obj = self.find_hostsystem_by_name(host_name=self.esxi_hostname) |
| 115 |
if host_system_obj: |
| 116 |
return host_system_obj |
| 117 |
else: |
| 118 |
self.module.fail_json(msg="Failed to find ESXi %s" % self.esxi_hostname) |
| 119 |
|
| 120 |
host_system = get_all_objs(self.content, [vim.HostSystem]) |
| 121 |
return list(host_system)[0] |
| 122 |
|
| 123 |
def process_state(self): |
| 124 |
if self.state == 'saved': |
| 125 |
self.save_configuration() |
| 126 |
|
| 127 |
if self.state == 'absent': |
| 128 |
self.reset_configuration() |
| 129 |
|
| 130 |
if self.state == 'loaded': |
| 131 |
self.load_configuration() |
| 132 |
|
| 133 |
def load_configuration(self): |
| 134 |
if not os.path.isfile(self.src): |
| 135 |
self.module.fail_json(msg="Source file {0} does not exist".format(self.src)) |
| 136 |
|
| 137 |
url = self.host.configManager.firmwareSystem.QueryFirmwareConfigUploadURL() |
| 138 |
url = url.replace('*', self.cfg_hurl) |
| 139 |
if self.module.params["port"] == 443: |
| 140 |
url = url.replace("http:", "https:") |
| 141 |
# find manually the url if there is a redirect because urllib2 -per RFC- doesn't do automatic redirects for PUT requests |
| 142 |
try: |
| 143 |
open_url(url=url, method='HEAD', validate_certs=self.validate_certs) |
| 144 |
except HTTPError as e: |
| 145 |
url = e.geturl() |
| 146 |
|
| 147 |
try: |
| 148 |
with open(self.src, 'rb') as file: |
| 149 |
data = file.read() |
| 150 |
open_url( |
| 151 |
url=url, data=data, method='PUT', validate_certs=self.validate_certs, |
| 152 |
url_username=self.username, url_password=self.password, force_basic_auth=True) |
| 153 |
except Exception as e: |
| 154 |
self.module.fail_json(msg=to_native(e)) |
| 155 |
|
| 156 |
if not self.host.runtime.inMaintenanceMode: |
| 157 |
self.enter_maintenance() |
| 158 |
try: |
| 159 |
self.host.configManager.firmwareSystem.RestoreFirmwareConfiguration(force=True) |
| 160 |
self.module.exit_json(changed=True) |
| 161 |
except Exception as e: |
| 162 |
self.exit_maintenance() |
| 163 |
self.module.fail_json(msg=to_native(e)) |
| 164 |
|
| 165 |
def reset_configuration(self): |
| 166 |
if not self.host.runtime.inMaintenanceMode: |
| 167 |
self.enter_maintenance() |
| 168 |
try: |
| 169 |
self.host.configManager.firmwareSystem.ResetFirmwareToFactoryDefaults() |
| 170 |
self.module.exit_json(changed=True) |
| 171 |
except Exception as e: |
| 172 |
self.exit_maintenance() |
| 173 |
self.module.fail_json(msg=to_native(e)) |
| 174 |
|
| 175 |
def save_configuration(self): |
| 176 |
url = self.host.configManager.firmwareSystem.BackupFirmwareConfiguration() |
| 177 |
url = url.replace('*', self.cfg_hurl) |
| 178 |
if self.module.params["port"] == 443: |
| 179 |
url = url.replace("http:", "https:") |
| 180 |
if os.path.isdir(self.dest): |
| 181 |
filename = url.rsplit('/', 1)[1] |
| 182 |
self.dest = os.path.join(self.dest, filename) |
| 183 |
else: |
| 184 |
filename, file_extension = os.path.splitext(self.dest) |
| 185 |
if file_extension != ".tgz": |
| 186 |
self.dest = filename + ".tgz" |
| 187 |
try: |
| 188 |
request = open_url(url=url, validate_certs=self.validate_certs) |
| 189 |
with open(self.dest, "wb") as file: |
| 190 |
file.write(request.read()) |
| 191 |
self.module.exit_json(changed=True, dest_file=self.dest) |
| 192 |
except IOError as e: |
| 193 |
error_msg = "Failed to save %s " % url |
| 194 |
error_msg += "to %s. Ensure that the dest path exists and is writable. " % self.dest |
| 195 |
error_msg += "Details: %s" % to_native(e) |
| 196 |
self.module.fail_json(msg=error_msg) |
| 197 |
except Exception as e: |
| 198 |
self.module.fail_json(msg=to_native(e)) |
| 199 |
|
| 200 |
def enter_maintenance(self): |
| 201 |
try: |
| 202 |
task = self.host.EnterMaintenanceMode_Task(timeout=15) |
| 203 |
success, result = wait_for_task(task) |
| 204 |
except Exception as e: |
| 205 |
self.module.fail_json(msg="Failed to enter maintenance mode." |
| 206 |
" Ensure that there are no powered on machines on the host. %s" % to_native(e)) |
| 207 |
|
| 208 |
def exit_maintenance(self): |
| 209 |
try: |
| 210 |
task = self.host.ExitMaintenanceMode_Task(timeout=15) |
| 211 |
success, result = wait_for_task(task) |
| 212 |
except Exception as generic_exc: |
| 213 |
self.module.fail_json(msg="Failed to exit maintenance mode due to %s" % to_native(generic_exc)) |
| 214 |
|
| 215 |
|
| 216 |
def main(): |
| 217 |
argument_spec = base_argument_spec() |
| 218 |
argument_spec.update(dict(dest=dict(required=False, type='path'), |
| 219 |
esxi_hostname=dict(required=False, type='str'), |
| 220 |
src=dict(required=False, type='path'), |
| 221 |
state=dict(required=True, choices=['saved', 'absent', 'loaded'], type='str'))) |
| 222 |
required_if = [('state', 'saved', ['dest']), |
| 223 |
('state', 'loaded', ['src'])] |
| 224 |
|
| 225 |
module = AnsibleModule(argument_spec=argument_spec, |
| 226 |
required_if=required_if, |
| 227 |
supports_check_mode=False) |
| 228 |
|
| 229 |
vmware_cfg_backup = VMwareConfigurationBackup(module) |
| 230 |
vmware_cfg_backup.process_state() |
| 231 |
|
| 232 |
|
| 233 |
if __name__ == '__main__': |
| 234 |
main() |