Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2016, Fabrizio Colonna <[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 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 author:
11 - Fabrizio Colonna (@ColOfAbRiX)
12 module: parted
13 short_description: Configure block device partitions
14 description:
15 - This module allows configuring block device partition using the C(parted) command line tool. For a full description of
16 the fields and the options check the GNU parted manual.
17 requirements:
18 - This module requires C(parted) version 1.8.3 and above.
19 - Option O(align) (except V(undefined)) requires C(parted) 2.1 or above.
20 - If the version of C(parted) is below 3.1, it requires a Linux version running the C(sysfs) file system C(/sys/).
21 - Requires the C(resizepart) command when using the O(resize) parameter.
22 extends_documentation_fragment:
23 - community.general._attributes
24 attributes:
25 check_mode:
26 support: full
27 diff_mode:
28 support: none
29 options:
30 device:
31 description:
32 - The block device (disk) where to operate.
33 - Regular files can also be partitioned, but it is recommended to create a loopback device using C(losetup) to easily
34 access its partitions.
35 type: str
36 required: true
37 align:
38 description:
39 - Set alignment for newly created partitions. Use V(undefined) for parted default alignment.
40 type: str
41 choices: [cylinder, minimal, none, optimal, undefined]
42 default: optimal
43 number:
44 description:
45 - The partition number being affected.
46 - Required when performing any action on the disk, except fetching information.
47 type: int
48 unit:
49 description:
50 - Selects the current default unit that Parted uses to display locations and capacities on the disk and to interpret
51 those given by the user if they are not suffixed by an unit.
52 - When fetching information about a disk, it is recommended to always specify a unit.
53 - O(unit_preserve_case) controls the case of the units in the return values. It used to be all lower case, but using that option you
54 can make it return the units textually equal to the choices used in O(unit).
55 type: str
56 choices: [s, B, KB, KiB, MB, MiB, GB, GiB, TB, TiB, '%', cyl, chs, compact]
57 default: KiB
58 label:
59 description:
60 - Disk label type or partition table to use.
61 - If O(device) already contains a different label, it is changed to O(label) and any previous partitions are lost.
62 - A O(name) must be specified for a V(gpt) partition table.
63 type: str
64 choices: [aix, amiga, bsd, dvh, gpt, loop, mac, msdos, pc98, sun]
65 default: msdos
66 part_type:
67 description:
68 - May be specified only with O(label=msdos) or O(label=dvh).
69 - Neither O(part_type) nor O(name) may be used with O(label=sun).
70 type: str
71 choices: [extended, logical, primary]
72 default: primary
73 part_start:
74 description:
75 - Where the partition starts as offset from the beginning of the disk, that is, the "distance" from the start of the
76 disk. Negative numbers specify distance from the end of the disk.
77 - The distance can be specified with all the units supported by parted (except compat) and it is case sensitive, for
78 example V(10GiB), V(15%).
79 - Using negative values may require setting of O(fs_type) (see notes).
80 type: str
81 default: 0%
82 part_end:
83 description:
84 - Where the partition ends as offset from the beginning of the disk, that is, the "distance" from the start of the disk.
85 Negative numbers specify distance from the end of the disk.
86 - The distance can be specified with all the units supported by parted (except compat) and it is case sensitive, for
87 example V(10GiB), V(15%).
88 type: str
89 default: 100%
90 name:
91 description:
92 - Sets the name for the partition number (GPT, Mac, MIPS and PC98 only).
93 type: str
94 flags:
95 description: A list of the flags that has to be set on the partition.
96 type: list
97 elements: str
98 state:
99 description:
100 - Whether to create or delete a partition.
101 - If set to V(info) the module only returns the device information.
102 type: str
103 choices: [absent, present, info]
104 default: info
105 fs_type:
106 description:
107 - If specified and the partition does not exist, sets filesystem type to given partition.
108 - Parameter optional, but see notes below about negative O(part_start) values.
109 type: str
110 version_added: '0.2.0'
111 resize:
112 description:
113 - Call C(resizepart) on existing partitions to match the size specified by O(part_end).
114 type: bool
115 default: false
116 version_added: '1.3.0'
117 unit_preserve_case:
118 description:
119 - Controls the case of the V(unit) field in the module output (RV(ignore:partition_info.disk.unit), RV(ignore:partition_info.partitions[].unit)).
120 - When V(true), the unit is returned in its original mixed case, for example V(KiB) or V(MiB). This matches the values
121 accepted by O(unit), making it safe to feed the output back as input.
122 - When V(false), the unit is returned in lowercase (legacy behavior), for example V(kib) or V(mib).
123 # - When not set, the module uses the legacy lowercase behavior and emits a deprecation warning. The default will change
124 # to V(true) in community.general 15.0.0.
125 type: bool
126 default: false
127 version_added: '12.6.0'
128
129 notes:
130 - When fetching information about a new disk and when the version of parted installed on the system is before version 3.1,
131 the module queries the kernel through C(/sys/) to obtain disk information. In this case the units CHS and CYL are not
132 supported.
133 - Negative O(part_start) start values were rejected if O(fs_type) was not given. This bug was fixed in parted 3.2.153. If
134 you want to use negative O(part_start), specify O(fs_type) as well or make sure your system contains newer parted.
135 """
136
137 RETURN = r"""
138 disk:
139 description: Generic device information.
140 type: dict
141 returned: success
142 sample:
143 "dev": "/dev/sdb"
144 "logical_block": 512
145 "model": "VMware Virtual disk"
146 "physical_block": 512
147 "size": 5.0
148 "table": "msdos"
149 "unit": "GiB"
150 partitions:
151 description: List of device partitions.
152 type: list
153 elements: dict
154 returned: success
155 sample:
156 - "begin": 0.0
157 "end": 1.0
158 "flags": ["boot", "lvm"]
159 "fstype": ""
160 "name": ""
161 "num": 1
162 "size": 1.0
163 - "begin": 1.0
164 "end": 5.0
165 "flags": []
166 "fstype": ""
167 "name": ""
168 "num": 2
169 "size": 4.0
170 script:
171 description: Parted script executed by module.
172 type: str
173 returned: success
174 sample: "unit KiB print "
175 """
176
177 EXAMPLES = r"""
178 - name: Create a new ext4 primary partition
179 community.general.parted:
180 device: /dev/sdb
181 number: 1
182 state: present
183 fs_type: ext4
184
185 - name: Remove partition number 1
186 community.general.parted:
187 device: /dev/sdb
188 number: 1
189 state: absent
190
191 - name: Create a new primary partition with a size of 1GiB
192 community.general.parted:
193 device: /dev/sdb
194 number: 1
195 state: present
196 part_end: 1GiB
197
198 - name: Create a new primary partition for LVM
199 community.general.parted:
200 device: /dev/sdb
201 number: 2
202 flags: [lvm]
203 state: present
204 part_start: 1GiB
205
206 - name: Create a new primary partition with a size of 1GiB at disk's end
207 community.general.parted:
208 device: /dev/sdb
209 number: 3
210 state: present
211 fs_type: ext3
212 part_start: -1GiB
213
214 # Example on how to read info and reuse it in subsequent task
215 - name: Read device information (always use unit when probing)
216 community.general.parted: device=/dev/sdb unit=MiB
217 register: sdb_info
218
219 - name: Remove all partitions from disk
220 community.general.parted:
221 device: /dev/sdb
222 number: '{{ item.num }}'
223 state: absent
224 loop: '{{ sdb_info.partitions }}'
225
226 - name: Extend an existing partition to fill all available space
227 community.general.parted:
228 device: /dev/sdb
229 number: "{{ sdb_info.partitions | length }}"
230 part_end: "100%"
231 resize: true
232 state: present
233 """
234
235
236 import math
237 import os
238 import re
239
240 from ansible.module_utils.basic import AnsibleModule
241
242 # Reference prefixes (International System of Units and IEC)
243 units_si = ["B", "KB", "MB", "GB", "TB"]
244 units_iec = ["KiB", "MiB", "GiB", "TiB"]
245 parted_units = units_si + units_iec + ["s", "%", "cyl", "chs", "compact"]
246 _parted_units_lower = {u.lower(): u for u in parted_units}
247
248
249 def canonical_unit(unit):
250 """Return the canonical mixed-case form of a parted unit string."""
251 return _parted_units_lower.get(unit.lower(), unit)
252
253
254 def parse_unit(size_str, unit=""):
255 """
256 Parses a string containing a size or boundary information
257 """
258 matches = re.search(r"^(-?[\d.]+) *([\w%]+)?$", size_str)
259 if matches is None:
260 # "<cylinder>,<head>,<sector>" format
261 matches = re.search(r"^(\d+),(\d+),(\d+)$", size_str)
262 if matches is None:
263 module.fail_json(msg=f"Error interpreting parted size output: '{size_str}'")
264
265 size = {"cylinder": int(matches.group(1)), "head": int(matches.group(2)), "sector": int(matches.group(3))}
266 unit = "chs"
267
268 else:
269 # Normal format: "<number>[<unit>]"
270 if matches.group(2) is not None:
271 unit = matches.group(2)
272
273 size = float(matches.group(1))
274
275 return size, unit
276
277
278 def parse_partition_info(parted_output, unit, unit_preserve_case):
279 """
280 Parses the output of parted and transforms the data into
281 a dictionary.
282
283 Parted Machine Parseable Output:
284 See: https://lists.alioth.debian.org/pipermail/parted-devel/2006-December/00
285 0573.html
286 - All lines end with a semicolon (;)
287 - The first line indicates the units in which the output is expressed.
288 CHS, CYL and BYT stands for CHS, Cylinder and Bytes respectively.
289 - The second line is made of disk information in the following format:
290 "path":"size":"transport-type":"logical-sector-size":"physical-sector-siz
291 e":"partition-table-type":"model-name";
292 - If the first line was either CYL or CHS, the next line will contain
293 information on no. of cylinders, heads, sectors and cylinder size.
294 - Partition information begins from the next line. This is of the format:
295 (for BYT)
296 "number":"begin":"end":"size":"filesystem-type":"partition-name":"flags-s
297 et";
298 (for CHS/CYL)
299 "number":"begin":"end":"filesystem-type":"partition-name":"flags-set";
300 """
301 lines = [x for x in parted_output.split("\n") if x.strip() != ""]
302
303 # Generic device info
304 generic_params = lines[1].rstrip(";").split(":")
305
306 # The unit is read once, because parted always returns the same unit
307 size, unit = parse_unit(generic_params[1], unit)
308
309 unit_output = canonical_unit(unit) if unit_preserve_case else unit.lower()
310 generic = {
311 "dev": generic_params[0],
312 "size": size,
313 "unit": unit_output,
314 "table": generic_params[5],
315 "model": generic_params[6],
316 "logical_block": int(generic_params[3]),
317 "physical_block": int(generic_params[4]),
318 }
319
320 # CYL and CHS have an additional line in the output
321 if unit in ["cyl", "chs"]:
322 chs_info = lines[2].rstrip(";").split(":")
323 cyl_size, cyl_unit = parse_unit(chs_info[3])
324 generic["chs_info"] = {
325 "cylinders": int(chs_info[0]),
326 "heads": int(chs_info[1]),
327 "sectors": int(chs_info[2]),
328 "cyl_size": cyl_size,
329 "cyl_size_unit": canonical_unit(cyl_unit) if unit_preserve_case else cyl_unit.lower(),
330 }
331 lines = lines[1:]
332
333 parts = []
334 for line in lines[2:]:
335 part_params = line.rstrip(";").split(":")
336
337 # CHS use a different format than BYT, but contrary to what stated by
338 # the author, CYL is the same as BYT. I've tested this undocumented
339 # behaviour down to parted version 1.8.3, which is the first version
340 # that supports the machine parseable output.
341 if unit != "chs":
342 size = parse_unit(part_params[3])[0]
343 fstype = part_params[4]
344 name = part_params[5]
345 flags = part_params[6]
346
347 else:
348 size = ""
349 fstype = part_params[3]
350 name = part_params[4]
351 flags = part_params[5]
352
353 parts.append(
354 {
355 "num": int(part_params[0]),
356 "begin": parse_unit(part_params[1])[0],
357 "end": parse_unit(part_params[2])[0],
358 "size": size,
359 "fstype": fstype,
360 "name": name,
361 "flags": [f.strip() for f in flags.split(", ") if f != ""],
362 "unit": unit_output,
363 }
364 )
365
366 return {"generic": generic, "partitions": parts}
367
368
369 def format_disk_size(size_bytes, unit):
370 """
371 Formats a size in bytes into a different unit, like parted does. It doesn't
372 manage CYL and CHS formats, though.
373 This function has been adapted from https://github.com/Distrotech/parted/blo
374 b/279d9d869ff472c52b9ec2e180d568f0c99e30b0/libparted/unit.c
375 """
376 global units_si, units_iec # pylint: disable=global-variable-not-assigned
377
378 unit = unit.lower()
379
380 # Shortcut
381 if size_bytes == 0:
382 return 0.0, "b"
383
384 # Cases where we default to 'compact'
385 if unit in ["", "compact", "cyl", "chs"]:
386 index = max(0, int((math.log10(size_bytes) - 1.0) / 3.0))
387 unit = "b"
388 if index < len(units_si):
389 unit = units_si[index]
390
391 # Find the appropriate multiplier
392 multiplier = 1.0
393 if unit in units_si:
394 multiplier = 1000.0 ** units_si.index(unit)
395 elif unit in units_iec:
396 multiplier = 1024.0 ** units_iec.index(unit)
397
398 output = size_bytes // multiplier * (1 + 1e-16)
399
400 # Corrections to round up as per IEEE754 standard
401 if output < 10:
402 w = output + 0.005
403 elif output < 100:
404 w = output + 0.05
405 else:
406 w = output + 0.5
407
408 if w < 10:
409 precision = 2
410 elif w < 100:
411 precision = 1
412 else:
413 precision = 0
414
415 # Round and return
416 return round(output, precision), unit
417
418
419 def convert_to_bytes(size_str, unit):
420 size = float(size_str)
421 multiplier = 1.0
422 if unit in units_si:
423 multiplier = 1000.0 ** units_si.index(unit)
424 elif unit in units_iec:
425 multiplier = 1024.0 ** (units_iec.index(unit) + 1)
426 elif unit in ["", "compact", "cyl", "chs"]:
427 # As per format_disk_size, default to compact, which defaults to megabytes
428 multiplier = 1000.0 ** units_si.index("MB")
429
430 output = size * multiplier
431 return int(output)
432
433
434 def get_unlabeled_device_info(device, unit, unit_preserve_case):
435 """
436 Fetches device information directly from the kernel and it is used when
437 parted cannot work because of a missing label. It always returns a 'unknown'
438 label.
439 """
440 device_name = os.path.basename(device)
441 base = f"/sys/block/{device_name}"
442
443 vendor = read_record(f"{base}/device/vendor", "Unknown")
444 model = read_record(f"{base}/device/model", "model")
445 logic_block = int(read_record(f"{base}/queue/logical_block_size", 0))
446 phys_block = int(read_record(f"{base}/queue/physical_block_size", 0))
447 size_bytes = int(read_record(f"{base}/size", 0)) * logic_block
448
449 size, unit = format_disk_size(size_bytes, unit)
450 if unit_preserve_case:
451 unit = canonical_unit(unit)
452
453 return {
454 "generic": {
455 "dev": device,
456 "table": "unknown",
457 "size": size,
458 "unit": unit,
459 "logical_block": logic_block,
460 "physical_block": phys_block,
461 "model": f"{vendor} {model}",
462 },
463 "partitions": [],
464 }
465
466
467 def get_device_info(device, unit, unit_preserve_case):
468 """
469 Fetches information about a disk and its partitions and it returns a
470 dictionary.
471 """
472 global module, parted_exec # pylint: disable=global-variable-not-assigned
473
474 # If parted complains about missing labels, it means there are no partitions.
475 # In this case only, use a custom function to fetch information and emulate
476 # parted formats for the unit.
477 label_needed = check_parted_label(device)
478 if label_needed:
479 return get_unlabeled_device_info(device, unit, unit_preserve_case)
480
481 command = [parted_exec, "-s", "-m", device, "--", "unit", unit, "print"]
482 rc, out, err = module.run_command(command)
483 if rc != 0 and "unrecognised disk label" not in err:
484 module.fail_json(
485 msg=(f"Error while getting device information with parted script: '{' '.join(command)}'"),
486 rc=rc,
487 out=out,
488 err=err,
489 )
490
491 return parse_partition_info(out, unit, unit_preserve_case)
492
493
494 def check_parted_label(device):
495 """
496 Determines if parted needs a label to complete its duties. Versions prior
497 to 3.1 don't return data when there is no label. For more information see:
498 http://upstream.rosalinux.ru/changelogs/libparted/3.1/changelog.html
499 """
500 global parted_exec # pylint: disable=global-variable-not-assigned
501
502 # Check the version
503 parted_major, parted_minor, dummy = parted_version()
504 if (parted_major == 3 and parted_minor >= 1) or parted_major > 3:
505 return False
506
507 # Older parted versions return a message in the stdout and RC > 0.
508 rc, out, err = module.run_command([parted_exec, "-s", "-m", device, "print"])
509 return rc != 0 and "unrecognised disk label" in out.lower()
510
511
512 def parse_parted_version(out):
513 """
514 Returns version tuple from the output of "parted --version" command
515 """
516 lines = [x for x in out.split("\n") if x.strip() != ""]
517 if len(lines) == 0:
518 return None, None, None
519
520 # Sample parted versions (see as well test unit):
521 # parted (GNU parted) 3.3
522 # parted (GNU parted) 3.4.5
523 # parted (GNU parted) 3.3.14-dfc61
524 matches = re.search(r"^parted.+\s(\d+)\.(\d+)(?:\.(\d+))?", lines[0].strip())
525
526 if matches is None:
527 return None, None, None
528
529 # Convert version to numbers
530 major = int(matches.group(1))
531 minor = int(matches.group(2))
532 rev = 0
533 if matches.group(3) is not None:
534 rev = int(matches.group(3))
535
536 return major, minor, rev
537
538
539 def parted_version():
540 """
541 Returns the major and minor version of parted installed on the system.
542 """
543 global module, parted_exec # pylint: disable=global-variable-not-assigned
544
545 rc, out, err = module.run_command([parted_exec, "--version"])
546 if rc != 0:
547 module.fail_json(msg="Failed to get parted version.", rc=rc, out=out, err=err)
548
549 (major, minor, rev) = parse_parted_version(out)
550 if major is None:
551 module.fail_json(msg="Failed to get parted version.", rc=0, out=out)
552
553 return major, minor, rev
554
555
556 def parted(script, device, align):
557 """
558 Runs a parted script.
559 """
560 global module, parted_exec # pylint: disable=global-variable-not-assigned
561
562 align_option = ["-a", align]
563 if align == "undefined":
564 align_option = []
565
566 """
567 Use option --fix (-f) if available. Versions prior
568 to 3.4.64 don't have it. For more information see:
569 http://savannah.gnu.org/news/?id=10114
570 """
571 if parted_version() >= (3, 4, 64):
572 script_option = ["-s", "-f"]
573 else:
574 script_option = ["-s"]
575
576 if script and not module.check_mode:
577 command = [parted_exec] + script_option + ["-m"] + align_option + [device, "--"] + script
578 rc, out, err = module.run_command(command)
579
580 if rc != 0:
581 module.fail_json(
582 msg=f"Error while running parted script: {' '.join(command).strip()}", rc=rc, out=out, err=err
583 )
584
585
586 def read_record(file_path, default=None):
587 """
588 Reads the first line of a file and returns it.
589 """
590 try:
591 with open(file_path) as f:
592 return f.readline().strip()
593 except OSError:
594 return default
595
596
597 def part_exists(partitions, attribute, number):
598 """
599 Looks if a partition that has a specific value for a specific attribute
600 actually exists.
601 """
602 return any(part.get(attribute) == number for part in partitions)
603
604
605 def check_size_format(size_str):
606 """
607 Checks if the input string is an allowed size
608 """
609 size, unit = parse_unit(size_str)
610 return unit in parted_units
611
612
613 def main():
614 global module, units_si, units_iec, parted_exec # pylint: disable=global-variable-not-assigned
615
616 changed = False
617 output_script = []
618 script = []
619 module = AnsibleModule(
620 argument_spec=dict(
621 device=dict(type="str", required=True),
622 align=dict(type="str", default="optimal", choices=["cylinder", "minimal", "none", "optimal", "undefined"]),
623 number=dict(type="int"),
624 # unit <unit> command
625 unit=dict(type="str", default="KiB", choices=parted_units),
626 # mklabel <label-type> command
627 label=dict(
628 type="str",
629 default="msdos",
630 choices=["aix", "amiga", "bsd", "dvh", "gpt", "loop", "mac", "msdos", "pc98", "sun"],
631 ),
632 # mkpart <part-type> [<fs-type>] <start> <end> command
633 part_type=dict(type="str", default="primary", choices=["extended", "logical", "primary"]),
634 part_start=dict(type="str", default="0%"),
635 part_end=dict(type="str", default="100%"),
636 fs_type=dict(type="str"),
637 # name <partition> <name> command
638 name=dict(type="str"),
639 # set <partition> <flag> <state> command
640 flags=dict(type="list", elements="str"),
641 # rm/mkpart command
642 state=dict(type="str", default="info", choices=["absent", "info", "present"]),
643 # resize part
644 resize=dict(type="bool", default=False),
645 unit_preserve_case=dict(type="bool", default=False),
646 ),
647 required_if=[
648 ["state", "present", ["number"]],
649 ["state", "absent", ["number"]],
650 ],
651 supports_check_mode=True,
652 )
653 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
654
655 # Data extraction
656 device = module.params["device"]
657 align = module.params["align"]
658 number = module.params["number"]
659 unit = module.params["unit"]
660 label = module.params["label"]
661 part_type = module.params["part_type"]
662 part_start = module.params["part_start"]
663 part_end = module.params["part_end"]
664 name = module.params["name"]
665 state = module.params["state"]
666 flags = module.params["flags"]
667 fs_type = module.params["fs_type"]
668 resize = module.params["resize"]
669 unit_preserve_case = module.params["unit_preserve_case"]
670 if unit_preserve_case is None:
671 # UNCOMMENT when 13.0.0 is released
672 #
673 # module.deprecate(
674 # "The unit field in the return value of community.general.parted is currently lowercased "
675 # "(for example ``kib``) when its original has mixed case (for example ``KiB``). "
676 # "To suppress this warning message, set the parameter ``unit_preserve_case`` either to ``false``, "
677 # "for preserving the current behavior, or to ``true``, for using the new behavior immediately. "
678 # "In community.general 15.0.0, the default value of this option will be set to ``true``.",
679 # version="15.0.0",
680 # collection_name="community.general",
681 # )
682 unit_preserve_case = False
683
684 # Parted executable
685 parted_exec = module.get_bin_path("parted", True)
686
687 # Conditioning
688 if number is not None and number < 1:
689 module.fail_json(msg="The partition number must be greater then 0.")
690 if not check_size_format(part_start):
691 module.fail_json(
692 msg="The argument 'part_start' doesn't respect required format.The size unit is case sensitive.",
693 err=parse_unit(part_start),
694 )
695 if not check_size_format(part_end):
696 module.fail_json(
697 msg="The argument 'part_end' doesn't respect required format.The size unit is case sensitive.",
698 err=parse_unit(part_end),
699 )
700
701 # Read the current disk information
702 current_device = get_device_info(device, unit, unit_preserve_case)
703 current_parts = current_device["partitions"]
704
705 if state == "present":
706 # Assign label if required
707 mklabel_needed = current_device["generic"].get("table", None) != label
708 if mklabel_needed:
709 script += ["mklabel", label]
710
711 # Create partition if required
712 if part_type and (mklabel_needed or not part_exists(current_parts, "num", number)):
713 script += ["mkpart"]
714 script += [part_type]
715 if fs_type is not None:
716 script += [fs_type]
717 script += [part_start, part_end]
718
719 # Set the unit of the run
720 if unit and script:
721 script = ["unit", unit] + script
722
723 # If partition exists, try to resize
724 if resize and part_exists(current_parts, "num", number):
725 # Ensure new end is different to current
726 partition = [p for p in current_parts if p["num"] == number][0]
727 current_part_end = convert_to_bytes(partition["end"], unit)
728
729 size, parsed_unit = parse_unit(part_end, unit)
730 if parsed_unit == "%":
731 size = int((int(current_device["generic"]["size"]) * size) / 100)
732 parsed_unit = unit
733
734 desired_part_end = convert_to_bytes(size, parsed_unit)
735
736 if current_part_end != desired_part_end:
737 script += ["resizepart", str(number), part_end]
738
739 # Execute the script and update the data structure.
740 # This will create the partition for the next steps
741 if script:
742 output_script += script
743 parted(script, device, align)
744 changed = True
745 script = []
746
747 if not module.check_mode:
748 current_parts = get_device_info(device, unit, unit_preserve_case)["partitions"]
749
750 if part_exists(current_parts, "num", number) or module.check_mode:
751 if changed and module.check_mode:
752 partition = {"flags": []} # Empty structure for the check-mode
753 else:
754 partition = [p for p in current_parts if p["num"] == number][0]
755
756 # Assign name to the partition
757 if name is not None and partition.get("name", None) != name:
758 # The double quotes need to be included in the arg passed to parted
759 script += ["name", str(number), f'"{name}"']
760
761 # Manage flags
762 if flags:
763 # Parted infers boot with esp, if you assign esp, boot is set
764 # and if boot is unset, esp is also unset.
765 if "esp" in flags and "boot" not in flags:
766 flags.append("boot")
767
768 # Compute only the changes in flags status
769 flags_off = list(set(partition["flags"]) - set(flags))
770 flags_on = list(set(flags) - set(partition["flags"]))
771
772 for f in flags_on:
773 script += ["set", str(number), f, "on"]
774
775 for f in flags_off:
776 script += ["set", str(number), f, "off"]
777
778 # Set the unit of the run
779 if unit and script:
780 script = ["unit", unit] + script
781
782 # Execute the script
783 if script:
784 output_script += script
785 changed = True
786 parted(script, device, align)
787
788 elif state == "absent":
789 # Remove the partition
790 if part_exists(current_parts, "num", number) or module.check_mode:
791 script = ["rm", str(number)]
792 output_script += script
793 changed = True
794 parted(script, device, align)
795
796 elif state == "info":
797 output_script = ["unit", unit, "print"]
798 # Final status of the device
799 final_device_status = get_device_info(device, unit, unit_preserve_case)
800 module.exit_json(
801 changed=changed,
802 disk=final_device_status["generic"],
803 partitions=final_device_status["partitions"],
804 script=output_script,
805 )
806
807
808 if __name__ == "__main__":
809 main()