Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2012, Jan-Piet Mens <jpmens () gmail.com>
4 # Copyright (c) 2015, Ales Nosek <anosek.nosek () gmail.com>
5 # Copyright (c) 2017, Ansible Project
6 # Copyright (c) 2023, Ansible Project
7 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
8 # SPDX-License-Identifier: GPL-3.0-or-later
9
10 from __future__ import annotations
11
12 DOCUMENTATION = r"""
13 module: ini_file
14 short_description: Tweak settings in INI files
15 extends_documentation_fragment:
16 - ansible.builtin.files
17 - community.general._attributes
18 description:
19 - Manage (add, remove, change) individual settings in an INI-style file without having to manage the file as a whole with,
20 say, M(ansible.builtin.template) or M(ansible.builtin.assemble).
21 - Adds missing sections if they do not exist.
22 - This module adds missing ending newlines to files to keep in line with the POSIX standard, even when no other modifications
23 need to be applied.
24 attributes:
25 check_mode:
26 support: full
27 diff_mode:
28 support: full
29 options:
30 path:
31 description:
32 - Path to the INI-style file; this file is created if required.
33 type: path
34 required: true
35 aliases: [dest]
36 section:
37 description:
38 - Section name in INI file. This is added if O(state=present) automatically when a single value is being set.
39 - If being omitted, the O(option) is placed before the first O(section).
40 - Omitting O(section) is also required if the config format does not support sections.
41 type: str
42 section_has_values:
43 type: list
44 elements: dict
45 suboptions:
46 option:
47 type: str
48 description: Matching O(section) must contain this option.
49 required: true
50 value:
51 type: str
52 description: Matching O(section_has_values[].option) must have this specific value.
53 values:
54 description:
55 - The string value to be associated with an O(section_has_values[].option).
56 - Mutually exclusive with O(section_has_values[].value).
57 - O(section_has_values[].value=v) is equivalent to O(section_has_values[].values=[v]).
58 type: list
59 elements: str
60 description:
61 - Among possibly multiple sections of the same name, select the first one that contains matching options and values.
62 - With O(state=present), if a suitable section is not found, a new section is added, including the required options.
63 - With O(state=absent), at most one O(section) is removed if it contains the values.
64 version_added: 8.6.0
65 option:
66 description:
67 - If set (required for changing a O(value)), this is the name of the option.
68 - May be omitted if adding/removing a whole O(section).
69 type: str
70 value:
71 description:
72 - The string value to be associated with an O(option).
73 - May be omitted when removing an O(option).
74 - Mutually exclusive with O(values).
75 - O(value=v) is equivalent to O(values=[v]).
76 type: str
77 values:
78 description:
79 - The string value to be associated with an O(option).
80 - May be omitted when removing an O(option).
81 - Mutually exclusive with O(value).
82 - O(value=v) is equivalent to O(values=[v]).
83 type: list
84 elements: str
85 version_added: 3.6.0
86 backup:
87 description:
88 - Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered
89 it incorrectly.
90 type: bool
91 default: false
92 state:
93 description:
94 - If set to V(absent) and O(exclusive) set to V(true) all matching O(option) lines are removed.
95 - If set to V(absent) and O(exclusive) set to V(false) the specified O(option=value) lines are removed, but the other
96 O(option)s with the same name are not touched.
97 - If set to V(present) and O(exclusive) set to V(false) the specified O(option=values) lines are added, but the other
98 O(option)s with the same name are not touched.
99 - If set to V(present) and O(exclusive) set to V(true) all given O(option=values) lines are added and the other O(option)s
100 with the same name are removed.
101 type: str
102 choices: [absent, present]
103 default: present
104 exclusive:
105 description:
106 - If set to V(true) (default), all matching O(option) lines are removed when O(state=absent), or replaced when O(state=present).
107 - If set to V(false), only the specified O(value)/O(values) are added when O(state=present), or removed when O(state=absent),
108 and existing ones are not modified.
109 type: bool
110 default: true
111 version_added: 3.6.0
112 no_extra_spaces:
113 description:
114 - Do not insert spaces before and after '=' symbol.
115 type: bool
116 default: false
117 ignore_spaces:
118 description:
119 - Do not change a line if doing so would only add or remove spaces before or after the V(=) symbol.
120 type: bool
121 default: false
122 version_added: 7.5.0
123 create:
124 description:
125 - If set to V(false), the module fails if the file does not already exist.
126 - By default it creates the file if it is missing.
127 type: bool
128 default: true
129 allow_no_value:
130 description:
131 - Allow option without value and without '=' symbol.
132 type: bool
133 default: false
134 modify_inactive_option:
135 description:
136 - By default the module replaces a commented line that matches the given option.
137 - Set this option to V(false) to avoid this. This is useful when you want to keep commented example C(key=value) pairs
138 for documentation purposes.
139 type: bool
140 default: true
141 version_added: 8.0.0
142 follow:
143 description:
144 - This flag indicates that filesystem links, if they exist, should be followed.
145 - O(follow=true) can modify O(path) when combined with parameters such as O(mode).
146 type: bool
147 default: false
148 version_added: 7.1.0
149 notes:
150 - While it is possible to add an O(option) without specifying a O(value), this makes no sense.
151 - As of community.general 3.2.0, UTF-8 BOM markers are discarded when reading files.
152 seealso:
153 - plugin: ansible.builtin.ini
154 plugin_type: lookup
155 - plugin: community.general.from_ini
156 plugin_type: filter
157 - plugin: community.general.to_ini
158 plugin_type: filter
159 author:
160 - Jan-Piet Mens (@jpmens)
161 - Ales Nosek (@noseka1)
162 """
163
164 EXAMPLES = r"""
165 - name: Ensure "fav=lemonade is in section "[drinks]" in specified file
166 community.general.ini_file:
167 path: /etc/conf
168 section: drinks
169 option: fav
170 value: lemonade
171 mode: '0600'
172 backup: true
173
174 - name: Ensure "temperature=cold is in section "[drinks]" in specified file
175 community.general.ini_file:
176 path: /etc/anotherconf
177 section: drinks
178 option: temperature
179 value: cold
180 backup: true
181
182 - name: Add "beverage=lemon juice" is in section "[drinks]" in specified file
183 community.general.ini_file:
184 path: /etc/conf
185 section: drinks
186 option: beverage
187 value: lemon juice
188 mode: '0600'
189 state: present
190 exclusive: false
191
192 - name: Ensure multiple values "beverage=coke" and "beverage=pepsi" are in section "[drinks]" in specified file
193 community.general.ini_file:
194 path: /etc/conf
195 section: drinks
196 option: beverage
197 values:
198 - coke
199 - pepsi
200 mode: '0600'
201 state: present
202
203 - name: Add "beverage=lemon juice" outside a section in specified file
204 community.general.ini_file:
205 path: /etc/conf
206 option: beverage
207 value: lemon juice
208 state: present
209
210 - name: Remove the peer configuration for 10.128.0.11/32
211 community.general.ini_file:
212 path: /etc/wireguard/wg0.conf
213 section: Peer
214 section_has_values:
215 - option: AllowedIps
216 value: 10.128.0.11/32
217 mode: '0600'
218 state: absent
219
220 - name: Add "beverage=lemon juice" outside a section in specified file
221 community.general.ini_file:
222 path: /etc/conf
223 option: beverage
224 value: lemon juice
225 state: present
226
227 - name: Update the public key for peer 10.128.0.12/32
228 community.general.ini_file:
229 path: /etc/wireguard/wg0.conf
230 section: Peer
231 section_has_values:
232 - option: AllowedIps
233 value: 10.128.0.12/32
234 option: PublicKey
235 value: xxxxxxxxxxxxxxxxxxxx
236 mode: '0600'
237 state: present
238
239 - name: Remove the peer configuration for 10.128.0.11/32
240 community.general.ini_file:
241 path: /etc/wireguard/wg0.conf
242 section: Peer
243 section_has_values:
244 - option: AllowedIps
245 value: 10.4.0.11/32
246 mode: '0600'
247 state: absent
248
249 - name: Update the public key for peer 10.128.0.12/32
250 community.general.ini_file:
251 path: /etc/wireguard/wg0.conf
252 section: Peer
253 section_has_values:
254 - option: AllowedIps
255 value: 10.4.0.12/32
256 option: PublicKey
257 value: xxxxxxxxxxxxxxxxxxxx
258 mode: '0600'
259 state: present
260 """
261
262 import os
263 import re
264 import tempfile
265 import traceback
266
267 from ansible.module_utils.basic import AnsibleModule
268 from ansible.module_utils.common.text.converters import to_bytes, to_text
269
270
271 def match_opt(option, line):
272 option = re.escape(option)
273 return re.match(f"( |\t)*([#;]?)( |\t)*({option})( |\t)*(=|$)( |\t)*(.*)", line)
274
275
276 def match_active_opt(option, line):
277 option = re.escape(option)
278 return re.match(f"()()( |\t)*({option})( |\t)*(=|$)( |\t)*(.*)", line)
279
280
281 def update_section_line(option, changed, section_lines, index, changed_lines, ignore_spaces, newline, msg):
282 option_changed = None
283 if ignore_spaces:
284 old_match = match_opt(option, section_lines[index])
285 if not old_match.group(2):
286 new_match = match_opt(option, newline)
287 option_changed = old_match.group(8) != new_match.group(8)
288 if option_changed is None:
289 option_changed = section_lines[index] != newline
290 if option_changed:
291 section_lines[index] = newline
292 changed = changed or option_changed
293 if option_changed:
294 msg = "option changed"
295 changed_lines[index] = 1
296 return (changed, msg)
297
298
299 def check_section_has_values(section_has_values, section_lines):
300 if section_has_values is not None:
301 for condition in section_has_values:
302 for line in section_lines:
303 match = match_opt(condition["option"], line)
304 if match and (len(condition["values"]) == 0 or match.group(8) in condition["values"]):
305 break
306 else:
307 return False
308 return True
309
310
311 def do_ini(
312 module,
313 filename,
314 section=None,
315 section_has_values=None,
316 option=None,
317 values=None,
318 state="present",
319 exclusive=True,
320 backup=False,
321 no_extra_spaces=False,
322 ignore_spaces=False,
323 create=True,
324 allow_no_value=False,
325 modify_inactive_option=True,
326 follow=False,
327 ):
328 if section is not None:
329 section = to_text(section)
330 if option is not None:
331 option = to_text(option)
332
333 # deduplicate entries in values
334 values_unique = []
335 [values_unique.append(to_text(value)) for value in values if value not in values_unique and value is not None]
336 values = values_unique
337
338 diff = dict(
339 before="",
340 after="",
341 before_header=f"{filename} (content)",
342 after_header=f"{filename} (content)",
343 )
344
345 if follow and os.path.islink(filename):
346 target_filename = os.path.realpath(filename)
347 else:
348 target_filename = filename
349
350 if not os.path.exists(target_filename):
351 if not create:
352 module.fail_json(rc=257, msg=f"Destination {target_filename} does not exist!")
353 destpath = os.path.dirname(target_filename)
354 if not os.path.exists(destpath) and not module.check_mode:
355 os.makedirs(destpath)
356 ini_lines = []
357 else:
358 with open(target_filename, encoding="utf-8-sig") as ini_file:
359 ini_lines = [to_text(line) for line in ini_file.readlines()]
360
361 if module._diff:
362 diff["before"] = "".join(ini_lines)
363
364 changed = False
365
366 # ini file could be empty
367 if not ini_lines:
368 ini_lines.append("\n")
369
370 # last line of file may not contain a trailing newline
371 if ini_lines[-1] == "" or ini_lines[-1][-1] != "\n":
372 ini_lines[-1] += "\n"
373 changed = True
374
375 # append fake section lines to simplify the logic
376 # At top:
377 # Fake random section to do not match any other in the file
378 # Using commit hash as fake section name
379 fake_section_name = "ad01e11446efb704fcdbdb21f2c43757423d91c5"
380
381 # Insert it at the beginning
382 ini_lines.insert(0, f"[{fake_section_name}]")
383
384 # At bottom:
385 ini_lines.append("[")
386
387 # If no section is defined, fake section is used
388 if not section:
389 section = fake_section_name
390
391 within_section = not section
392 section_start = section_end = 0
393 msg = "OK"
394 sep = "=" if no_extra_spaces else " = "
395
396 option_no_value_present = False
397
398 non_blank_non_comment_pattern = re.compile(to_text(r"^[ \t]*([#;].*)?$"))
399
400 before = after = []
401 section_lines = []
402
403 section_pattern = re.compile(to_text(rf"^\[\s*{re.escape(section.strip())}\s*]"))
404
405 for index, line in enumerate(ini_lines):
406 # end of section:
407 if within_section and line.startswith("["):
408 if check_section_has_values(section_has_values, ini_lines[section_start:index]):
409 section_end = index
410 break
411 else:
412 # look for another section
413 within_section = False
414 section_start = section_end = 0
415
416 # find start and end of section
417 if section_pattern.match(line):
418 within_section = True
419 section_start = index
420
421 before = ini_lines[0:section_start]
422 section_lines = ini_lines[section_start:section_end]
423 after = ini_lines[section_end : len(ini_lines)]
424
425 # Keep track of changed section_lines
426 changed_lines = [0] * len(section_lines)
427
428 # Determine whether to consider using commented out/inactive options or only active ones
429 if modify_inactive_option:
430 match_function = match_opt
431 else:
432 match_function = match_active_opt
433
434 # handling multiple instances of option=value when state is 'present' with/without exclusive is a bit complex
435 #
436 # 1. edit all lines where we have a option=value pair with a matching value in values[]
437 # 2. edit all the remaining lines where we have a matching option
438 # 3. delete remaining lines where we have a matching option
439 # 4. insert missing option line(s) at the end of the section
440
441 if state == "present" and option:
442 for index, line in enumerate(section_lines):
443 if match_function(option, line):
444 match = match_function(option, line)
445 if values and match.group(8) in values:
446 matched_value = match.group(8)
447 if not matched_value and allow_no_value:
448 # replace existing option with no value line(s)
449 newline = f"{option}\n"
450 option_no_value_present = True
451 else:
452 # replace existing option=value line(s)
453 newline = f"{option}{sep}{matched_value}\n"
454 (changed, msg) = update_section_line(
455 option, changed, section_lines, index, changed_lines, ignore_spaces, newline, msg
456 )
457 values.remove(matched_value)
458 elif not values and allow_no_value:
459 # replace existing option with no value line(s)
460 newline = f"{option}\n"
461 (changed, msg) = update_section_line(
462 option, changed, section_lines, index, changed_lines, ignore_spaces, newline, msg
463 )
464 option_no_value_present = True
465 break
466
467 if state == "present" and exclusive and not allow_no_value:
468 # override option with no value to option with value if not allow_no_value
469 if len(values) > 0:
470 for index, line in enumerate(section_lines):
471 if not changed_lines[index] and match_function(option, line):
472 newline = f"{option}{sep}{values.pop(0)}\n"
473 (changed, msg) = update_section_line(
474 option, changed, section_lines, index, changed_lines, ignore_spaces, newline, msg
475 )
476 if len(values) == 0:
477 break
478 # remove all remaining option occurrences from the rest of the section
479 for index in range(len(section_lines) - 1, 0, -1):
480 if not changed_lines[index] and match_function(option, section_lines[index]):
481 del section_lines[index]
482 del changed_lines[index]
483 changed = True
484 msg = "option changed"
485
486 if state == "present":
487 # insert missing option line(s) at the end of the section
488 for index in range(len(section_lines), 0, -1):
489 # search backwards for previous non-blank or non-comment line
490 if not non_blank_non_comment_pattern.match(section_lines[index - 1]):
491 if option and values:
492 # insert option line(s)
493 for element in values[::-1]:
494 # items are added backwards, so traverse the list backwards to not confuse the user
495 # otherwise some of their options might appear in reverse order for whatever fancy reason ¯\_(ツ)_/¯
496 if element is not None:
497 # insert option=value line
498 section_lines.insert(index, f"{option}{sep}{element}\n")
499 msg = "option added"
500 changed = True
501 elif element is None and allow_no_value:
502 # insert option with no value line
503 section_lines.insert(index, f"{option}\n")
504 msg = "option added"
505 changed = True
506 elif option and not values and allow_no_value and not option_no_value_present:
507 # insert option with no value line(s)
508 section_lines.insert(index, f"{option}\n")
509 msg = "option added"
510 changed = True
511 break
512
513 if state == "absent":
514 if option:
515 if exclusive:
516 # delete all option line(s) with given option and ignore value
517 new_section_lines = [line for line in section_lines if not (match_active_opt(option, line))]
518 if section_lines != new_section_lines:
519 changed = True
520 msg = "option changed"
521 section_lines = new_section_lines
522 elif not exclusive and len(values) > 0:
523 # delete specified option=value line(s)
524 new_section_lines = [
525 i
526 for i in section_lines
527 if not (match_active_opt(option, i) and match_active_opt(option, i).group(8) in values)
528 ]
529 if section_lines != new_section_lines:
530 changed = True
531 msg = "option changed"
532 section_lines = new_section_lines
533 else:
534 # drop the entire section
535 if section_lines:
536 section_lines = []
537 msg = "section removed"
538 changed = True
539
540 # reassemble the ini_lines after manipulation
541 ini_lines = before + section_lines + after
542
543 # remove the fake section line
544 del ini_lines[0]
545 del ini_lines[-1:]
546
547 if not within_section and state == "present":
548 ini_lines.append(f"[{section}]\n")
549 msg = "section and option added"
550 if section_has_values:
551 for condition in section_has_values:
552 if condition["option"] != option:
553 if len(condition["values"]) > 0:
554 for value in condition["values"]:
555 ini_lines.append(f"{condition['option']}{sep}{value}\n")
556 elif allow_no_value:
557 ini_lines.append(f"{condition['option']}\n")
558 elif not exclusive:
559 for value in condition["values"]:
560 if value not in values:
561 values.append(value)
562 if option and values:
563 for value in values:
564 ini_lines.append(f"{option}{sep}{value}\n")
565 elif option and not values and allow_no_value:
566 ini_lines.append(f"{option}\n")
567 else:
568 msg = "only section added"
569 changed = True
570
571 if module._diff:
572 diff["after"] = "".join(ini_lines)
573
574 backup_file = None
575 if changed and not module.check_mode:
576 if backup:
577 backup_file = module.backup_local(target_filename)
578
579 encoded_ini_lines = [to_bytes(line) for line in ini_lines]
580 try:
581 tmpfd, tmpfile = tempfile.mkstemp(dir=module.tmpdir)
582 f = os.fdopen(tmpfd, "wb")
583 f.writelines(encoded_ini_lines)
584 f.close()
585 except OSError:
586 module.fail_json(msg="Unable to create temporary file %s", traceback=traceback.format_exc())
587
588 try:
589 module.atomic_move(tmpfile, os.path.abspath(target_filename))
590 except OSError:
591 module.ansible.fail_json(
592 msg=f"Unable to move temporary file {tmpfile} to {target_filename}, IOError",
593 traceback=traceback.format_exc(),
594 )
595
596 return (changed, backup_file, diff, msg)
597
598
599 def main():
600 module = AnsibleModule(
601 argument_spec=dict(
602 path=dict(type="path", required=True, aliases=["dest"]),
603 section=dict(type="str"),
604 section_has_values=dict(
605 type="list",
606 elements="dict",
607 options=dict(
608 option=dict(type="str", required=True),
609 value=dict(type="str"),
610 values=dict(type="list", elements="str"),
611 ),
612 mutually_exclusive=[["value", "values"]],
613 ),
614 option=dict(type="str"),
615 value=dict(type="str"),
616 values=dict(type="list", elements="str"),
617 backup=dict(type="bool", default=False),
618 state=dict(type="str", default="present", choices=["absent", "present"]),
619 exclusive=dict(type="bool", default=True),
620 no_extra_spaces=dict(type="bool", default=False),
621 ignore_spaces=dict(type="bool", default=False),
622 allow_no_value=dict(type="bool", default=False),
623 modify_inactive_option=dict(type="bool", default=True),
624 create=dict(type="bool", default=True),
625 follow=dict(type="bool", default=False),
626 ),
627 mutually_exclusive=[["value", "values"]],
628 add_file_common_args=True,
629 supports_check_mode=True,
630 )
631
632 path = module.params["path"]
633 section = module.params["section"]
634 section_has_values = module.params["section_has_values"]
635 option = module.params["option"]
636 value = module.params["value"]
637 values = module.params["values"]
638 state = module.params["state"]
639 exclusive = module.params["exclusive"]
640 backup = module.params["backup"]
641 no_extra_spaces = module.params["no_extra_spaces"]
642 ignore_spaces = module.params["ignore_spaces"]
643 allow_no_value = module.params["allow_no_value"]
644 modify_inactive_option = module.params["modify_inactive_option"]
645 create = module.params["create"]
646 follow = module.params["follow"]
647
648 if state == "present" and not allow_no_value and value is None and not values:
649 module.fail_json(msg="Parameter 'value(s)' must be defined if state=present and allow_no_value=False.")
650
651 if value is not None:
652 values = [value]
653 elif values is None:
654 values = []
655
656 if section_has_values:
657 for condition in section_has_values:
658 if condition["value"] is not None:
659 condition["values"] = [condition["value"]]
660 elif condition["values"] is None:
661 condition["values"] = []
662 # raise Exception("section_has_values: {}".format(section_has_values))
663
664 (changed, backup_file, diff, msg) = do_ini(
665 module,
666 path,
667 section,
668 section_has_values,
669 option,
670 values,
671 state,
672 exclusive,
673 backup,
674 no_extra_spaces,
675 ignore_spaces,
676 create,
677 allow_no_value,
678 modify_inactive_option,
679 follow,
680 )
681
682 if not module.check_mode and os.path.exists(path):
683 file_args = module.load_file_common_arguments(module.params)
684 changed = module.set_fs_attributes_if_different(file_args, changed)
685
686 results = dict(
687 changed=changed,
688 diff=diff,
689 msg=msg,
690 path=path,
691 )
692 if backup_file is not None:
693 results["backup_file"] = backup_file
694
695 # Mission complete
696 module.exit_json(**results)
697
698
699 if __name__ == "__main__":
700 main()