| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2019, Nurfet Becirevic <[email protected]> |
| 4 |
# Copyright (c) 2017, Tomas Karasek <[email protected]> |
| 5 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
DOCUMENTATION = r""" |
| 11 |
module: packet_volume_attachment |
| 12 |
|
| 13 |
short_description: Attach/detach a volume to a device in the Packet host |
| 14 |
|
| 15 |
description: |
| 16 |
- Attach/detach a volume to a device in the Packet host. |
| 17 |
- API is documented at U(https://www.packet.com/developers/api/volumes/). |
| 18 |
- This module creates the attachment route in the Packet API. In order to discover the block devices on the server, you |
| 19 |
have to run the Attach Scripts, as documented at U(https://help.packet.net/technical/storage/packet-block-storage-linux). |
| 20 |
version_added: '0.2.0' |
| 21 |
|
| 22 |
author: |
| 23 |
- Tomas Karasek (@t0mk) <[email protected]> |
| 24 |
- Nurfet Becirevic (@nurfet-becirevic) <[email protected]> |
| 25 |
|
| 26 |
extends_documentation_fragment: |
| 27 |
- community.general._attributes |
| 28 |
|
| 29 |
attributes: |
| 30 |
check_mode: |
| 31 |
support: full |
| 32 |
diff_mode: |
| 33 |
support: none |
| 34 |
|
| 35 |
options: |
| 36 |
state: |
| 37 |
description: |
| 38 |
- Indicate desired state of the attachment. |
| 39 |
default: present |
| 40 |
choices: ['present', 'absent'] |
| 41 |
type: str |
| 42 |
|
| 43 |
auth_token: |
| 44 |
description: |
| 45 |
- Packet API token. You can also supply it in environment variable E(PACKET_API_TOKEN). |
| 46 |
type: str |
| 47 |
|
| 48 |
project_id: |
| 49 |
description: |
| 50 |
- UUID of the project to which the device and volume belong. |
| 51 |
type: str |
| 52 |
required: true |
| 53 |
|
| 54 |
volume: |
| 55 |
description: |
| 56 |
- Selector for the volume. |
| 57 |
- It can be a UUID, an API-generated volume name, or user-defined description string. |
| 58 |
- 'Example values: V(4a347482-b546-4f67-8300-fb5018ef0c5), V(volume-4a347482), V(my volume).' |
| 59 |
type: str |
| 60 |
required: true |
| 61 |
|
| 62 |
device: |
| 63 |
description: |
| 64 |
- Selector for the device. |
| 65 |
- It can be a UUID of the device, or a hostname. |
| 66 |
- 'Example values: 98a14f7a-3d27-4478-b7cf-35b5670523f3, "my device".' |
| 67 |
type: str |
| 68 |
|
| 69 |
requirements: |
| 70 |
- "packet-python >= 1.35" |
| 71 |
""" |
| 72 |
|
| 73 |
EXAMPLES = r""" |
| 74 |
# All the examples assume that you have your Packet API token in env var PACKET_API_TOKEN. |
| 75 |
# You can also pass the api token in module param auth_token. |
| 76 |
|
| 77 |
- hosts: localhost |
| 78 |
|
| 79 |
vars: |
| 80 |
volname: testvol |
| 81 |
devname: testdev |
| 82 |
project_id: 52000fb2-ee46-4673-93a8-de2c2bdba33b |
| 83 |
|
| 84 |
tasks: |
| 85 |
- name: Create volume |
| 86 |
community.general.packet_volume: |
| 87 |
description: "{{ volname }}" |
| 88 |
project_id: "{{ project_id }}" |
| 89 |
facility: ewr1 |
| 90 |
plan: storage_1 |
| 91 |
state: present |
| 92 |
size: 10 |
| 93 |
snapshot_policy: |
| 94 |
snapshot_count: 10 |
| 95 |
snapshot_frequency: 1day |
| 96 |
|
| 97 |
- name: Create a device |
| 98 |
community.general.packet_device: |
| 99 |
project_id: "{{ project_id }}" |
| 100 |
hostnames: "{{ devname }}" |
| 101 |
operating_system: ubuntu_16_04 |
| 102 |
plan: baremetal_0 |
| 103 |
facility: ewr1 |
| 104 |
state: present |
| 105 |
|
| 106 |
- name: Attach testvol to testdev |
| 107 |
community.general.packet_volume_attachment: |
| 108 |
project_id: "{{ project_id }}" |
| 109 |
volume: "{{ volname }}" |
| 110 |
device: "{{ devname }}" |
| 111 |
|
| 112 |
- name: Detach testvol from testdev |
| 113 |
community.general.packet_volume_attachment: |
| 114 |
project_id: "{{ project_id }}" |
| 115 |
volume: "{{ volname }}" |
| 116 |
device: "{{ devname }}" |
| 117 |
state: absent |
| 118 |
""" |
| 119 |
|
| 120 |
RETURN = r""" |
| 121 |
volume_id: |
| 122 |
description: UUID of volume addressed by the module call. |
| 123 |
type: str |
| 124 |
returned: success |
| 125 |
|
| 126 |
device_id: |
| 127 |
description: UUID of device addressed by the module call. |
| 128 |
type: str |
| 129 |
returned: success |
| 130 |
""" |
| 131 |
|
| 132 |
import uuid |
| 133 |
|
| 134 |
from ansible.module_utils.basic import AnsibleModule, env_fallback |
| 135 |
|
| 136 |
HAS_PACKET_SDK = True |
| 137 |
|
| 138 |
|
| 139 |
try: |
| 140 |
import packet |
| 141 |
except ImportError: |
| 142 |
HAS_PACKET_SDK = False |
| 143 |
|
| 144 |
|
| 145 |
PACKET_API_TOKEN_ENV_VAR = "PACKET_API_TOKEN" |
| 146 |
|
| 147 |
STATES = ["present", "absent"] |
| 148 |
|
| 149 |
|
| 150 |
def is_valid_uuid(myuuid): |
| 151 |
try: |
| 152 |
val = uuid.UUID(myuuid, version=4) |
| 153 |
except ValueError: |
| 154 |
return False |
| 155 |
return str(val) == myuuid |
| 156 |
|
| 157 |
|
| 158 |
def get_volume_selector(spec): |
| 159 |
if is_valid_uuid(spec): |
| 160 |
return lambda v: v["id"] == spec |
| 161 |
else: |
| 162 |
return lambda v: v["name"] == spec or v["description"] == spec |
| 163 |
|
| 164 |
|
| 165 |
def get_device_selector(spec): |
| 166 |
if is_valid_uuid(spec): |
| 167 |
return lambda v: v["id"] == spec |
| 168 |
else: |
| 169 |
return lambda v: v["hostname"] == spec |
| 170 |
|
| 171 |
|
| 172 |
def do_attach(packet_conn, vol_id, dev_id): |
| 173 |
api_method = f"storage/{vol_id}/attachments" |
| 174 |
packet_conn.call_api(api_method, params={"device_id": dev_id}, type="POST") |
| 175 |
|
| 176 |
|
| 177 |
def do_detach(packet_conn, vol, dev_id=None): |
| 178 |
def dev_match(a): |
| 179 |
return (dev_id is None) or (a["device"]["id"] == dev_id) |
| 180 |
|
| 181 |
for a in vol["attachments"]: |
| 182 |
if dev_match(a): |
| 183 |
packet_conn.call_api(a["href"], type="DELETE") |
| 184 |
|
| 185 |
|
| 186 |
def validate_selected(l, resource_type, spec): |
| 187 |
if len(l) > 1: |
| 188 |
_msg = f"more than one {resource_type} matches specification {spec}: {l}" |
| 189 |
raise Exception(_msg) |
| 190 |
if len(l) == 0: |
| 191 |
_msg = f"no {resource_type} matches specification: {spec}" |
| 192 |
raise Exception(_msg) |
| 193 |
|
| 194 |
|
| 195 |
def get_attached_dev_ids(volume_dict): |
| 196 |
if len(volume_dict["attachments"]) == 0: |
| 197 |
return [] |
| 198 |
else: |
| 199 |
return [a["device"]["id"] for a in volume_dict["attachments"]] |
| 200 |
|
| 201 |
|
| 202 |
def act_on_volume_attachment(target_state, module, packet_conn): |
| 203 |
return_dict = {"changed": False} |
| 204 |
volspec = module.params.get("volume") |
| 205 |
devspec = module.params.get("device") |
| 206 |
if devspec is None and target_state == "present": |
| 207 |
raise Exception("If you want to attach a volume, you must specify a device.") |
| 208 |
project_id = module.params.get("project_id") |
| 209 |
volumes_api_method = f"projects/{project_id}/storage" |
| 210 |
volumes = packet_conn.call_api(volumes_api_method, params={"include": "facility,attachments.device"})["volumes"] |
| 211 |
v_match = get_volume_selector(volspec) |
| 212 |
matching_volumes = [v for v in volumes if v_match(v)] |
| 213 |
validate_selected(matching_volumes, "volume", volspec) |
| 214 |
volume = matching_volumes[0] |
| 215 |
return_dict["volume_id"] = volume["id"] |
| 216 |
|
| 217 |
device = None |
| 218 |
if devspec is not None: |
| 219 |
devices_api_method = f"projects/{project_id}/devices" |
| 220 |
devices = packet_conn.call_api(devices_api_method)["devices"] |
| 221 |
d_match = get_device_selector(devspec) |
| 222 |
matching_devices = [d for d in devices if d_match(d)] |
| 223 |
validate_selected(matching_devices, "device", devspec) |
| 224 |
device = matching_devices[0] |
| 225 |
return_dict["device_id"] = device["id"] |
| 226 |
|
| 227 |
attached_device_ids = get_attached_dev_ids(volume) |
| 228 |
|
| 229 |
if target_state == "present": |
| 230 |
if len(attached_device_ids) == 0: |
| 231 |
do_attach(packet_conn, volume["id"], device["id"]) |
| 232 |
return_dict["changed"] = True |
| 233 |
elif device["id"] not in attached_device_ids: |
| 234 |
# Don't reattach volume which is attached to a different device. |
| 235 |
# Rather fail than force remove a device on state == 'present'. |
| 236 |
raise Exception(f"volume {volume} is already attached to device {attached_device_ids}") |
| 237 |
else: |
| 238 |
if device is None: |
| 239 |
if len(attached_device_ids) > 0: |
| 240 |
do_detach(packet_conn, volume) |
| 241 |
return_dict["changed"] = True |
| 242 |
elif device["id"] in attached_device_ids: |
| 243 |
do_detach(packet_conn, volume, device["id"]) |
| 244 |
return_dict["changed"] = True |
| 245 |
|
| 246 |
return return_dict |
| 247 |
|
| 248 |
|
| 249 |
def main(): |
| 250 |
module = AnsibleModule( |
| 251 |
argument_spec=dict( |
| 252 |
state=dict(choices=STATES, default="present"), |
| 253 |
auth_token=dict(type="str", fallback=(env_fallback, [PACKET_API_TOKEN_ENV_VAR]), no_log=True), |
| 254 |
volume=dict(type="str", required=True), |
| 255 |
project_id=dict(type="str", required=True), |
| 256 |
device=dict(type="str"), |
| 257 |
), |
| 258 |
supports_check_mode=True, |
| 259 |
) |
| 260 |
|
| 261 |
if not HAS_PACKET_SDK: |
| 262 |
module.fail_json(msg="packet required for this module") |
| 263 |
|
| 264 |
if not module.params.get("auth_token"): |
| 265 |
_fail_msg = f"if Packet API token is not in environment variable {PACKET_API_TOKEN_ENV_VAR}, the auth_token parameter is required" |
| 266 |
module.fail_json(msg=_fail_msg) |
| 267 |
|
| 268 |
auth_token = module.params.get("auth_token") |
| 269 |
|
| 270 |
packet_conn = packet.Manager(auth_token=auth_token) |
| 271 |
|
| 272 |
state = module.params.get("state") |
| 273 |
|
| 274 |
if state in STATES: |
| 275 |
if module.check_mode: |
| 276 |
module.exit_json(changed=False) |
| 277 |
|
| 278 |
try: |
| 279 |
module.exit_json(**act_on_volume_attachment(state, module, packet_conn)) |
| 280 |
except Exception as e: |
| 281 |
module.fail_json(msg=f"failed to set volume_attachment state {state}: {e}") |
| 282 |
else: |
| 283 |
module.fail_json(msg=f"{state} is not a valid state for this module") |
| 284 |
|
| 285 |
|
| 286 |
if __name__ == "__main__": |
| 287 |
main() |