| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright: (c) 2014, 2015 YAEGASHI Takeshi <[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: blockinfile |
| 13 |
short_description: Insert/update/remove a text block surrounded by marker lines |
| 14 |
version_added: '2.0' |
| 15 |
description: |
| 16 |
- This module will insert/update/remove a block of multi-line text surrounded by customizable marker lines. |
| 17 |
author: |
| 18 |
- Yaegashi Takeshi (@yaegashi) |
| 19 |
options: |
| 20 |
path: |
| 21 |
description: |
| 22 |
- The file to modify. |
| 23 |
- Before Ansible 2.3 this option was only usable as O(dest), O(destfile) and O(name). |
| 24 |
type: path |
| 25 |
required: yes |
| 26 |
aliases: [ dest, destfile, name ] |
| 27 |
state: |
| 28 |
description: |
| 29 |
- Whether the block should be there or not. |
| 30 |
type: str |
| 31 |
choices: [ absent, present ] |
| 32 |
default: present |
| 33 |
marker: |
| 34 |
description: |
| 35 |
- The marker line template. |
| 36 |
- C({mark}) will be replaced with the values in O(marker_begin) (default=C(BEGIN)) and O(marker_end) (default=C(END)). |
| 37 |
- Using a custom marker without the C({mark}) variable may result in the block being repeatedly inserted on subsequent playbook runs. |
| 38 |
- Multi-line markers are not supported and will result in the block being repeatedly inserted on subsequent playbook runs. |
| 39 |
- A newline is automatically appended by the module to O(marker_begin) and O(marker_end). |
| 40 |
type: str |
| 41 |
default: '# {mark} ANSIBLE MANAGED BLOCK' |
| 42 |
block: |
| 43 |
description: |
| 44 |
- The text to insert inside the marker lines. |
| 45 |
- If it is missing or an empty string, the block will be removed as if O(state) were specified to V(absent). |
| 46 |
type: str |
| 47 |
default: '' |
| 48 |
aliases: [ content ] |
| 49 |
insertafter: |
| 50 |
description: |
| 51 |
- If specified and no begin/ending O(marker) lines are found, the block will be inserted after the last match of specified regular expression. |
| 52 |
- A special value is available; V(EOF) for inserting the block at the end of the file. |
| 53 |
- If specified regular expression has no matches or no value is passed, V(EOF) will be used instead. |
| 54 |
- The presence of the multiline flag (?m) in the regular expression controls whether the match is done line by line or with multiple lines. |
| 55 |
This behaviour was added in ansible-core 2.14. |
| 56 |
type: str |
| 57 |
insertbefore: |
| 58 |
description: |
| 59 |
- If specified and no begin/ending O(marker) lines are found, the block will be inserted before the last match of specified regular expression. |
| 60 |
- A special value is available; V(BOF) for inserting the block at the beginning of the file. |
| 61 |
- If specified regular expression has no matches, the block will be inserted at the end of the file. |
| 62 |
- The presence of the multiline flag (?m) in the regular expression controls whether the match is done line by line or with multiple lines. |
| 63 |
This behaviour was added in ansible-core 2.14. |
| 64 |
type: str |
| 65 |
create: |
| 66 |
description: |
| 67 |
- Create a new file if it does not exist. |
| 68 |
type: bool |
| 69 |
default: no |
| 70 |
backup: |
| 71 |
description: |
| 72 |
- Create a backup file including the timestamp information so you can |
| 73 |
get the original file back if you somehow clobbered it incorrectly. |
| 74 |
type: bool |
| 75 |
default: no |
| 76 |
marker_begin: |
| 77 |
description: |
| 78 |
- This will be inserted at C({mark}) in the opening ansible block O(marker). |
| 79 |
type: str |
| 80 |
default: BEGIN |
| 81 |
version_added: '2.5' |
| 82 |
marker_end: |
| 83 |
required: false |
| 84 |
description: |
| 85 |
- This will be inserted at C({mark}) in the closing ansible block O(marker). |
| 86 |
type: str |
| 87 |
default: END |
| 88 |
version_added: '2.5' |
| 89 |
append_newline: |
| 90 |
required: false |
| 91 |
description: |
| 92 |
- Append a blank line to the inserted block, if this does not appear at the end of the file. |
| 93 |
- Note that this attribute is not considered when C(state) is set to C(absent) |
| 94 |
type: bool |
| 95 |
default: no |
| 96 |
version_added: '2.16' |
| 97 |
prepend_newline: |
| 98 |
required: false |
| 99 |
description: |
| 100 |
- Prepend a blank line to the inserted block, if this does not appear at the beginning of the file. |
| 101 |
- Note that this attribute is not considered when C(state) is set to C(absent) |
| 102 |
type: bool |
| 103 |
default: no |
| 104 |
version_added: '2.16' |
| 105 |
encoding: |
| 106 |
description: |
| 107 |
- The character set in which the target file is encoded. |
| 108 |
- For a list of available built-in encodings, see U(https://docs.python.org/3/library/codecs.html#standard-encodings) |
| 109 |
type: str |
| 110 |
default: utf-8 |
| 111 |
version_added: '2.20' |
| 112 |
notes: |
| 113 |
- When using C(with_*) loops be aware that if you do not set a unique mark the block will be overwritten on each iteration. |
| 114 |
- As of Ansible 2.3, the O(dest) option has been changed to O(path) as default, but O(dest) still works as well. |
| 115 |
- Option O(ignore:follow) has been removed in Ansible 2.5, because this module modifies the contents of the file |
| 116 |
so O(ignore:follow=no) does not make sense. |
| 117 |
- When more than one block should be handled in one file you must change the O(marker) per task. |
| 118 |
extends_documentation_fragment: |
| 119 |
- action_common_attributes |
| 120 |
- action_common_attributes.files |
| 121 |
- files |
| 122 |
- validate |
| 123 |
attributes: |
| 124 |
check_mode: |
| 125 |
support: full |
| 126 |
diff_mode: |
| 127 |
support: full |
| 128 |
safe_file_operations: |
| 129 |
support: full |
| 130 |
platform: |
| 131 |
support: full |
| 132 |
platforms: posix |
| 133 |
vault: |
| 134 |
support: none |
| 135 |
""" |
| 136 |
|
| 137 |
EXAMPLES = r""" |
| 138 |
# Before Ansible 2.3, option 'dest' or 'name' was used instead of 'path' |
| 139 |
- name: Insert/Update "Match User" configuration block in /etc/ssh/sshd_config prepending and appending a new line |
| 140 |
ansible.builtin.blockinfile: |
| 141 |
path: /etc/ssh/sshd_config |
| 142 |
append_newline: true |
| 143 |
prepend_newline: true |
| 144 |
block: | |
| 145 |
Match User ansible-agent |
| 146 |
PasswordAuthentication no |
| 147 |
|
| 148 |
- name: Insert/Update eth0 configuration stanza in /etc/network/interfaces |
| 149 |
(it might be better to copy files into /etc/network/interfaces.d/) |
| 150 |
ansible.builtin.blockinfile: |
| 151 |
path: /etc/network/interfaces |
| 152 |
block: | |
| 153 |
iface eth0 inet static |
| 154 |
address 192.0.2.23 |
| 155 |
netmask 255.255.255.0 |
| 156 |
|
| 157 |
- name: Insert/Update configuration using a local file and validate it |
| 158 |
ansible.builtin.blockinfile: |
| 159 |
block: "{{ lookup('ansible.builtin.file', './local/sshd_config') }}" |
| 160 |
path: /etc/ssh/sshd_config |
| 161 |
backup: yes |
| 162 |
validate: /usr/sbin/sshd -T -f %s |
| 163 |
|
| 164 |
- name: Insert/Update HTML surrounded by custom markers after <body> line |
| 165 |
ansible.builtin.blockinfile: |
| 166 |
path: /var/www/html/index.html |
| 167 |
marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->" |
| 168 |
insertafter: "<body>" |
| 169 |
block: | |
| 170 |
<h1>Welcome to {{ ansible_hostname }}</h1> |
| 171 |
<p>Last updated on {{ ansible_date_time.iso8601 }}</p> |
| 172 |
|
| 173 |
- name: Remove HTML as well as surrounding markers |
| 174 |
ansible.builtin.blockinfile: |
| 175 |
path: /var/www/html/index.html |
| 176 |
marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->" |
| 177 |
block: "" |
| 178 |
|
| 179 |
- name: Add mappings to /etc/hosts |
| 180 |
ansible.builtin.blockinfile: |
| 181 |
path: /etc/hosts |
| 182 |
block: | |
| 183 |
{{ item.ip }} {{ item.name }} |
| 184 |
marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.name }}" |
| 185 |
loop: |
| 186 |
- { name: host1, ip: 10.10.1.10 } |
| 187 |
- { name: host2, ip: 10.10.1.11 } |
| 188 |
- { name: host3, ip: 10.10.1.12 } |
| 189 |
|
| 190 |
- name: Search with a multiline search flags regex and if found insert after |
| 191 |
blockinfile: |
| 192 |
path: listener.ora |
| 193 |
block: "{{ listener_line | indent(width=8, first=True) }}" |
| 194 |
insertafter: '(?m)SID_LIST_LISTENER_DG =\n.*\(SID_LIST =' |
| 195 |
marker: " <!-- {mark} ANSIBLE MANAGED BLOCK -->" |
| 196 |
|
| 197 |
""" |
| 198 |
|
| 199 |
import re |
| 200 |
import os |
| 201 |
import tempfile |
| 202 |
|
| 203 |
from ansible.module_utils.basic import AnsibleModule |
| 204 |
from ansible.module_utils.common.text.converters import to_native |
| 205 |
|
| 206 |
|
| 207 |
def write_changes(module, contents, path, encoding=None): |
| 208 |
|
| 209 |
tmpfd, tmpfile = tempfile.mkstemp(dir=module.tmpdir) |
| 210 |
# newline param set to translate newline sequences with system default line separator |
| 211 |
with os.fdopen(tmpfd, 'w', encoding=encoding, newline=None) as tf: |
| 212 |
tf.write(contents) |
| 213 |
|
| 214 |
validate = module.params.get('validate', None) |
| 215 |
valid = not validate |
| 216 |
if validate: |
| 217 |
if "%s" not in validate: |
| 218 |
module.fail_json(msg="validate must contain %%s: %s" % (validate)) |
| 219 |
(rc, out, err) = module.run_command(validate % tmpfile) |
| 220 |
valid = rc == 0 |
| 221 |
if rc != 0: |
| 222 |
module.fail_json(msg='failed to validate: ' |
| 223 |
'rc:%s error:%s' % (rc, err)) |
| 224 |
if valid: |
| 225 |
module.atomic_move(tmpfile, path, unsafe_writes=module.params['unsafe_writes']) |
| 226 |
|
| 227 |
|
| 228 |
def check_file_attrs(module, changed, message, diff): |
| 229 |
|
| 230 |
file_args = module.load_file_common_arguments(module.params) |
| 231 |
if module.set_file_attributes_if_different(file_args, False, diff=diff): |
| 232 |
|
| 233 |
if changed: |
| 234 |
message += " and " |
| 235 |
changed = True |
| 236 |
message += "ownership, perms or SE linux context changed" |
| 237 |
|
| 238 |
return message, changed |
| 239 |
|
| 240 |
|
| 241 |
def main(): |
| 242 |
module = AnsibleModule( |
| 243 |
argument_spec=dict( |
| 244 |
path=dict(type='path', required=True, aliases=['dest', 'destfile', 'name']), |
| 245 |
state=dict(type='str', default='present', choices=['absent', 'present']), |
| 246 |
marker=dict(type='str', default='# {mark} ANSIBLE MANAGED BLOCK'), |
| 247 |
block=dict(type='str', default='', aliases=['content']), |
| 248 |
insertafter=dict(type='str'), |
| 249 |
insertbefore=dict(type='str'), |
| 250 |
create=dict(type='bool', default=False), |
| 251 |
backup=dict(type='bool', default=False), |
| 252 |
validate=dict(type='str'), |
| 253 |
marker_begin=dict(type='str', default='BEGIN'), |
| 254 |
marker_end=dict(type='str', default='END'), |
| 255 |
append_newline=dict(type='bool', default=False), |
| 256 |
prepend_newline=dict(type='bool', default=False), |
| 257 |
encoding=dict(type='str', default='utf-8'), |
| 258 |
), |
| 259 |
mutually_exclusive=[['insertbefore', 'insertafter']], |
| 260 |
add_file_common_args=True, |
| 261 |
supports_check_mode=True |
| 262 |
) |
| 263 |
params = module.params |
| 264 |
path = params['path'] |
| 265 |
|
| 266 |
encoding = module.params.get('encoding', None) |
| 267 |
|
| 268 |
if os.path.isdir(path): |
| 269 |
module.fail_json(rc=256, |
| 270 |
msg='Path %s is a directory !' % path) |
| 271 |
|
| 272 |
path_exists = os.path.exists(path) |
| 273 |
if not path_exists: |
| 274 |
if not module.boolean(params['create']): |
| 275 |
module.fail_json(rc=257, |
| 276 |
msg='Path %s does not exist !' % path) |
| 277 |
destpath = os.path.dirname(path) |
| 278 |
if destpath and not os.path.exists(destpath) and not module.check_mode: |
| 279 |
try: |
| 280 |
os.makedirs(destpath) |
| 281 |
except OSError as e: |
| 282 |
module.fail_json(msg='Error creating %s Error code: %s Error description: %s' % (destpath, e.errno, e.strerror)) |
| 283 |
except Exception as e: |
| 284 |
module.fail_json(msg='Error creating %s Error: %s' % (destpath, to_native(e))) |
| 285 |
original = None |
| 286 |
lines = [] |
| 287 |
else: |
| 288 |
# newline param set to preserve newline sequences read from file |
| 289 |
with open(path, 'r', encoding=encoding, newline='') as f: |
| 290 |
original = f.read() |
| 291 |
lines = original.splitlines(True) |
| 292 |
|
| 293 |
diff = {'before': '', |
| 294 |
'after': '', |
| 295 |
'before_header': '%s (content)' % path, |
| 296 |
'after_header': '%s (content)' % path} |
| 297 |
|
| 298 |
if module._diff and original: |
| 299 |
diff['before'] = original |
| 300 |
|
| 301 |
insertbefore = params['insertbefore'] |
| 302 |
insertafter = params['insertafter'] |
| 303 |
block = params['block'] |
| 304 |
marker = params['marker'] |
| 305 |
present = params['state'] == 'present' |
| 306 |
|
| 307 |
line_separator = os.linesep |
| 308 |
blank_line = [line_separator] |
| 309 |
|
| 310 |
if not present and not path_exists: |
| 311 |
module.exit_json(changed=False, msg="File %s not present" % path) |
| 312 |
|
| 313 |
if insertbefore is None and insertafter is None: |
| 314 |
insertafter = 'EOF' |
| 315 |
|
| 316 |
if insertafter not in (None, 'EOF'): |
| 317 |
insertre = re.compile(insertafter) |
| 318 |
elif insertbefore not in (None, 'BOF'): |
| 319 |
insertre = re.compile(insertbefore) |
| 320 |
else: |
| 321 |
insertre = None |
| 322 |
|
| 323 |
marker0 = re.sub(r'{mark}', params['marker_begin'], marker) + line_separator |
| 324 |
marker1 = re.sub(r'{mark}', params['marker_end'], marker) + line_separator |
| 325 |
|
| 326 |
if present and block: |
| 327 |
if not block.endswith(line_separator): |
| 328 |
block += line_separator |
| 329 |
|
| 330 |
blocklines = [marker0] + block.splitlines(True) + [marker1] |
| 331 |
else: |
| 332 |
blocklines = [] |
| 333 |
|
| 334 |
n0 = n1 = None |
| 335 |
for i, line in enumerate(lines): |
| 336 |
if line == marker0: |
| 337 |
n0 = i |
| 338 |
if line == marker1: |
| 339 |
n1 = i |
| 340 |
|
| 341 |
if None in (n0, n1): |
| 342 |
n0 = None |
| 343 |
if insertre is not None: |
| 344 |
if insertre.flags & re.MULTILINE: |
| 345 |
match = insertre.search(original) |
| 346 |
if match: |
| 347 |
if insertafter: |
| 348 |
n0 = original.count('\n', 0, match.end()) |
| 349 |
elif insertbefore: |
| 350 |
n0 = original.count('\n', 0, match.start()) |
| 351 |
else: |
| 352 |
for i, line in enumerate(lines): |
| 353 |
if insertre.search(line): |
| 354 |
n0 = i |
| 355 |
if n0 is None: |
| 356 |
n0 = len(lines) |
| 357 |
elif insertafter is not None: |
| 358 |
n0 += 1 |
| 359 |
elif insertbefore is not None: |
| 360 |
n0 = 0 # insertbefore=BOF |
| 361 |
else: |
| 362 |
n0 = len(lines) # insertafter=EOF |
| 363 |
elif n0 < n1: |
| 364 |
lines[n0:n1 + 1] = [] |
| 365 |
else: |
| 366 |
lines[n1:n0 + 1] = [] |
| 367 |
n0 = n1 |
| 368 |
|
| 369 |
# Ensure there is a line separator before the block of lines to be inserted |
| 370 |
if n0 > 0: |
| 371 |
if not lines[n0 - 1].endswith(line_separator): |
| 372 |
lines[n0 - 1] += line_separator |
| 373 |
|
| 374 |
# Before the block: check if we need to prepend a blank line |
| 375 |
# If yes, we need to add the blank line if we are not at the beginning of the file |
| 376 |
# and the previous line is not a blank line |
| 377 |
# In both cases, we need to shift by one on the right the inserting position of the block |
| 378 |
if params['prepend_newline'] and present: |
| 379 |
if n0 != 0 and lines[n0 - 1] != line_separator: |
| 380 |
lines[n0:n0] = blank_line |
| 381 |
n0 += 1 |
| 382 |
|
| 383 |
# Insert the block |
| 384 |
lines[n0:n0] = blocklines |
| 385 |
|
| 386 |
# After the block: check if we need to append a blank line |
| 387 |
# If yes, we need to add the blank line if we are not at the end of the file |
| 388 |
# and the line right after is not a blank line |
| 389 |
if params['append_newline'] and present: |
| 390 |
line_after_block = n0 + len(blocklines) |
| 391 |
if line_after_block < len(lines) and lines[line_after_block] != line_separator: |
| 392 |
lines[line_after_block:line_after_block] = blank_line |
| 393 |
|
| 394 |
if lines: |
| 395 |
result = ''.join(lines) |
| 396 |
else: |
| 397 |
result = '' |
| 398 |
|
| 399 |
if module._diff: |
| 400 |
diff['after'] = result |
| 401 |
|
| 402 |
if original == result: |
| 403 |
msg = '' |
| 404 |
changed = False |
| 405 |
elif original is None: |
| 406 |
msg = 'File created' |
| 407 |
changed = True |
| 408 |
elif not blocklines: |
| 409 |
msg = 'Block removed' |
| 410 |
changed = True |
| 411 |
else: |
| 412 |
msg = 'Block inserted' |
| 413 |
changed = True |
| 414 |
|
| 415 |
backup_file = None |
| 416 |
if changed and not module.check_mode: |
| 417 |
if module.boolean(params['backup']) and path_exists: |
| 418 |
backup_file = module.backup_local(path) |
| 419 |
# We should always follow symlinks so that we change the real file |
| 420 |
real_path = os.path.realpath(params['path']) |
| 421 |
write_changes(module, result, real_path, encoding) |
| 422 |
|
| 423 |
if module.check_mode and not path_exists: |
| 424 |
module.exit_json(changed=changed, msg=msg, diff=diff) |
| 425 |
|
| 426 |
attr_diff = {} |
| 427 |
msg, changed = check_file_attrs(module, changed, msg, attr_diff) |
| 428 |
|
| 429 |
attr_diff['before_header'] = '%s (file attributes)' % path |
| 430 |
attr_diff['after_header'] = '%s (file attributes)' % path |
| 431 |
|
| 432 |
difflist = [diff, attr_diff] |
| 433 |
|
| 434 |
if backup_file is None: |
| 435 |
module.exit_json(changed=changed, msg=msg, diff=difflist) |
| 436 |
else: |
| 437 |
module.exit_json(changed=changed, msg=msg, diff=difflist, backup_file=backup_file) |
| 438 |
|
| 439 |
|
| 440 |
if __name__ == '__main__': |
| 441 |
main() |