| 1 |
#!/usr/bin/python |
| 2 |
# |
| 3 |
# Copyright (c) 2020, Jeffrey van Pelt (@Thulium-Drake) <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
|
| 8 |
DOCUMENTATION = r""" |
| 9 |
module: proxmox_snap |
| 10 |
short_description: Snapshot management of instances in Proxmox VE cluster |
| 11 |
description: |
| 12 |
- Allows you to create/delete/restore snapshots from instances in Proxmox VE cluster. |
| 13 |
- Supports both KVM and LXC, OpenVZ has not been tested, as it is no longer supported on Proxmox VE. |
| 14 |
attributes: |
| 15 |
check_mode: |
| 16 |
support: full |
| 17 |
diff_mode: |
| 18 |
support: none |
| 19 |
options: |
| 20 |
hostname: |
| 21 |
description: |
| 22 |
- The instance name. |
| 23 |
type: str |
| 24 |
vmid: |
| 25 |
description: |
| 26 |
- The instance ID. |
| 27 |
- If not set, will be fetched from PromoxAPI based on the hostname. |
| 28 |
type: str |
| 29 |
state: |
| 30 |
description: |
| 31 |
- Indicate desired state of the instance snapshot. |
| 32 |
choices: ['present', 'absent', 'rollback'] |
| 33 |
default: present |
| 34 |
type: str |
| 35 |
force: |
| 36 |
description: |
| 37 |
- For removal from config file, even if removing disk snapshot fails. |
| 38 |
default: false |
| 39 |
type: bool |
| 40 |
unbind: |
| 41 |
description: |
| 42 |
- This option only applies to LXC containers. |
| 43 |
- Allows to snapshot a container even if it has configured mountpoints. |
| 44 |
- Temporarily disables all configured mountpoints, takes snapshot, and finally restores original configuration. |
| 45 |
- If running, the container will be stopped and restarted to apply config changes. |
| 46 |
- Due to restrictions in the Proxmox API this option can only be used authenticating as V(root@pam) with O(api_password), |
| 47 |
API tokens do not work either. |
| 48 |
- See U(https://pve.proxmox.com/pve-docs/api-viewer/#/nodes/{node}/lxc/{vmid}/config) (PUT tab) for more details. |
| 49 |
default: false |
| 50 |
type: bool |
| 51 |
vmstate: |
| 52 |
description: |
| 53 |
- Snapshot includes RAM. |
| 54 |
default: false |
| 55 |
type: bool |
| 56 |
description: |
| 57 |
description: |
| 58 |
- Specify the description for the snapshot. Only used on the configuration web interface. |
| 59 |
- This is saved as a comment inside the configuration file. |
| 60 |
type: str |
| 61 |
timeout: |
| 62 |
description: |
| 63 |
- Timeout for operations. |
| 64 |
default: 30 |
| 65 |
type: int |
| 66 |
snapname: |
| 67 |
description: |
| 68 |
- Name of the snapshot that has to be created/deleted/restored. |
| 69 |
default: 'ansible_snap' |
| 70 |
type: str |
| 71 |
retention: |
| 72 |
description: |
| 73 |
- Remove old snapshots if there are more than O(retention) snapshots. |
| 74 |
- If O(retention) is set to V(0), all snapshots will be kept. |
| 75 |
- This is only used when O(state=present) and when an actual snapshot is created. If no snapshot is created, all existing |
| 76 |
snapshots will be kept. |
| 77 |
default: 0 |
| 78 |
type: int |
| 79 |
|
| 80 |
notes: |
| 81 |
- Requires proxmoxer and requests modules on host. These modules can be installed with pip. |
| 82 |
author: Jeffrey van Pelt (@Thulium-Drake) |
| 83 |
extends_documentation_fragment: |
| 84 |
- community.proxmox.proxmox.actiongroup_proxmox |
| 85 |
- community.proxmox.proxmox.documentation |
| 86 |
- community.proxmox.attributes |
| 87 |
""" |
| 88 |
|
| 89 |
EXAMPLES = r""" |
| 90 |
- name: Create new container snapshot |
| 91 |
community.proxmox.proxmox_snap: |
| 92 |
vmid: 100 |
| 93 |
state: present |
| 94 |
snapname: pre-updates |
| 95 |
|
| 96 |
- name: Create new container snapshot and keep only the 2 newest snapshots |
| 97 |
community.proxmox.proxmox_snap: |
| 98 |
vmid: 100 |
| 99 |
state: present |
| 100 |
snapname: snapshot-42 |
| 101 |
retention: 2 |
| 102 |
|
| 103 |
- name: Create new snapshot for a container with configured mountpoints |
| 104 |
community.proxmox.proxmox_snap: |
| 105 |
vmid: 100 |
| 106 |
state: present |
| 107 |
unbind: true # requires root@pam+password auth, API tokens are not supported |
| 108 |
snapname: pre-updates |
| 109 |
|
| 110 |
- name: Remove container snapshot |
| 111 |
community.proxmox.proxmox_snap: |
| 112 |
vmid: 100 |
| 113 |
state: absent |
| 114 |
snapname: pre-updates |
| 115 |
|
| 116 |
- name: Rollback container snapshot |
| 117 |
community.proxmox.proxmox_snap: |
| 118 |
vmid: 100 |
| 119 |
state: rollback |
| 120 |
snapname: pre-updates |
| 121 |
""" |
| 122 |
|
| 123 |
RETURN = r"""#""" |
| 124 |
|
| 125 |
import time |
| 126 |
|
| 127 |
from ansible.module_utils.common.text.converters import to_native |
| 128 |
from ansible.module_utils.errors import AnsibleValidationError |
| 129 |
|
| 130 |
from ansible_collections.community.proxmox.plugins.module_utils.proxmox import ( |
| 131 |
ProxmoxAnsible, |
| 132 |
create_proxmox_module, |
| 133 |
) |
| 134 |
|
| 135 |
|
| 136 |
def validate_params(params): |
| 137 |
# Validate unbind authentication requirements. |
| 138 |
# Mountpoint configuration operations require root@pam with password authentication. |
| 139 |
# API tokens are not supported for mountpoint operations, even for root@pam. |
| 140 |
# Without proper authentication, the operation would fail after mountpoints are removed, |
| 141 |
# leaving the container in a misconfigured state without its mountpoints. |
| 142 |
if params.get("unbind"): |
| 143 |
api_user = params.get("api_user") |
| 144 |
api_password = params.get("api_password") |
| 145 |
if api_user != "root@pam" or not api_password: |
| 146 |
raise AnsibleValidationError("Parameter 'unbind=True' requires 'api_user' and 'api_password' options.") |
| 147 |
|
| 148 |
|
| 149 |
def module_args(): |
| 150 |
return dict( |
| 151 |
vmid=dict(required=False), |
| 152 |
hostname=dict(), |
| 153 |
timeout=dict(type="int", default=30), |
| 154 |
state=dict(default="present", choices=["present", "absent", "rollback"]), |
| 155 |
description=dict(type="str"), |
| 156 |
snapname=dict(type="str", default="ansible_snap"), |
| 157 |
force=dict(type="bool", default=False), |
| 158 |
unbind=dict(type="bool", default=False), |
| 159 |
vmstate=dict(type="bool", default=False), |
| 160 |
retention=dict(type="int", default=0), |
| 161 |
) |
| 162 |
|
| 163 |
|
| 164 |
def module_options(): |
| 165 |
return dict( |
| 166 |
required_if=[ |
| 167 |
("unbind", True, ["api_password"]), |
| 168 |
], |
| 169 |
) |
| 170 |
|
| 171 |
|
| 172 |
class ProxmoxSnapAnsible(ProxmoxAnsible): |
| 173 |
def snapshot(self, vm, vmid): |
| 174 |
return getattr(self.proxmox_api.nodes(vm["node"]), vm["type"])(vmid).snapshot |
| 175 |
|
| 176 |
def vmconfig(self, vm, vmid): |
| 177 |
return getattr(self.proxmox_api.nodes(vm["node"]), vm["type"])(vmid).config |
| 178 |
|
| 179 |
def vmstatus(self, vm, vmid): |
| 180 |
return getattr(self.proxmox_api.nodes(vm["node"]), vm["type"])(vmid).status |
| 181 |
|
| 182 |
def _container_mp_get(self, vm, vmid): |
| 183 |
cfg = self.vmconfig(vm, vmid).get() |
| 184 |
mountpoints = {} |
| 185 |
for key, value in cfg.items(): |
| 186 |
if key.startswith("mp"): |
| 187 |
mountpoints[key] = value |
| 188 |
return mountpoints |
| 189 |
|
| 190 |
def _container_mp_disable(self, vm, vmid, timeout, unbind, mountpoints, vmstatus): # noqa: PLR0913 |
| 191 |
# shutdown container if running |
| 192 |
if vmstatus == "running": |
| 193 |
self.shutdown_instance(vm, vmid, timeout) |
| 194 |
# delete all mountpoints configs |
| 195 |
self.vmconfig(vm, vmid).put(delete=" ".join(mountpoints)) |
| 196 |
|
| 197 |
def _container_mp_restore(self, vm, vmid, timeout, unbind, mountpoints, vmstatus): # noqa: PLR0913 |
| 198 |
# NOTE: requires auth as `root@pam`, API tokens are not supported |
| 199 |
# see https://pve.proxmox.com/pve-docs/api-viewer/#/nodes/{node}/lxc/{vmid}/config |
| 200 |
# restore original config |
| 201 |
self.vmconfig(vm, vmid).put(**mountpoints) |
| 202 |
# start container (if was running before snap) |
| 203 |
if vmstatus == "running": |
| 204 |
self.start_instance(vm, vmid, timeout) |
| 205 |
|
| 206 |
def start_instance(self, vm, vmid, timeout): |
| 207 |
taskid = self.vmstatus(vm, vmid).start.post() |
| 208 |
while timeout >= 0: |
| 209 |
if self.api_task_ok(vm["node"], taskid): |
| 210 |
return True |
| 211 |
timeout -= 1 |
| 212 |
if timeout == 0: |
| 213 |
last_log = self.proxmox_api.nodes(vm["node"]).tasks(taskid).log.get()[:1] |
| 214 |
self.module.fail_json( |
| 215 |
msg=f"Reached timeout while waiting for VM to start. Last line in task before timeout: {last_log}" |
| 216 |
) |
| 217 |
time.sleep(1) |
| 218 |
return False |
| 219 |
|
| 220 |
def shutdown_instance(self, vm, vmid, timeout): |
| 221 |
taskid = self.vmstatus(vm, vmid).shutdown.post() |
| 222 |
while timeout >= 0: |
| 223 |
if self.api_task_ok(vm["node"], taskid): |
| 224 |
return True |
| 225 |
timeout -= 1 |
| 226 |
if timeout == 0: |
| 227 |
last_log = self.proxmox_api.nodes(vm["node"]).tasks(taskid).log.get()[:1] |
| 228 |
self.module.fail_json( |
| 229 |
msg=f"Reached timeout while waiting for VM to stop. Last line in task before timeout: {last_log}" |
| 230 |
) |
| 231 |
time.sleep(1) |
| 232 |
return False |
| 233 |
|
| 234 |
def snapshot_retention(self, vm, vmid, retention): |
| 235 |
# ignore the last snapshot, which is the current state |
| 236 |
snapshots = self.snapshot(vm, vmid).get()[:-1] |
| 237 |
if retention > 0 and len(snapshots) > retention: |
| 238 |
# sort by age, oldest first |
| 239 |
for snap in sorted(snapshots, key=lambda x: x["snaptime"])[: len(snapshots) - retention]: |
| 240 |
self.snapshot(vm, vmid)(snap["name"]).delete() |
| 241 |
|
| 242 |
def snapshot_create(self, vm, vmid, timeout, snapname, description, vmstate, unbind, retention): # noqa: PLR0913 |
| 243 |
if self.module.check_mode: |
| 244 |
return True |
| 245 |
|
| 246 |
if vm["type"] == "lxc": |
| 247 |
if unbind is True: |
| 248 |
mountpoints = self._container_mp_get(vm, vmid) |
| 249 |
vmstatus = self.vmstatus(vm, vmid).current().get()["status"] |
| 250 |
if mountpoints: |
| 251 |
self._container_mp_disable(vm, vmid, timeout, unbind, mountpoints, vmstatus) |
| 252 |
taskid = self.snapshot(vm, vmid).post(snapname=snapname, description=description) |
| 253 |
else: |
| 254 |
taskid = self.snapshot(vm, vmid).post(snapname=snapname, description=description, vmstate=int(vmstate)) |
| 255 |
|
| 256 |
while timeout >= 0: |
| 257 |
if self.api_task_ok(vm["node"], taskid): |
| 258 |
break |
| 259 |
if timeout == 0: |
| 260 |
last_log = self.proxmox_api.nodes(vm["node"]).tasks(taskid).log.get()[:1] |
| 261 |
self.module.fail_json( |
| 262 |
msg=f"Reached timeout while waiting for creating VM snapshot. Last line in task before timeout: {last_log}" |
| 263 |
) |
| 264 |
|
| 265 |
time.sleep(1) |
| 266 |
timeout -= 1 |
| 267 |
if vm["type"] == "lxc" and unbind is True and mountpoints: |
| 268 |
self._container_mp_restore(vm, vmid, timeout, unbind, mountpoints, vmstatus) |
| 269 |
|
| 270 |
self.snapshot_retention(vm, vmid, retention) |
| 271 |
return timeout > 0 |
| 272 |
|
| 273 |
def snapshot_remove(self, vm, vmid, timeout, snapname, force): |
| 274 |
if self.module.check_mode: |
| 275 |
return True |
| 276 |
|
| 277 |
taskid = self.snapshot(vm, vmid).delete(snapname, force=int(force)) |
| 278 |
while timeout >= 0: |
| 279 |
if self.api_task_ok(vm["node"], taskid): |
| 280 |
return True |
| 281 |
if timeout == 0: |
| 282 |
last_log = self.proxmox_api.nodes(vm["node"]).tasks(taskid).log.get()[:1] |
| 283 |
self.module.fail_json( |
| 284 |
msg=f"Reached timeout while waiting for removing VM snapshot. Last line in task before timeout: {last_log}" |
| 285 |
) |
| 286 |
|
| 287 |
time.sleep(1) |
| 288 |
timeout -= 1 |
| 289 |
return False |
| 290 |
|
| 291 |
def snapshot_rollback(self, vm, vmid, timeout, snapname): |
| 292 |
if self.module.check_mode: |
| 293 |
return True |
| 294 |
|
| 295 |
taskid = self.snapshot(vm, vmid)(snapname).post("rollback") |
| 296 |
while timeout >= 0: |
| 297 |
if self.api_task_ok(vm["node"], taskid): |
| 298 |
return True |
| 299 |
if timeout == 0: |
| 300 |
last_log = self.proxmox_api.nodes(vm["node"]).tasks(taskid).log.get()[:1] |
| 301 |
self.module.fail_json( |
| 302 |
msg=f"Reached timeout while waiting for rolling back VM snapshot. Last line in task before timeout: {last_log}" |
| 303 |
) |
| 304 |
|
| 305 |
time.sleep(1) |
| 306 |
timeout -= 1 |
| 307 |
return False |
| 308 |
|
| 309 |
|
| 310 |
def main(): # noqa: PLR0912, PLR0915 |
| 311 |
module = create_proxmox_module(module_args(), **module_options()) |
| 312 |
|
| 313 |
try: |
| 314 |
validate_params(module.params) |
| 315 |
except AnsibleValidationError as e: |
| 316 |
module.fail_json(msg=to_native(e)) |
| 317 |
|
| 318 |
proxmox = ProxmoxSnapAnsible(module) |
| 319 |
|
| 320 |
state = module.params["state"] |
| 321 |
vmid = module.params["vmid"] |
| 322 |
hostname = module.params["hostname"] |
| 323 |
description = module.params["description"] |
| 324 |
snapname = module.params["snapname"] |
| 325 |
timeout = module.params["timeout"] |
| 326 |
force = module.params["force"] |
| 327 |
unbind = module.params["unbind"] |
| 328 |
vmstate = module.params["vmstate"] |
| 329 |
retention = module.params["retention"] |
| 330 |
|
| 331 |
# If hostname is set get the VM id from ProxmoxAPI |
| 332 |
if not vmid and hostname: |
| 333 |
vmid = proxmox.get_vmid(hostname) |
| 334 |
elif not vmid: |
| 335 |
module.exit_json(changed=False, msg=f"Vmid could not be fetched for the following action: {state}") |
| 336 |
|
| 337 |
vm = proxmox.get_vm(vmid) |
| 338 |
if state == "present": |
| 339 |
try: |
| 340 |
for i in proxmox.snapshot(vm, vmid).get(): |
| 341 |
if i["name"] == snapname: |
| 342 |
module.exit_json(changed=False, msg=f"Snapshot {snapname} is already present") |
| 343 |
|
| 344 |
if proxmox.snapshot_create(vm, vmid, timeout, snapname, description, vmstate, unbind, retention): |
| 345 |
if module.check_mode: |
| 346 |
module.exit_json(changed=False, msg=f"Snapshot {snapname} would be created") |
| 347 |
else: |
| 348 |
module.exit_json(changed=True, msg=f"Snapshot {snapname} created") |
| 349 |
|
| 350 |
except Exception as e: |
| 351 |
module.fail_json(msg=f"Creating snapshot {snapname} of VM {vmid} failed with exception: {to_native(e)}") |
| 352 |
|
| 353 |
elif state == "absent": |
| 354 |
try: |
| 355 |
snap_exist = False |
| 356 |
|
| 357 |
for i in proxmox.snapshot(vm, vmid).get(): |
| 358 |
if i["name"] == snapname: |
| 359 |
snap_exist = True |
| 360 |
continue |
| 361 |
|
| 362 |
if not snap_exist: |
| 363 |
module.exit_json(changed=False, msg=f"Snapshot {snapname} does not exist") |
| 364 |
elif proxmox.snapshot_remove(vm, vmid, timeout, snapname, force): |
| 365 |
if module.check_mode: |
| 366 |
module.exit_json(changed=False, msg=f"Snapshot {snapname} would be removed") |
| 367 |
else: |
| 368 |
module.exit_json(changed=True, msg=f"Snapshot {snapname} removed") |
| 369 |
|
| 370 |
except Exception as e: |
| 371 |
module.fail_json(msg=f"Removing snapshot {snapname} of VM {vmid} failed with exception: {to_native(e)}") |
| 372 |
elif state == "rollback": |
| 373 |
try: |
| 374 |
snap_exist = False |
| 375 |
|
| 376 |
for i in proxmox.snapshot(vm, vmid).get(): |
| 377 |
if i["name"] == snapname: |
| 378 |
snap_exist = True |
| 379 |
continue |
| 380 |
|
| 381 |
if not snap_exist: |
| 382 |
module.fail_json(changed=False, msg=f"Snapshot {snapname} does not exist") |
| 383 |
if proxmox.snapshot_rollback(vm, vmid, timeout, snapname): |
| 384 |
if module.check_mode: |
| 385 |
module.exit_json(changed=True, msg=f"Snapshot {snapname} would be rolled back") |
| 386 |
else: |
| 387 |
module.exit_json(changed=True, msg=f"Snapshot {snapname} rolled back") |
| 388 |
|
| 389 |
except Exception as e: |
| 390 |
module.fail_json(msg=f"Rollback of snapshot {snapname} of VM {vmid} failed with exception: {to_native(e)}") |
| 391 |
|
| 392 |
|
| 393 |
if __name__ == "__main__": |
| 394 |
main() |