Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move/rename a file using an Ansible task on a remote system

Tags:

file

ansible

move

How is it possible to move/rename a file/directory using an Ansible module on a remote system? I don't want to use the command/shell tasks and I don't want to copy the file from the local system to the remote system.

like image 772
Christian Berendt Avatar asked Jun 11 '14 12:06

Christian Berendt


People also ask

Which Ansible modules can be used to change the contents of a file?

The lineinfile - module is the best option, if you just want to add, replace or remove one line. The replace - module is best, if you want to add, replace or delete several lines.


3 Answers

From version 2.0, in copy module you can use remote_src parameter.

If True it will go to the remote/target machine for the src.

- name: Copy files from foo to bar
  copy: remote_src=True src=/path/to/foo dest=/path/to/bar

If you want to move file you need to delete old file with file module

- name: Remove old files foo
  file: path=/path/to/foo state=absent

From version 2.8 copy module remote_src supports recursive copying.

like image 54
Alex Avatar answered Oct 08 '22 14:10

Alex


The file module doesn't copy files on the remote system. The src parameter is only used by the file module when creating a symlink to a file.

If you want to move/rename a file entirely on a remote system then your best bet is to use the command module to just invoke the appropriate command:

- name: Move foo to bar
  command: mv /path/to/foo /path/to/bar

If you want to get fancy then you could first use the stat module to check that foo actually exists:

- name: stat foo
  stat: path=/path/to/foo
  register: foo_stat

- name: Move foo to bar
  command: mv /path/to/foo /path/to/bar
  when: foo_stat.stat.exists
like image 249
Bruce P Avatar answered Oct 08 '22 14:10

Bruce P


I have found the creates option in the command module useful. How about this:

- name: Move foo to bar
  command: creates="path/to/bar" mv /path/to/foo /path/to/bar

I used to do a 2 task approach using stat like Bruce P suggests. Now I do this as one task with creates. I think this is a lot clearer.

like image 117
Tom Ekberg Avatar answered Oct 08 '22 13:10

Tom Ekberg