Ansible does not have a module that can be used to rename files or directories. The copy module can be used to copy files. When you want to rename a file, the mv (move) command and the command module can be used. In this example, command is used to rename foo.txt to bar.txt.
---
- hosts: all
tasks:
- name: rename /tmp/foo.txt to /tmp/bar.txt
command: "mv /tmp/foo.txt /tmp/bar.txt"
...
Or shell can be used
---
- hosts: all
tasks:
- name: rename /tmp/foo.txt to /tmp/bar.txt
shell: "mv /tmp/foo.txt /tmp/bar.txt"
...
The following should be produced.
TASK [rename /tmp/foo.txt to /tmp/bar.txt]
changed: [server1.example.com]
By default, no stdout is printed. The register module can be used to print output to the console.
non-zero return code
If non-zero return code is being displayed in the output of the play, refer to our article on resolving non-zero return code.
Become (root, sudo)
If you do not have permission to rename a file, permission denied will be returned. To resolve this, the become module can be used to become root.
Arguments
Certain arguments can be used with the shell command. In this example, the chdir (change directory) argument is used to perform the shell command from a particular directory.
- name: ps command
shell: "ls"
arg:
chdir: /root
connection module / delegate_to module
By default, Ansible performs tasks on managed node. Refer to run tasks on the control node if you want to run this module on your control node.
Did you find this article helpful?
If so, consider buying me a coffee over at