diff --git a/lib/ansible/plugins/action/fetch.py b/lib/ansible/plugins/action/fetch.py index 821a365a12c..62d1ac51f52 100644 --- a/lib/ansible/plugins/action/fetch.py +++ b/lib/ansible/plugins/action/fetch.py @@ -120,6 +120,11 @@ class ActionModule(ActionBase): dest = os.path.expanduser(dest) if flat: + if os.path.isdir(to_bytes(dest, errors='surrogate_or_strict')) and not dest.endswith(os.sep): + result['msg'] = "dest is an existing directory, use a trailing slash if you want to fetch src into that directory" + result['file'] = dest + result['failed'] = True + return result if dest.endswith(os.sep): # if the path ends with "/", we'll use the source filename as the # destination filename diff --git a/test/integration/targets/fetch/tasks/main.yml b/test/integration/targets/fetch/tasks/main.yml index 03339dee814..b110e91a0b1 100644 --- a/test/integration/targets/fetch/tasks/main.yml +++ b/test/integration/targets/fetch/tasks/main.yml @@ -122,3 +122,17 @@ assert: that: 'diff.stdout == ""' + +- name: dest is an existing directory name without trailing slash and flat=yes, should fail + fetch: + src: "{{ output_dir }}/orig" + dest: "{{ output_dir }}" + flat: yes + register: failed_fetch_dest_dir + ignore_errors: true + +- name: check that it indeed failed + assert: + that: + - "failed_fetch_dest_dir|failed" + - "failed_fetch_dest_dir.msg"