Ansible Move File: Rename & Move Files on Remote Hosts (Complete Guide)
By Luca Berton · Published 2024-01-01 · Category: file-operations
How to move and rename files with Ansible. Use command mv, copy+file, or ansible.builtin.copy with remote_src. Move files between directories on remote hosts with playbook examples.
Ansible Move File: Rename & Move Files on Remote Hosts (Complete Guide)
Ansible doesn't have a dedicated "move" module, but there are several reliable ways to move and rename files on remote hosts. This guide covers every approach with practical examples.
Method 1: command + mv (Simplest)
The removes and creates parameters make it idempotent.
Method 2: copy + file (Ansible-Native)
This approach gives you control over ownership and permissions during the move.
Method 3: Rename a File
Method 4: Move with Stat Check (Conditional)
Move Multiple Files
Move with Backup
Move Directory
Atomic Move (Safe for Config Files)
Which Method Should You Use?
| Scenario | Best Method | |----------|-------------| | Simple move/rename | command: mv with creates/removes | | Move + change permissions | copy (remote_src) + file (absent) | | Move with validation | Template to .tmp, then command: mv | | Move if file exists | stat check + conditional command: mv | | Move multiple files | find + loop + command: mv | | Move with glob patterns | shell: mv *.log /archive/ |
FAQ
Does Ansible have a move module?
No. Ansible doesn't have a dedicated move/rename module. Use ansible.builtin.command: mv for simple moves, or ansible.builtin.copy with remote_src: true followed by ansible.builtin.file: state=absent for an Ansible-native approach with permission control.
How do I move a file in Ansible idempotently?
Use ansible.builtin.command: mv source dest with creates: dest and removes: source parameters. This ensures the command only runs if the source exists and the destination doesn't.
How do I rename a file with Ansible?
Use ansible.builtin.command: mv /path/old-name /path/new-name with creates and removes for idempotency. Renaming is just a move within the same directory.
Can I move files between remote hosts with Ansible?
Not directly. Use ansible.builtin.fetch to download from one host, then ansible.builtin.copy to upload to another. Or use ansible.posix.synchronize (rsync) for efficient transfers between hosts.
Conclusion
While Ansible lacks a dedicated move module, command: mv with creates/removes is the most straightforward approach. Use copy + file when you need permission changes, and stat checks for conditional moves.
Related Articles • Ansible copy Module: Copy Files Local to Remote • Ansible file Module: Manage File Properties • Ansible find Module: Search Files on Remote Hosts
Category: file-operations