Debian Codegraph @

lib/ansible/modules/lineinfile.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: (c) 2012, Daniel Hokka Zakrisson <[email protected]>
4 # Copyright: (c) 2014, Ahti Kitsik <[email protected]>
5 # Copyright: (c) 2017, Ansible Project
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 from __future__ import annotations
9
10
11 DOCUMENTATION = r"""
12 ---
13 module: lineinfile
14 short_description: Manage lines in text files
15 description:
16 - This module ensures a particular line is in a file, or replace an
17 existing line using a back-referenced regular expression.
18 - This is primarily useful when you want to change a single line in a file only.
19 - See the M(ansible.builtin.replace) module if you want to change multiple, similar lines
20 or check M(ansible.builtin.blockinfile) if you want to insert/update/remove a block of lines in a file.
21 For other cases, see the M(ansible.builtin.copy) or M(ansible.builtin.template) modules.
22 version_added: "0.7"
23 options:
24 path:
25 description:
26 - The file to modify.
27 - Before Ansible 2.3 this option was only usable as O(dest), O(destfile) and O(name).
28 type: path
29 required: true
30 aliases: [ dest, destfile, name ]
31 regexp:
32 description:
33 - The regular expression to look for in every line of the file.
34 - For O(state=present), the pattern to replace if found. Only the last line found will be replaced.
35 - For O(state=absent), the pattern of the line(s) to remove.
36 - If the regular expression is not matched, the line will be
37 added to the file in keeping with O(insertbefore) or O(insertafter)
38 settings.
39 - When modifying a line the regexp should typically match both the initial state of
40 the line as well as its state after replacement by O(line) to ensure idempotence.
41 - Uses Python regular expressions. See U(https://docs.python.org/3/library/re.html).
42 type: str
43 aliases: [ regex ]
44 version_added: '1.7'
45 search_string:
46 description:
47 - The literal string to look for in every line of the file. This does not have to match the entire line.
48 - For O(state=present), the line to replace if the string is found in the file. Only the last line found will be replaced.
49 - For O(state=absent), the line(s) to remove if the string is in the line.
50 - If the literal expression is not matched, the line will be
51 added to the file in keeping with O(insertbefore) or O(insertafter)
52 settings.
53 - Mutually exclusive with O(backrefs) and O(regexp).
54 type: str
55 version_added: '2.11'
56 state:
57 description:
58 - Whether the line should be there or not.
59 type: str
60 choices: [ absent, present ]
61 default: present
62 line:
63 description:
64 - The line to insert/replace into the file.
65 - Required for O(state=present).
66 - If O(backrefs) is set, may contain backreferences that will get
67 expanded with the O(regexp) capture groups if the regexp matches.
68 type: str
69 aliases: [ value ]
70 backrefs:
71 description:
72 - Used with O(state=present).
73 - If set, O(line) can contain backreferences (both positional and named)
74 that will get populated if the O(regexp) matches.
75 - This parameter changes the operation of the module slightly;
76 O(insertbefore) and O(insertafter) will be ignored, and if the O(regexp)
77 does not match anywhere in the file, the file will be left unchanged.
78 - If the O(regexp) does match, the last matching line will be replaced by
79 the expanded line parameter.
80 - Mutually exclusive with O(search_string).
81 type: bool
82 default: no
83 version_added: "1.1"
84 insertafter:
85 description:
86 - Used with O(state=present).
87 - If specified, the line will be inserted after the last match of specified regular expression.
88 - If the first match is required, use(firstmatch=yes).
89 - A special value is available; V(EOF) for inserting the line at the end of the file.
90 - If specified regular expression has no matches or no value is passed, V(EOF) will be used instead.
91 - If O(insertbefore) is set, default value V(EOF) will be ignored.
92 - If regular expressions are passed to both O(regexp) and O(insertafter), O(insertafter) is only honored if no match for O(regexp) is found.
93 - May not be used with O(backrefs) or O(insertbefore).
94 type: str
95 insertbefore:
96 description:
97 - Used with O(state=present).
98 - If specified, the line will be inserted before the last match of specified regular expression.
99 - If the first match is required, use O(firstmatch=yes).
100 - A value is available; V(BOF) for inserting the line at the beginning of the file.
101 - If specified regular expression has no matches, the line will be inserted at the end of the file.
102 - If regular expressions are passed to both O(regexp) and O(insertbefore), O(insertbefore) is only honored if no match for O(regexp) is found.
103 - May not be used with O(backrefs) or O(insertafter).
104 type: str
105 version_added: "1.1"
106 create:
107 description:
108 - Used with O(state=present).
109 - If specified, the file will be created if it does not already exist.
110 - By default it will fail if the file is missing.
111 type: bool
112 default: no
113 backup:
114 description:
115 - Create a backup file including the timestamp information so you can
116 get the original file back if you somehow clobbered it incorrectly.
117 type: bool
118 default: no
119 firstmatch:
120 description:
121 - Used with O(insertafter) or O(insertbefore).
122 - If set, O(insertafter) and O(insertbefore) will work with the first line that matches the given regular expression.
123 type: bool
124 default: no
125 version_added: "2.5"
126 encoding:
127 description:
128 - The character set in which the target file is encoded.
129 - For a list of available built-in encodings, see U(https://docs.python.org/3/library/codecs.html#standard-encodings)
130 type: str
131 default: utf-8
132 version_added: "2.20"
133 extends_documentation_fragment:
134 - action_common_attributes
135 - action_common_attributes.files
136 - files
137 - validate
138 attributes:
139 check_mode:
140 support: full
141 diff_mode:
142 support: full
143 platform:
144 platforms: posix
145 safe_file_operations:
146 support: full
147 vault:
148 support: none
149 notes:
150 - As of Ansible 2.3, the O(dest) option has been changed to O(path) as default, but O(dest) still works as well.
151 seealso:
152 - module: ansible.builtin.blockinfile
153 - module: ansible.builtin.copy
154 - module: ansible.builtin.file
155 - module: ansible.builtin.replace
156 - module: ansible.builtin.template
157 - module: community.windows.win_lineinfile
158 author:
159 - Daniel Hokka Zakrissoni (@dhozac)
160 - Ahti Kitsik (@ahtik)
161 - Jose Angel Munoz (@imjoseangel)
162 """
163
164 EXAMPLES = r"""
165 # NOTE: Before 2.3, option 'dest', 'destfile' or 'name' was used instead of 'path'
166 - name: Ensure SELinux is set to enforcing mode
167 ansible.builtin.lineinfile:
168 path: /etc/selinux/config
169 regexp: '^SELINUX='
170 line: SELINUX=enforcing
171
172 - name: Make sure group wheel is not in the sudoers configuration
173 ansible.builtin.lineinfile:
174 path: /etc/sudoers
175 state: absent
176 regexp: '^%wheel'
177
178 - name: Replace a localhost entry with our own
179 ansible.builtin.lineinfile:
180 path: /etc/hosts
181 regexp: '^127\.0\.0\.1'
182 line: 127.0.0.1 localhost
183 owner: root
184 group: root
185 mode: '0644'
186
187 - name: Replace a localhost entry searching for a literal string to avoid escaping
188 ansible.builtin.lineinfile:
189 path: /etc/hosts
190 search_string: '127.0.0.1'
191 line: 127.0.0.1 localhost
192 owner: root
193 group: root
194 mode: '0644'
195
196 - name: Ensure the default Apache port is 8080
197 ansible.builtin.lineinfile:
198 path: /etc/httpd/conf/httpd.conf
199 regexp: '^Listen '
200 insertafter: '^#Listen '
201 line: Listen 8080
202
203 - name: Ensure php extension matches new pattern
204 ansible.builtin.lineinfile:
205 path: /etc/httpd/conf/httpd.conf
206 search_string: '<FilesMatch ".php[45]?$">'
207 insertafter: '^\t<Location \/>\n'
208 line: ' <FilesMatch ".php[34]?$">'
209
210 - name: Ensure we have our own comment added to /etc/services
211 ansible.builtin.lineinfile:
212 path: /etc/services
213 regexp: '^# port for http'
214 insertbefore: '^www.*80/tcp'
215 line: '# port for http by default'
216
217 - name: Add a line to a file if the file does not exist, without passing regexp
218 ansible.builtin.lineinfile:
219 path: /tmp/testfile
220 line: 192.168.1.99 foo.lab.net foo
221 create: yes
222
223 # NOTE: Yaml requires escaping backslashes in double quotes but not in single quotes
224 - name: Ensure the JBoss memory settings are exactly as needed
225 ansible.builtin.lineinfile:
226 path: /opt/jboss-as/bin/standalone.conf
227 regexp: '^(.*)Xms(\d+)m(.*)$'
228 line: '\1Xms${xms}m\3'
229 backrefs: yes
230
231 # NOTE: Fully quoted because of the ': ' on the line. See the Gotchas in the YAML docs.
232 - name: Validate the sudoers file before saving
233 ansible.builtin.lineinfile:
234 path: /etc/sudoers
235 state: present
236 regexp: '^%ADMIN ALL='
237 line: '%ADMIN ALL=(ALL) NOPASSWD: ALL'
238 validate: /usr/sbin/visudo -cf %s
239
240 # See https://docs.python.org/3/library/re.html for further details on syntax
241 - name: Use backrefs with alternative group syntax to avoid conflicts with variable values
242 ansible.builtin.lineinfile:
243 path: /tmp/config
244 regexp: ^(host=).*
245 line: \g<1>{{ hostname }}
246 backrefs: yes
247 """
248
249 RETURN = r"""#"""
250
251 import os
252 import re
253 import tempfile
254
255 # import module snippets
256 from ansible.module_utils.basic import AnsibleModule
257 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
258
259
260 def write_changes(module, lines, dest, encoding=None):
261
262 tmpfd, tmpfile = tempfile.mkstemp(dir=module.tmpdir)
263 with os.fdopen(tmpfd, 'w', encoding=encoding) as f:
264 f.writelines(lines)
265
266 validate = module.params.get('validate', None)
267 valid = not validate
268 if validate:
269 if "%s" not in validate:
270 module.fail_json(msg="validate must contain %%s: %s" % (validate))
271 (rc, out, err) = module.run_command(to_bytes(validate % tmpfile, errors='surrogate_or_strict'))
272 valid = rc == 0
273 if rc != 0:
274 module.fail_json(msg='failed to validate: '
275 'rc:%s error:%s' % (rc, err))
276 if valid:
277 module.atomic_move(tmpfile,
278 to_native(os.path.realpath(to_bytes(dest, errors='surrogate_or_strict')), errors='surrogate_or_strict'),
279 unsafe_writes=module.params['unsafe_writes'])
280
281
282 def check_file_attrs(module, changed, message, diff):
283
284 file_args = module.load_file_common_arguments(module.params)
285 if module.set_fs_attributes_if_different(file_args, False, diff=diff):
286
287 if changed:
288 message += " and "
289 changed = True
290 message += "ownership, perms or SE linux context changed"
291
292 return message, changed
293
294
295 def present(module, dest, regexp, search_string, line, insertafter, insertbefore, create,
296 backup, backrefs, firstmatch):
297
298 diff = {'before': '',
299 'after': '',
300 'before_header': '%s (content)' % dest,
301 'after_header': '%s (content)' % dest}
302
303 encoding = module.params.get('encoding', None)
304 b_dest = to_bytes(dest, errors='surrogate_or_strict')
305 if not os.path.exists(b_dest):
306 if not create:
307 module.fail_json(rc=257, msg='Destination %s does not exist !' % dest)
308 b_destpath = os.path.dirname(b_dest)
309 if b_destpath and not os.path.exists(b_destpath) and not module.check_mode:
310 try:
311 os.makedirs(b_destpath)
312 except Exception as e:
313 module.fail_json(msg='Error creating %s (%s)' % (to_text(b_destpath), to_text(e)))
314
315 lines = []
316 else:
317 with open(b_dest, 'r', encoding=encoding) as f:
318 lines = f.readlines()
319
320 if module._diff:
321 diff['before'] = ''.join(lines)
322
323 if regexp is not None:
324 re_m = re.compile(regexp)
325
326 if insertafter not in (None, 'BOF', 'EOF'):
327 re_ins = re.compile(insertafter)
328 elif insertbefore not in (None, 'BOF'):
329 re_ins = re.compile(insertbefore)
330 else:
331 re_ins = None
332
333 # index[0] is the line num where regexp has been found
334 # index[1] is the line num where insertafter/insertbefore has been found
335 index = [-1, -1]
336 match = None
337 exact_line_match = False
338
339 # The module's doc says
340 # "If regular expressions are passed to both regexp and
341 # insertafter, insertafter is only honored if no match for regexp is found."
342 # Therefore:
343 # 1. regexp or search_string was found -> ignore insertafter, replace the founded line
344 # 2. regexp or search_string was not found -> insert the line after 'insertafter' or 'insertbefore' line
345
346 # Given the above:
347 # 1. First check that there is no match for regexp:
348 if regexp is not None:
349 for lineno, cur_line in enumerate(lines):
350 match_found = re_m.search(cur_line)
351 if match_found:
352 index[0] = lineno
353 match = match_found
354 if firstmatch:
355 break
356
357 # 2. Second check that there is no match for search_string:
358 if search_string is not None:
359 for lineno, cur_line in enumerate(lines):
360 match_found = search_string in cur_line
361 if match_found:
362 index[0] = lineno
363 match = match_found
364 if firstmatch:
365 break
366
367 # 3. When no match found on the previous step,
368 # parse for searching insertafter/insertbefore:
369 if not match:
370 for lineno, cur_line in enumerate(lines):
371 if line == cur_line.rstrip('\r\n'):
372 index[0] = lineno
373 exact_line_match = True
374
375 elif re_ins is not None and re_ins.search(cur_line):
376 if insertafter:
377 # + 1 for the next line
378 index[1] = lineno + 1
379 if firstmatch:
380 break
381
382 if insertbefore:
383 # index[1] for the previous line
384 index[1] = lineno
385 if firstmatch:
386 break
387
388 msg = ''
389 changed = False
390 linesep = os.linesep
391 # Exact line or Regexp matched a line in the file
392 if index[0] != -1:
393 if backrefs and match:
394 new_line = match.expand(line)
395 else:
396 # Don't do backref expansion if not asked.
397 new_line = line
398
399 if not new_line.endswith(linesep):
400 new_line += linesep
401
402 # If no regexp or search_string was given and no line match is found anywhere in the file,
403 # insert the line appropriately if using insertbefore or insertafter
404 if (regexp, search_string, match) == (None, None, None) and not exact_line_match:
405
406 # Insert lines
407 if insertafter and insertafter != 'EOF':
408 # Ensure there is a line separator after the found string
409 # at the end of the file.
410 if lines and not lines[-1][-1:] in ('\n', '\r'):
411 lines[-1] = lines[-1] + linesep
412
413 # If the line to insert after is at the end of the file
414 # use the appropriate index value.
415 if len(lines) == index[1]:
416 if lines[index[1] - 1].rstrip('\r\n') != line:
417 lines.append(line + linesep)
418 msg = 'line added'
419 changed = True
420 elif lines[index[1]].rstrip('\r\n') != line:
421 lines.insert(index[1], line + linesep)
422 msg = 'line added'
423 changed = True
424
425 elif insertbefore and insertbefore != 'BOF':
426 # If the line to insert before is at the beginning of the file
427 # use the appropriate index value.
428 if index[1] <= 0:
429 if lines[index[1]].rstrip('\r\n') != line:
430 lines.insert(index[1], line + linesep)
431 msg = 'line added'
432 changed = True
433
434 elif lines[index[1] - 1].rstrip('\r\n') != line:
435 lines.insert(index[1], line + linesep)
436 msg = 'line added'
437 changed = True
438
439 elif lines[index[0]] != new_line:
440 lines[index[0]] = new_line
441 msg = 'line replaced'
442 changed = True
443
444 elif backrefs:
445 # Do absolutely nothing, since it's not safe generating the line
446 # without the regexp matching to populate the backrefs.
447 pass
448 # Add it to the beginning of the file
449 elif insertbefore == 'BOF' or insertafter == 'BOF':
450 lines.insert(0, line + linesep)
451 msg = 'line added'
452 changed = True
453 # Add it to the end of the file if requested or
454 # if insertafter/insertbefore didn't match anything
455 # (so default behaviour is to add at the end)
456 elif insertafter == 'EOF' or index[1] == -1:
457
458 # If the file is not empty then ensure there's a newline before the added line
459 if lines and not lines[-1][-1:] in ('\n', '\r'):
460 lines.append(linesep)
461
462 lines.append(line + linesep)
463 msg = 'line added'
464 changed = True
465
466 elif insertafter and index[1] != -1:
467
468 # Don't insert the line if it already matches at the index.
469 # If the line to insert after is at the end of the file use the appropriate index value.
470 if len(lines) == index[1]:
471 if lines[index[1] - 1].rstrip('\r\n') != line:
472 lines.append(line + linesep)
473 msg = 'line added'
474 changed = True
475 elif line != lines[index[1]].rstrip('\n\r'):
476 lines.insert(index[1], line + linesep)
477 msg = 'line added'
478 changed = True
479
480 # insert matched, but not the regexp or search_string
481 else:
482 lines.insert(index[1], line + linesep)
483 msg = 'line added'
484 changed = True
485
486 if module._diff:
487 diff['after'] = ''.join(lines)
488
489 backupdest = ""
490 if changed and not module.check_mode:
491 if backup and os.path.exists(b_dest):
492 backupdest = module.backup_local(dest)
493 write_changes(module, lines, dest, encoding)
494
495 if module.check_mode and not os.path.exists(b_dest):
496 module.exit_json(changed=changed, msg=msg, backup=backupdest, diff=diff)
497
498 attr_diff = {}
499 msg, changed = check_file_attrs(module, changed, msg, attr_diff)
500
501 attr_diff['before_header'] = '%s (file attributes)' % dest
502 attr_diff['after_header'] = '%s (file attributes)' % dest
503
504 difflist = [diff, attr_diff]
505 module.exit_json(changed=changed, msg=msg, backup=backupdest, diff=difflist)
506
507
508 def absent(module, dest, regexp, search_string, line, backup):
509
510 b_dest = to_bytes(dest, errors='surrogate_or_strict')
511 if not os.path.exists(b_dest):
512 module.exit_json(changed=False, msg="file not present")
513
514 msg = ''
515 diff = {'before': '',
516 'after': '',
517 'before_header': '%s (content)' % dest,
518 'after_header': '%s (content)' % dest}
519
520 encoding = module.params['encoding']
521
522 with open(b_dest, 'r', encoding=encoding) as f:
523 lines = f.readlines()
524
525 if module._diff:
526 diff['before'] = ''.join(lines)
527
528 if regexp is not None:
529 re_c = re.compile(regexp)
530 found = []
531
532 def matcher(cur_line):
533 if regexp is not None:
534 match_found = re_c.search(cur_line)
535 elif search_string is not None:
536 match_found = search_string in cur_line
537 else:
538 match_found = line == cur_line.rstrip('\r\n')
539 if match_found:
540 found.append(cur_line)
541 return not match_found
542
543 lines = [l for l in lines if matcher(l)]
544 changed = len(found) > 0
545
546 if module._diff:
547 diff['after'] = ''.join(lines)
548
549 backupdest = ""
550 if changed and not module.check_mode:
551 if backup:
552 backupdest = module.backup_local(dest)
553 write_changes(module, lines, dest, encoding)
554
555 if changed:
556 msg = "%s line(s) removed" % len(found)
557
558 attr_diff = {}
559 msg, changed = check_file_attrs(module, changed, msg, attr_diff)
560
561 attr_diff['before_header'] = '%s (file attributes)' % dest
562 attr_diff['after_header'] = '%s (file attributes)' % dest
563
564 difflist = [diff, attr_diff]
565
566 module.exit_json(changed=changed, found=len(found), msg=msg, backup=backupdest, diff=difflist)
567
568
569 def main():
570 module = AnsibleModule(
571 argument_spec=dict(
572 path=dict(type='path', required=True, aliases=['dest', 'destfile', 'name']),
573 state=dict(type='str', default='present', choices=['absent', 'present']),
574 regexp=dict(type='str', aliases=['regex']),
575 search_string=dict(type='str'),
576 line=dict(type='str', aliases=['value']),
577 encoding=dict(type='str', default='utf-8'),
578 insertafter=dict(type='str'),
579 insertbefore=dict(type='str'),
580 backrefs=dict(type='bool', default=False),
581 create=dict(type='bool', default=False),
582 backup=dict(type='bool', default=False),
583 firstmatch=dict(type='bool', default=False),
584 validate=dict(type='str'),
585 ),
586 mutually_exclusive=[
587 ['insertbefore', 'insertafter'], ['regexp', 'search_string'], ['backrefs', 'search_string']],
588 add_file_common_args=True,
589 supports_check_mode=True,
590 )
591
592 params = module.params
593 create = params['create']
594 backup = params['backup']
595 backrefs = params['backrefs']
596 path = params['path']
597 firstmatch = params['firstmatch']
598 regexp = params['regexp']
599 search_string = params['search_string']
600 line = params['line']
601
602 if '' in [regexp, search_string]:
603 msg = ("The %s is an empty string, which will match every line in the file. "
604 "This may have unintended consequences, such as replacing the last line in the file rather than appending.")
605 param_name = 'search string'
606 if regexp == '':
607 param_name = 'regular expression'
608 msg += " If this is desired, use '^' to match every line in the file and avoid this warning."
609 module.warn(msg % param_name)
610
611 b_path = to_bytes(path, errors='surrogate_or_strict')
612 if os.path.isdir(b_path):
613 module.fail_json(rc=256, msg='Path %s is a directory !' % path)
614
615 if params['state'] == 'present':
616 if backrefs and regexp is None:
617 module.fail_json(msg='regexp is required with backrefs=true')
618
619 if line is None:
620 module.fail_json(msg='line is required with state=present')
621
622 # Deal with the insertafter default value manually, to avoid errors
623 # because of the mutually_exclusive mechanism.
624 ins_bef, ins_aft = params['insertbefore'], params['insertafter']
625 if ins_bef is None and ins_aft is None:
626 ins_aft = 'EOF'
627
628 present(module, path, regexp, search_string, line,
629 ins_aft, ins_bef, create, backup, backrefs, firstmatch)
630 else:
631 if (regexp, search_string, line) == (None, None, None):
632 module.fail_json(msg='one of line, search_string, or regexp is required with state=absent')
633
634 absent(module, path, regexp, search_string, line, backup)
635
636
637 if __name__ == '__main__':
638 main()