Ansible to rename a file only if exists
Solution 1:
Below is a working solution. Note that you may want to set the owner/permissions on the file created by blockinfile
, and that blockinfile
will add insertion anchors around the inserted text in the destination file. Both of these can be configured (see the docs)
- name: Some very cool play
hosts: test
gather_facts: false
vars:
destination_path: /jp/test
legacy_path: /jp/Test
tasks:
- name: Check if legacy file exists
stat:
path: "{{ legacy_path }}"
register: legacy_status
- name: Move contents of legacy file to destination file
when: legacy_status.stat.exists is true
block:
# Note that there is currently no module to read the contents of a
# file on the remote, so using "cat" via command is the best alternative
- name: Read contents of legacy file
command:
cmd: cat {{ legacy_path }}
register: legacy_contents
changed_when: false
- name: Add contents of legacy file to destination file
blockinfile:
path: "{{ destination_path }}"
state: present
block: "{{ legacy_contents.stdout }}"
# This ensures the file is created if it does not exist,
# saving an extra task to rename the file if necessary
create: true
- name: Remove legacy file
file:
path: "{{ legacy_path }}"
state: absent
The error you have there is due to the loop variable not being a list, but a dictionary object. When you invoke loop: "{{ jpresult.results }}"
(note, see loop
vs with_
) the value of {{ item }}
for each iteration of the loop is a single item in the list, rather than the full list. To access the stat value of the current loop index you can use item.stat
, or to access the stat of a different iteration you can use jpresult.results.N.stat
(where N
is the index you want to access).