#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2013, Evan Kaufman = 2.4) replace: path: /etc/hosts regexp: '(\s+)old\.host\.name(\s+.*)?$' replace: '\1new.host.name\2' after: Start after line.* backup: yes - name: Replace before the expression till the begin of the file (requires Ansible >= 2.4) replace: path: /etc/hosts regexp: '(\s+)old\.host\.name(\s+.*)?$' replace: '\1new.host.name\2' before: 'Start before line.*' backup: yes - name: Replace between the expressions (requires Ansible >= 2.4) replace: path: /etc/hosts regexp: '(\s+)old\.host\.name(\s+.*)?$' replace: '\1new.host.name\2' after: 'Start after line.*' before: 'Start before line.*' backup: yes - replace: path: /home/jdoe/.ssh/known_hosts regexp: '^old\.host\.name[^\n]*\n' owner: jdoe group: jdoe mode: '0644' - replace: path: /etc/apache/ports regexp: '^(NameVirtualHost|Listen)\s+80\s*$' replace: '\1 127.0.0.1:8080' validate: '/usr/sbin/apache2ctl -f %s -t' - name: Short form task (in ansible 2+) necessitates backslash-escaped sequences replace: dest=/etc/hosts regexp='\\b(localhost)(\\d*)\\b' replace='\\1\\2.localdomain\\2 \\1\\2' - name: Long form task does not replace: dest: /etc/hosts regexp: '\b(localhost)(\d*)\b' replace: '\1\2.localdomain\2 \1\2' ''' import os import re import tempfile from ansible.module_utils._text import to_text, to_bytes from ansible.module_utils.basic import AnsibleModule def write_changes(module, contents, path): tmpfd, tmpfile = tempfile.mkstemp(dir=module.tmpdir) f = os.fdopen(tmpfd, 'wb') f.write(contents) f.close() validate = module.params.get('validate', None) valid = not validate if validate: if "%s" not in validate: module.fail_json(msg="validate must contain %%s: %s" % (validate)) (rc, out, err) = module.run_command(validate % tmpfile) valid = rc == 0 if rc != 0: module.fail_json(msg='failed to validate: ' 'rc:%s error:%s' % (rc, err)) if valid: module.atomic_move(tmpfile, path, unsafe_writes=module.params['unsafe_writes']) def check_file_attrs(module, changed, message): file_args = module.load_file_common_arguments(module.params) if module.set_file_attributes_if_different(file_args, False): if changed: message += " and " changed = True message += "ownership, perms or SE linux context changed" return message, changed def main(): module = AnsibleModule( argument_spec=dict( path=dict(type='path', required=True, aliases=['dest', 'destfile', 'name']), regexp=dict(type='str', required=True), replace=dict(type='str', default=''), after=dict(type='str'), before=dict(type='str'), backup=dict(type='bool', default=False), validate=dict(type='str'), encoding=dict(type='str', default='utf-8'), ), add_file_common_args=True, supports_check_mode=True, ) params = module.params path = params['path'] encoding = params['encoding'] res_args = dict() params['after'] = to_text(params['after'], errors='surrogate_or_strict', nonstring='passthru') params['before'] = to_text(params['before'], errors='surrogate_or_strict', nonstring='passthru') params['regexp'] = to_text(params['regexp'], errors='surrogate_or_strict', nonstring='passthru') params['replace'] = to_text(params['replace'], errors='surrogate_or_strict', nonstring='passthru') if os.path.isdir(path): module.fail_json(rc=256, msg='Path %s is a directory !' % path) if not os.path.exists(path): module.fail_json(rc=257, msg='Path %s does not exist !' % path) else: f = open(path, 'rb') contents = to_text(f.read(), errors='surrogate_or_strict', encoding=encoding) f.close() pattern = u'' if params['after'] and params['before']: pattern = u'%s(?P.*?)%s' % (params['before'], params['after']) elif params['after']: pattern = u'%s(?P.*)' % params['after'] elif params['before']: pattern = u'(?P.*)%s' % params['before'] if pattern: section_re = re.compile(pattern, re.DOTALL) match = re.search(section_re, contents) if match: section = match.group('subsection') else: res_args['msg'] = 'Pattern for before/after params did not match the given file: %s' % pattern res_args['changed'] = False module.exit_json(**res_args) else: section = contents mre = re.compile(params['regexp'], re.MULTILINE) result = re.subn(mre, params['replace'], section, 0) if result[1] > 0 and section != result[0]: if pattern: result = (contents.replace(section, result[0]), result[1]) msg = '%s replacements made' % result[1] changed = True if module._diff: res_args['diff'] = { 'before_header': path, 'before': contents, 'after_header': path, 'after': result[0], } else: msg = '' changed = False if changed and not module.check_mode: if params['backup'] and os.path.exists(path): res_args['backup_file'] = module.backup_local(path) # We should always follow symlinks so that we change the real file path = os.path.realpath(path) write_changes(module, to_bytes(result[0], encoding=encoding), path) res_args['msg'], res_args['changed'] = check_file_attrs(module, changed, msg) module.exit_json(**res_args) if __name__ == '__main__': main()