diff --git a/changelogs/fragments/file-return-state-when-file-does-not-exist.yaml b/changelogs/fragments/file-return-state-when-file-does-not-exist.yaml new file mode 100644 index 00000000000..c51abb29c58 --- /dev/null +++ b/changelogs/fragments/file-return-state-when-file-does-not-exist.yaml @@ -0,0 +1,2 @@ +bugfixes: + - "file - return ``'state': 'absent'`` when a file does not exist (https://github.com/ansible/ansible/issues/66171)" diff --git a/lib/ansible/modules/file.py b/lib/ansible/modules/file.py index bd313baf9e8..ee966572345 100644 --- a/lib/ansible/modules/file.py +++ b/lib/ansible/modules/file.py @@ -583,7 +583,7 @@ def ensure_file_attributes(path, follow, timestamps): if prev_state not in ('file', 'hard'): # file is not absent and any other state is a conflict raise AnsibleModuleError(results={'msg': 'file (%s) is %s, cannot continue' % (path, prev_state), - 'path': path}) + 'path': path, 'state': prev_state}) diff = initial_diff(path, 'file', prev_state) changed = module.set_fs_attributes_if_different(file_args, False, diff, expand=False) diff --git a/test/integration/targets/file/tasks/main.yml b/test/integration/targets/file/tasks/main.yml index 8731c55474a..4e1d88e6bae 100644 --- a/test/integration/targets/file/tasks/main.yml +++ b/test/integration/targets/file/tasks/main.yml @@ -61,6 +61,25 @@ - "file_result.changed == false" - "file_result.state == 'file'" +- name: Make sure file does not exist + file: + path: /tmp/ghost + state: absent + +- name: Target a file that does not exist + file: + path: /tmp/ghost + ignore_errors: yes + register: ghost_file_result + +- name: Validate ghost file results + assert: + that: + - ghost_file_result is failed + - ghost_file_result is not changed + - ghost_file_result.state == 'absent' + - "'cannot continue' in ghost_file_result.msg" + - name: verify that we are checking an absent file file: path={{output_dir}}/bar.txt state=absent register: file2_result @@ -269,7 +288,7 @@ copy: src=foobar dest={{output_dir}} - name: check what would be removed if folder state was absent and diff is enabled - file: + file: path: "{{ item }}" state: absent check_mode: yes