Debian Codegraph @

ansible_collections/community/general/plugins/modules/packet_device.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2016, Tomas Karasek <[email protected]>
3 # Copyright (c) 2016, Matt Baldwin <[email protected]>
4 # Copyright (c) 2016, Thibaud Morel l'Horset <[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_device
12
13 short_description: Manage a bare metal server in the Packet Host
14
15 description:
16 - Manage a bare metal server in the Packet Host (a "device" in the API terms).
17 - When the machine is created it can optionally wait for public IP address, or for active state.
18 - This module has a dependency on packet >= 1.0.
19 - API is documented at U(https://www.packet.net/developers/api/devices).
20 author:
21 - Tomas Karasek (@t0mk) <[email protected]>
22 - Matt Baldwin (@baldwinSPC) <[email protected]>
23 - Thibaud Morel l'Horset (@teebes) <[email protected]>
24
25 extends_documentation_fragment:
26 - community.general._attributes
27
28 attributes:
29 check_mode:
30 support: none
31 diff_mode:
32 support: none
33
34 options:
35 auth_token:
36 description:
37 - Packet API token. You can also supply it in environment variable E(PACKET_API_TOKEN).
38 type: str
39
40 count:
41 description:
42 - The number of devices to create. Count number can be included in hostname using the C(%d) string formatter.
43 default: 1
44 type: int
45
46 count_offset:
47 description:
48 - From which number to start the count.
49 default: 1
50 type: int
51
52 device_ids:
53 description:
54 - List of device IDs on which to operate.
55 type: list
56 elements: str
57
58 tags:
59 description:
60 - List of device tags.
61 - Currently implemented only for device creation.
62 type: list
63 elements: str
64 version_added: '0.2.0'
65
66 facility:
67 description:
68 - Facility slug for device creation. See Packet API for current list - U(https://www.packet.net/developers/api/facilities/).
69 type: str
70
71 features:
72 description:
73 - Dict with "features" for device creation. See Packet API docs for details.
74 type: dict
75
76 hostnames:
77 description:
78 - A hostname of a device, or a list of hostnames.
79 - If given string or one-item list, you can use the C("%d") Python string format to expand numbers from O(count).
80 - If only one hostname, it might be expanded to list if O(count)>1.
81 aliases: [name]
82 type: list
83 elements: str
84
85 locked:
86 description:
87 - Whether to lock a created device.
88 default: false
89 aliases: [lock]
90 type: bool
91
92 operating_system:
93 description:
94 - OS slug for device creation. See Packet API for current list - U(https://www.packet.net/developers/api/operatingsystems/).
95 type: str
96
97 plan:
98 description:
99 - Plan slug for device creation. See Packet API for current list - U(https://www.packet.net/developers/api/plans/).
100 type: str
101
102 project_id:
103 description:
104 - ID of project of the device.
105 required: true
106 type: str
107
108 state:
109 description:
110 - Desired state of the device.
111 - If set to V(present) (the default), the module call returns immediately after the device-creating HTTP request successfully
112 returns.
113 - If set to V(active), the module call blocks until all the specified devices are in state active due to the Packet
114 API, or until O(wait_timeout).
115 choices: [present, absent, active, inactive, rebooted]
116 default: present
117 type: str
118
119 user_data:
120 description:
121 - Userdata blob made available to the machine.
122 type: str
123
124 wait_for_public_IPv:
125 description:
126 - Whether to wait for the instance to be assigned a public IPv4/IPv6 address.
127 - If set to V(4), it waits until IPv4 is assigned to the instance.
128 - If set to V(6), it waits until public IPv6 is assigned to the instance.
129 choices: [4, 6]
130 type: int
131
132 wait_timeout:
133 description:
134 - How long (seconds) to wait either for automatic IP address assignment, or for the device to reach the V(active) state.
135 - If O(wait_for_public_IPv) is set and O(state=active), the module waits for both events consequently, applying the
136 timeout twice.
137 default: 900
138 type: int
139
140 ipxe_script_url:
141 description:
142 - URL of custom iPXE script for provisioning.
143 - More about custom iPXE for Packet devices at U(https://help.packet.net/technical/infrastructure/custom-ipxe).
144 type: str
145 default: ''
146
147 always_pxe:
148 description:
149 - Persist PXE as the first boot option.
150 - Normally, the PXE process happens only on the first boot. Set this arg to have your device continuously boot to iPXE.
151 default: false
152 type: bool
153
154
155 requirements:
156 - "packet-python >= 1.35"
157 """
158
159 EXAMPLES = r"""
160 # All the examples assume that you have your Packet API token in environment variable PACKET_API_TOKEN.
161 # You can also pass it to the auth_token parameter of the module instead.
162
163 # Creating devices
164
165 - name: Create 1 device
166 hosts: localhost
167 tasks:
168 - community.general.packet_device:
169 project_id: 89b497ee-5afc-420a-8fb5-56984898f4df
170 hostnames: myserver
171 tags: ci-xyz
172 operating_system: ubuntu_16_04
173 plan: baremetal_0
174 facility: sjc1
175
176 # Create the same device and wait until it is in state "active", (when it is
177 # ready for other API operations). Fail if the device is not "active" in
178 # 10 minutes.
179
180 - name: Create device and wait up to 10 minutes for active state
181 hosts: localhost
182 tasks:
183 - community.general.packet_device:
184 project_id: 89b497ee-5afc-420a-8fb5-56984898f4df
185 hostnames: myserver
186 operating_system: ubuntu_16_04
187 plan: baremetal_0
188 facility: sjc1
189 state: active
190 wait_timeout: 600
191
192 - name: Create 3 ubuntu devices called server-01, server-02 and server-03
193 hosts: localhost
194 tasks:
195 - community.general.packet_device:
196 project_id: 89b497ee-5afc-420a-8fb5-56984898f4df
197 hostnames: server-%02d
198 count: 3
199 operating_system: ubuntu_16_04
200 plan: baremetal_0
201 facility: sjc1
202
203 - name: Create 3 coreos devices with userdata, wait until they get IPs and then wait for SSH
204 hosts: localhost
205 tasks:
206 - name: Create 3 devices and register their facts
207 community.general.packet_device:
208 hostnames: [coreos-one, coreos-two, coreos-three]
209 operating_system: coreos_stable
210 plan: baremetal_0
211 facility: ewr1
212 locked: true
213 project_id: 89b497ee-5afc-420a-8fb5-56984898f4df
214 wait_for_public_IPv: 4
215 user_data: |
216 #cloud-config
217 ssh_authorized_keys:
218 - {{ lookup('file', 'my_packet_sshkey') }}
219 coreos:
220 etcd:
221 discovery: https://discovery.etcd.io/6a28e078895c5ec737174db2419bb2f3
222 addr: $private_ipv4:4001
223 peer-addr: $private_ipv4:7001
224 fleet:
225 public-ip: $private_ipv4
226 units:
227 - name: etcd.service
228 command: start
229 - name: fleet.service
230 command: start
231 register: newhosts
232
233 - name: Wait for ssh
234 ansible.builtin.wait_for:
235 delay: 1
236 host: "{{ item.public_ipv4 }}"
237 port: 22
238 state: started
239 timeout: 500
240 with_items: "{{ newhosts.devices }}"
241
242
243 # Other states of devices
244
245 - name: Remove 3 devices by uuid
246 hosts: localhost
247 tasks:
248 - community.general.packet_device:
249 project_id: 89b497ee-5afc-420a-8fb5-56984898f4df
250 state: absent
251 device_ids:
252 - 1fb4faf8-a638-4ac7-8f47-86fe514c30d8
253 - 2eb4faf8-a638-4ac7-8f47-86fe514c3043
254 - 6bb4faf8-a638-4ac7-8f47-86fe514c301f
255 """
256
257 RETURN = r"""
258 devices:
259 description: Information about each device that was processed.
260 type: list
261 sample:
262 - "hostname": "my-server.com"
263 "id": "2a5122b9-c323-4d5c-b53c-9ad3f54273e7"
264 "public_ipv4": "147.229.15.12"
265 "private-ipv4": "10.0.15.12"
266 "tags": []
267 "locked": false
268 "state": "provisioning"
269 "public_ipv6": "2604:1380:2:5200::3"
270 returned: success
271 """
272
273
274 import os
275 import re
276 import time
277 import traceback
278 import uuid
279
280 from ansible.module_utils.basic import AnsibleModule
281
282 HAS_PACKET_SDK = True
283 try:
284 import packet
285 except ImportError:
286 HAS_PACKET_SDK = False
287
288
289 NAME_RE = r"([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])"
290 HOSTNAME_RE = rf"({NAME_RE}\.)*{NAME_RE}$"
291 MAX_DEVICES = 100
292
293 PACKET_DEVICE_STATES = (
294 "queued",
295 "provisioning",
296 "failed",
297 "powering_on",
298 "active",
299 "powering_off",
300 "inactive",
301 "rebooting",
302 )
303
304 PACKET_API_TOKEN_ENV_VAR = "PACKET_API_TOKEN"
305
306
307 ALLOWED_STATES = ["absent", "active", "inactive", "rebooted", "present"]
308
309
310 def serialize_device(device):
311 """
312 Standard representation for a device as returned by various tasks::
313
314 {
315 'id': 'device_id'
316 'hostname': 'device_hostname',
317 'tags': [],
318 'locked': false,
319 'state': 'provisioning',
320 'ip_addresses': [
321 {
322 "address": "147.75.194.227",
323 "address_family": 4,
324 "public": true
325 },
326 {
327 "address": "2604:1380:2:5200::3",
328 "address_family": 6,
329 "public": true
330 },
331 {
332 "address": "10.100.11.129",
333 "address_family": 4,
334 "public": false
335 }
336 ],
337 "private_ipv4": "10.100.11.129",
338 "public_ipv4": "147.75.194.227",
339 "public_ipv6": "2604:1380:2:5200::3",
340 }
341
342 """
343 device_data = {}
344 device_data["id"] = device.id
345 device_data["hostname"] = device.hostname
346 device_data["tags"] = device.tags
347 device_data["locked"] = device.locked
348 device_data["state"] = device.state
349 device_data["ip_addresses"] = [
350 {
351 "address": addr_data["address"],
352 "address_family": addr_data["address_family"],
353 "public": addr_data["public"],
354 }
355 for addr_data in device.ip_addresses
356 ]
357 # Also include each IPs as a key for easier lookup in roles.
358 # Key names:
359 # - public_ipv4
360 # - public_ipv6
361 # - private_ipv4
362 # - private_ipv6 (if there is one)
363 for ipdata in device_data["ip_addresses"]:
364 if ipdata["public"]:
365 if ipdata["address_family"] == 6:
366 device_data["public_ipv6"] = ipdata["address"]
367 elif ipdata["address_family"] == 4:
368 device_data["public_ipv4"] = ipdata["address"]
369 elif not ipdata["public"]:
370 if ipdata["address_family"] == 6:
371 # Packet doesn't give public ipv6 yet, but maybe one
372 # day they will
373 device_data["private_ipv6"] = ipdata["address"]
374 elif ipdata["address_family"] == 4:
375 device_data["private_ipv4"] = ipdata["address"]
376 return device_data
377
378
379 def is_valid_hostname(hostname):
380 return re.match(HOSTNAME_RE, hostname) is not None
381
382
383 def is_valid_uuid(myuuid):
384 try:
385 val = uuid.UUID(myuuid, version=4)
386 except ValueError:
387 return False
388 return str(val) == myuuid
389
390
391 def listify_string_name_or_id(s):
392 if "," in s:
393 return s.split(",")
394 else:
395 return [s]
396
397
398 def get_hostname_list(module):
399 # hostname is a list-typed param, so I guess it should return list
400 # (and it does, in Ansible 2.2.1) but in order to be defensive,
401 # I keep here the code to convert an eventual string to list
402 hostnames = module.params.get("hostnames")
403 count = module.params.get("count")
404 count_offset = module.params.get("count_offset")
405 if isinstance(hostnames, str):
406 hostnames = listify_string_name_or_id(hostnames)
407 if not isinstance(hostnames, list):
408 raise Exception(f"name {hostnames} is not convertible to list")
409
410 # at this point, hostnames is a list
411 hostnames = [h.strip() for h in hostnames]
412
413 if len(hostnames) > 1 and count > 1:
414 _msg = (
415 "If you set count>1, you should only specify one hostname with the %d formatter, not a list of hostnames."
416 )
417 raise Exception(_msg)
418
419 if len(hostnames) == 1 and count > 0:
420 hostname_spec = hostnames[0]
421 count_range = range(count_offset, count_offset + count)
422 if re.search(r"%\d{0,2}d", hostname_spec):
423 hostnames = [hostname_spec % i for i in count_range]
424 elif count > 1:
425 hostnames = [f"{hostname_spec}{i:02}" for i in count_range]
426
427 for hn in hostnames:
428 if not is_valid_hostname(hn):
429 raise Exception(f"Hostname '{hn}' does not seem to be valid")
430
431 if len(hostnames) > MAX_DEVICES:
432 raise Exception(f"You specified too many hostnames, max is {MAX_DEVICES}")
433 return hostnames
434
435
436 def get_device_id_list(module):
437 device_ids = module.params.get("device_ids")
438
439 if isinstance(device_ids, str):
440 device_ids = listify_string_name_or_id(device_ids)
441
442 device_ids = [di.strip() for di in device_ids]
443
444 for di in device_ids:
445 if not is_valid_uuid(di):
446 raise Exception(f"Device ID '{di}' does not seem to be valid")
447
448 if len(device_ids) > MAX_DEVICES:
449 raise Exception(f"You specified too many devices, max is {MAX_DEVICES}")
450 return device_ids
451
452
453 def create_single_device(module, packet_conn, hostname):
454 for param in ("hostnames", "operating_system", "plan"):
455 if not module.params.get(param):
456 raise Exception(f"{param} parameter is required for new device.")
457 project_id = module.params.get("project_id")
458 plan = module.params.get("plan")
459 tags = module.params.get("tags")
460 user_data = module.params.get("user_data")
461 facility = module.params.get("facility")
462 operating_system = module.params.get("operating_system")
463 locked = module.params.get("locked")
464 ipxe_script_url = module.params.get("ipxe_script_url")
465 always_pxe = module.params.get("always_pxe")
466 if operating_system != "custom_ipxe":
467 for param in ("ipxe_script_url", "always_pxe"):
468 if module.params.get(param):
469 raise Exception(f"{param} parameter is not valid for non custom_ipxe operating_system.")
470
471 device = packet_conn.create_device(
472 project_id=project_id,
473 hostname=hostname,
474 tags=tags,
475 plan=plan,
476 facility=facility,
477 operating_system=operating_system,
478 userdata=user_data,
479 locked=locked,
480 ipxe_script_url=ipxe_script_url,
481 always_pxe=always_pxe,
482 )
483 return device
484
485
486 def refresh_device_list(module, packet_conn, devices):
487 device_ids = [d.id for d in devices]
488 new_device_list = get_existing_devices(module, packet_conn)
489 return [d for d in new_device_list if d.id in device_ids]
490
491
492 def wait_for_devices_active(module, packet_conn, watched_devices):
493 wait_timeout = module.params.get("wait_timeout")
494 wait_timeout = time.time() + wait_timeout
495 refreshed = watched_devices
496 while wait_timeout > time.time():
497 refreshed = refresh_device_list(module, packet_conn, watched_devices)
498 if all(d.state == "active" for d in refreshed):
499 return refreshed
500 time.sleep(5)
501 timed_out_devices = [d.hostname for d in refreshed if d.state != "active"]
502 raise Exception(f'Waiting for state "active" timed out for devices: {timed_out_devices}')
503
504
505 def wait_for_public_IPv(module, packet_conn, created_devices):
506 def has_public_ip(addr_list, ip_v):
507 return any(a["public"] and a["address_family"] == ip_v and a["address"] for a in addr_list)
508
509 def all_have_public_ip(ds, ip_v):
510 return all(has_public_ip(d.ip_addresses, ip_v) for d in ds)
511
512 address_family = module.params.get("wait_for_public_IPv")
513
514 wait_timeout = module.params.get("wait_timeout")
515 wait_timeout = time.time() + wait_timeout
516 while wait_timeout > time.time():
517 refreshed = refresh_device_list(module, packet_conn, created_devices)
518 if all_have_public_ip(refreshed, address_family):
519 return refreshed
520 time.sleep(5)
521
522 raise Exception(
523 f"Waiting for IPv{address_family} address timed out. Hostnames: {[d.hostname for d in created_devices]}"
524 )
525
526
527 def get_existing_devices(module, packet_conn):
528 project_id = module.params.get("project_id")
529 return packet_conn.list_devices(project_id, params={"per_page": MAX_DEVICES})
530
531
532 def get_specified_device_identifiers(module):
533 if module.params.get("device_ids"):
534 device_id_list = get_device_id_list(module)
535 return {"ids": device_id_list, "hostnames": []}
536 elif module.params.get("hostnames"):
537 hostname_list = get_hostname_list(module)
538 return {"hostnames": hostname_list, "ids": []}
539
540
541 def act_on_devices(module, packet_conn, target_state):
542 specified_identifiers = get_specified_device_identifiers(module)
543 existing_devices = get_existing_devices(module, packet_conn)
544 changed = False
545 create_hostnames = []
546 if target_state in ["present", "active", "rebooted"]:
547 # states where we might create non-existing specified devices
548 existing_devices_names = [ed.hostname for ed in existing_devices]
549 create_hostnames = [hn for hn in specified_identifiers["hostnames"] if hn not in existing_devices_names]
550
551 process_devices = [
552 d
553 for d in existing_devices
554 if (d.id in specified_identifiers["ids"]) or (d.hostname in specified_identifiers["hostnames"])
555 ]
556
557 if target_state != "present":
558 _absent_state_map = {}
559 for s in PACKET_DEVICE_STATES:
560 _absent_state_map[s] = packet.Device.delete
561
562 state_map = {
563 "absent": _absent_state_map,
564 "active": {"inactive": packet.Device.power_on, "provisioning": None, "rebooting": None},
565 "inactive": {"active": packet.Device.power_off},
566 "rebooted": {
567 "active": packet.Device.reboot,
568 "inactive": packet.Device.power_on,
569 "provisioning": None,
570 "rebooting": None,
571 },
572 }
573
574 # First do non-creation actions, it might be faster
575 for d in process_devices:
576 if d.state == target_state:
577 continue
578 if d.state in state_map[target_state]:
579 api_operation = state_map[target_state].get(d.state)
580 if api_operation is not None:
581 api_operation(d)
582 changed = True
583 else:
584 _msg = f"I don't know how to process existing device {d.hostname} from state {d.state} to state {target_state}"
585 raise Exception(_msg)
586
587 # At last create missing devices
588 created_devices = []
589 if create_hostnames:
590 created_devices = [create_single_device(module, packet_conn, n) for n in create_hostnames]
591 if module.params.get("wait_for_public_IPv"):
592 created_devices = wait_for_public_IPv(module, packet_conn, created_devices)
593 changed = True
594
595 processed_devices = created_devices + process_devices
596 if target_state == "active":
597 processed_devices = wait_for_devices_active(module, packet_conn, processed_devices)
598
599 return {"changed": changed, "devices": [serialize_device(d) for d in processed_devices]}
600
601
602 def main():
603 module = AnsibleModule(
604 argument_spec=dict(
605 auth_token=dict(default=os.environ.get(PACKET_API_TOKEN_ENV_VAR), no_log=True),
606 count=dict(type="int", default=1),
607 count_offset=dict(type="int", default=1),
608 device_ids=dict(type="list", elements="str"),
609 facility=dict(),
610 features=dict(type="dict"),
611 hostnames=dict(type="list", elements="str", aliases=["name"]),
612 tags=dict(type="list", elements="str"),
613 locked=dict(type="bool", default=False, aliases=["lock"]),
614 operating_system=dict(),
615 plan=dict(),
616 project_id=dict(required=True),
617 state=dict(choices=ALLOWED_STATES, default="present"),
618 user_data=dict(),
619 wait_for_public_IPv=dict(type="int", choices=[4, 6]),
620 wait_timeout=dict(type="int", default=900),
621 ipxe_script_url=dict(default=""),
622 always_pxe=dict(type="bool", default=False),
623 ),
624 required_one_of=[
625 (
626 "device_ids",
627 "hostnames",
628 )
629 ],
630 mutually_exclusive=[
631 ("hostnames", "device_ids"),
632 ("count", "device_ids"),
633 ("count_offset", "device_ids"),
634 ],
635 )
636
637 if not HAS_PACKET_SDK:
638 module.fail_json(msg="packet required for this module")
639
640 if not module.params.get("auth_token"):
641 _fail_msg = f"if Packet API token is not in environment variable {PACKET_API_TOKEN_ENV_VAR}, the auth_token parameter is required"
642 module.fail_json(msg=_fail_msg)
643
644 auth_token = module.params.get("auth_token")
645
646 packet_conn = packet.Manager(auth_token=auth_token)
647
648 state = module.params.get("state")
649
650 try:
651 module.exit_json(**act_on_devices(module, packet_conn, state))
652 except Exception as e:
653 module.fail_json(msg=f"failed to set device state {state}, error: {e}", exception=traceback.format_exc())
654
655
656 if __name__ == "__main__":
657 main()