From a1730af91f94552e8aaff4bedfb8dcae00bd284d Mon Sep 17 00:00:00 2001 From: Brian Coca <bcoca@users.noreply.github.com> Date: Mon, 9 Nov 2020 14:45:09 -0500 Subject: [PATCH] Ensure blockinfile correctly returns backupfile (#72544) * Ensure blockinfile correctly returns backupfile Fixes #27626 based on #27859 Co-authored-by: Giovanni Sciortino (@giovannisciortino) --- .../fragments/blockinfile_fix_no_backup_return.yml | 2 ++ lib/ansible/modules/blockinfile.py | 9 +++++++-- .../blockinfile/tasks/add_block_to_existing_file.yml | 5 +++++ 3 files changed, 14 insertions(+), 2 deletions(-) create mode 100644 changelogs/fragments/blockinfile_fix_no_backup_return.yml diff --git a/changelogs/fragments/blockinfile_fix_no_backup_return.yml b/changelogs/fragments/blockinfile_fix_no_backup_return.yml new file mode 100644 index 00000000000..e35cd41b1b0 --- /dev/null +++ b/changelogs/fragments/blockinfile_fix_no_backup_return.yml @@ -0,0 +1,2 @@ +bugfixes: + - blockinfile now returns name of backup file when this option is used. diff --git a/lib/ansible/modules/blockinfile.py b/lib/ansible/modules/blockinfile.py index 2f80a65edcc..fde44b5d600 100644 --- a/lib/ansible/modules/blockinfile.py +++ b/lib/ansible/modules/blockinfile.py @@ -328,9 +328,10 @@ def main(): msg = 'Block inserted' changed = True + backup_file = None if changed and not module.check_mode: if module.boolean(params['backup']) and path_exists: - module.backup_local(path) + backup_file = module.backup_local(path) # We should always follow symlinks so that we change the real file real_path = os.path.realpath(params['path']) write_changes(module, result, real_path) @@ -345,7 +346,11 @@ def main(): attr_diff['after_header'] = '%s (file attributes)' % path difflist = [diff, attr_diff] - module.exit_json(changed=changed, msg=msg, diff=difflist) + + if backup_file is None: + module.exit_json(changed=changed, msg=msg, diff=difflist) + else: + module.exit_json(changed=changed, msg=msg, diff=difflist, backup_file=backup_file) if __name__ == '__main__': diff --git a/test/integration/targets/blockinfile/tasks/add_block_to_existing_file.yml b/test/integration/targets/blockinfile/tasks/add_block_to_existing_file.yml index dbb93ecce3b..7093ed2b99c 100644 --- a/test/integration/targets/blockinfile/tasks/add_block_to_existing_file.yml +++ b/test/integration/targets/blockinfile/tasks/add_block_to_existing_file.yml @@ -12,6 +12,11 @@ backup: yes register: blockinfile_test0 +- name: ensure we have a bcackup file + assert: + that: + - "'backup_file' in blockinfile_test0" + - name: check content shell: 'grep -c -e "Match User ansible-agent" -e "PasswordAuthentication no" {{ output_dir_test }}/sshd_config' register: blockinfile_test0_grep