Debian Codegraph @

lib/ansible/modules/replace.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: (c) 2013, Evan Kaufman <[email protected]
4 # Copyright: (c) 2017, Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import annotations
8
9
10 DOCUMENTATION = r"""
11 ---
12 module: replace
13 author: Evan Kaufman (@EvanK)
14 extends_documentation_fragment:
15 - action_common_attributes
16 - action_common_attributes.files
17 - files
18 - validate
19 attributes:
20 check_mode:
21 support: full
22 diff_mode:
23 support: full
24 platform:
25 platforms: posix
26 safe_file_operations:
27 support: full
28 vault:
29 support: none
30 short_description: Replace all instances of a particular string in a
31 file using a back-referenced regular expression
32 description:
33 - This module will replace all instances of a pattern within a file.
34 - It is up to the user to maintain idempotence by ensuring that the
35 same pattern would never match any replacements made.
36 version_added: "1.6"
37 options:
38 path:
39 description:
40 - The file to modify.
41 - Before Ansible 2.3 this option was only usable as O(dest), O(destfile) and O(name).
42 type: path
43 required: true
44 aliases: [ dest, destfile, name ]
45 regexp:
46 description:
47 - The regular expression to look for in the contents of the file.
48 - Uses Python regular expressions; see
49 U(https://docs.python.org/3/library/re.html).
50 - Uses MULTILINE mode, which means V(^) and V($) match the beginning
51 and end of the file, as well as the beginning and end respectively
52 of I(each line) of the file.
53 - Does not use DOTALL, which means the V(.) special character matches
54 any character I(except newlines). A common mistake is to assume that
55 a negated character set like V([^#]) will also not match newlines.
56 - In order to exclude newlines, they must be added to the set like V([^#\\n]).
57 - Note that, as of Ansible 2.0, short form tasks should have any escape
58 sequences backslash-escaped in order to prevent them being parsed
59 as string literal escapes. See the examples.
60 type: str
61 required: true
62 replace:
63 description:
64 - The string to replace regexp matches.
65 - May contain backreferences that will get expanded with the regexp capture groups if the regexp matches.
66 - If not set, matches are removed entirely.
67 - Backreferences can be used ambiguously like V(\\1), or explicitly like V(\\g<1>).
68 type: str
69 default: ''
70 after:
71 description:
72 - If specified, only content after this match will be replaced/removed.
73 - Can be used in combination with O(before).
74 - Uses Python regular expressions; see
75 U(https://docs.python.org/3/library/re.html).
76 - Uses DOTALL, which means the V(.) special character I(can match newlines).
77 - Does not use MULTILINE, so V(^) and V($) will only match the beginning and end of the file.
78 type: str
79 version_added: "2.4"
80 before:
81 description:
82 - If specified, only content before this match will be replaced/removed.
83 - Can be used in combination with O(after).
84 - Uses Python regular expressions; see
85 U(https://docs.python.org/3/library/re.html).
86 - Uses DOTALL, which means the V(.) special character I(can match newlines).
87 - Does not use MULTILINE, so V(^) and V($) will only match the beginning and end of the file.
88 type: str
89 version_added: "2.4"
90 backup:
91 description:
92 - Create a backup file including the timestamp information so you can
93 get the original file back if you somehow clobbered it incorrectly.
94 type: bool
95 default: no
96 encoding:
97 description:
98 - The character encoding for reading and writing the file.
99 type: str
100 default: utf-8
101 version_added: "2.4"
102 notes:
103 - As of Ansible 2.3, the O(dest) option has been changed to O(path) as default, but O(dest) still works as well.
104 - As of Ansible 2.7.10, the combined use of O(before) and O(after) works properly. If you were relying on the
105 previous incorrect behavior, you may be need to adjust your tasks.
106 See U(https://github.com/ansible/ansible/issues/31354) for details.
107 - Option O(ignore:follow) has been removed in Ansible 2.5, because this module modifies the contents of the file
108 so O(ignore:follow=no) does not make sense.
109 """
110
111 EXAMPLES = r"""
112 - name: Replace old hostname with new hostname (requires Ansible >= 2.4)
113 ansible.builtin.replace:
114 path: /etc/hosts
115 regexp: '(\s+)old\.host\.name(\s+.*)?$'
116 replace: '\1new.host.name\2'
117
118 - name: Replace after the expression till the end of the file (requires Ansible >= 2.4)
119 ansible.builtin.replace:
120 path: /etc/apache2/sites-available/default.conf
121 after: 'NameVirtualHost [*]'
122 regexp: '^(.+)$'
123 replace: '# \1'
124
125 - name: Replace before the expression from the beginning of the file (requires Ansible >= 2.4)
126 ansible.builtin.replace:
127 path: /etc/apache2/sites-available/default.conf
128 before: '# live site config'
129 regexp: '^(.+)$'
130 replace: '# \1'
131
132 # Prior to Ansible 2.7.10, using before and after in combination did the opposite of what was intended.
133 # see https://github.com/ansible/ansible/issues/31354 for details.
134 # Note (?m) which turns on MULTILINE mode so ^ matches any line's beginning
135 - name: Replace between the expressions (requires Ansible >= 2.4)
136 ansible.builtin.replace:
137 path: /etc/hosts
138 after: '(?m)^<VirtualHost [*]>'
139 before: '</VirtualHost>'
140 regexp: '^(.+)$'
141 replace: '# \1'
142
143 - name: Supports common file attributes
144 ansible.builtin.replace:
145 path: /home/jdoe/.ssh/known_hosts
146 regexp: '^old\.host\.name[^\n]*\n'
147 owner: jdoe
148 group: jdoe
149 mode: '0644'
150
151 - name: Supports a validate command
152 ansible.builtin.replace:
153 path: /etc/apache/ports
154 regexp: '^(NameVirtualHost|Listen)\s+80\s*$'
155 replace: '\1 127.0.0.1:8080'
156 validate: '/usr/sbin/apache2ctl -f %s -t'
157
158 - name: Short form task (in ansible 2+) necessitates backslash-escaped sequences
159 ansible.builtin.replace: path=/etc/hosts regexp='\\b(localhost)(\\d*)\\b' replace='\\1\\2.localdomain\\2 \\1\\2'
160
161 - name: Long form task does not
162 ansible.builtin.replace:
163 path: /etc/hosts
164 regexp: '\b(localhost)(\d*)\b'
165 replace: '\1\2.localdomain\2 \1\2'
166
167 - name: Explicitly specifying positional matched groups in replacement
168 ansible.builtin.replace:
169 path: /etc/ssh/sshd_config
170 regexp: '^(ListenAddress[ ]+)[^\n]+$'
171 replace: '\g<1>0.0.0.0'
172
173 - name: Explicitly specifying named matched groups
174 ansible.builtin.replace:
175 path: /etc/ssh/sshd_config
176 regexp: '^(?P<dctv>ListenAddress[ ]+)(?P<host>[^\n]+)$'
177 replace: '#\g<dctv>\g<host>\n\g<dctv>0.0.0.0'
178 """
179
180 RETURN = r"""#"""
181
182 import os
183 import re
184 import tempfile
185
186 from ansible.module_utils.common.text.converters import to_text
187 from ansible.module_utils.basic import AnsibleModule
188
189
190 def write_changes(module, contents, path, encoding='utf-8'):
191
192 tmpfd, tmpfile = tempfile.mkstemp(dir=module.tmpdir)
193 with os.fdopen(tmpfd, 'w', encoding=encoding) as f:
194 f.write(contents)
195
196 validate = module.params.get('validate', None)
197 valid = not validate
198 if validate:
199 if "%s" not in validate:
200 module.fail_json(msg="validate must contain %%s: %s" % (validate))
201 (rc, out, err) = module.run_command(validate % tmpfile)
202 valid = rc == 0
203 if rc != 0:
204 module.fail_json(msg='failed to validate: '
205 'rc:%s error:%s' % (rc, err))
206 if valid:
207 module.atomic_move(tmpfile, path, unsafe_writes=module.params['unsafe_writes'])
208
209
210 def check_file_attrs(module, changed, message):
211
212 file_args = module.load_file_common_arguments(module.params)
213 if module.set_file_attributes_if_different(file_args, False):
214
215 if changed:
216 message += " and "
217 changed = True
218 message += "ownership, perms or SE linux context changed"
219
220 return message, changed
221
222
223 def main():
224 module = AnsibleModule(
225 argument_spec=dict(
226 path=dict(type='path', required=True, aliases=['dest', 'destfile', 'name']),
227 regexp=dict(type='str', required=True),
228 replace=dict(type='str', default=''),
229 after=dict(type='str'),
230 before=dict(type='str'),
231 backup=dict(type='bool', default=False),
232 validate=dict(type='str'),
233 encoding=dict(type='str', default='utf-8'),
234 ),
235 add_file_common_args=True,
236 supports_check_mode=True,
237 )
238
239 params = module.params
240 path = params['path']
241 encoding = params['encoding']
242 res_args = dict(rc=0)
243 contents = None
244
245 params['after'] = to_text(params['after'], errors='surrogate_or_strict', nonstring='passthru')
246 params['before'] = to_text(params['before'], errors='surrogate_or_strict', nonstring='passthru')
247 params['regexp'] = to_text(params['regexp'], errors='surrogate_or_strict', nonstring='passthru')
248 params['replace'] = to_text(params['replace'], errors='surrogate_or_strict', nonstring='passthru')
249
250 if os.path.isdir(path):
251 module.fail_json(rc=256, msg='Path %s is a directory !' % path)
252
253 if not os.path.exists(path):
254 module.fail_json(rc=257, msg='Path %s does not exist !' % path)
255 else:
256 try:
257 with open(path, 'r', encoding=encoding) as f:
258 contents = f.read()
259 except OSError as ex:
260 raise Exception(f"Unable to read the contents of {path!r}.") from ex
261
262 pattern = u''
263 if params['after'] and params['before']:
264 pattern = u'%s(?P<subsection>.*?)%s' % (params['after'], params['before'])
265 elif params['after']:
266 pattern = u'%s(?P<subsection>.*)' % params['after']
267 elif params['before']:
268 pattern = u'(?P<subsection>.*)%s' % params['before']
269
270 if pattern:
271 section_re = re.compile(pattern, re.DOTALL)
272 match = re.search(section_re, contents)
273 if match:
274 section = match.group('subsection')
275 indices = [match.start('subsection'), match.end('subsection')]
276 else:
277 res_args['msg'] = 'Pattern for before/after params did not match the given file: %s' % pattern
278 res_args['changed'] = False
279 module.exit_json(**res_args)
280 else:
281 section = contents
282
283 mre = re.compile(params['regexp'], re.MULTILINE)
284 try:
285 result = re.subn(mre, params['replace'], section, 0)
286 except re.error as e:
287 module.fail_json(msg="Unable to process replace due to error: %s" % to_text(e))
288
289 if result[1] > 0 and section != result[0]:
290 if pattern:
291 result = (contents[:indices[0]] + result[0] + contents[indices[1]:], result[1])
292 msg = '%s replacements made' % result[1]
293 changed = True
294 if module._diff:
295 res_args['diff'] = {
296 'before_header': path,
297 'before': contents,
298 'after_header': path,
299 'after': result[0],
300 }
301 else:
302 msg = ''
303 changed = False
304
305 if changed and not module.check_mode:
306 if params['backup'] and os.path.exists(path):
307 res_args['backup_file'] = module.backup_local(path)
308 # We should always follow symlinks so that we change the real file
309 path = os.path.realpath(path)
310 write_changes(module, result[0], path, encoding=encoding)
311
312 res_args['msg'], res_args['changed'] = check_file_attrs(module, changed, msg)
313 module.exit_json(**res_args)
314
315
316 if __name__ == '__main__':
317 main()