Bootstrap FreeKB - Ansible - Move files and directories
Ansible - Move files and directories

Updated:   |  Ansible articles

Ansible does not have a module that can be used to move files. The copy module can be used to copy files. When you want to move a file from one directory to another directory, the command module or shell module can be used. Before moving a file, you'll want to use the stat module to determine if the file exists.

---
- hosts: localhost
  tasks:
  - name: store the stats of example.txt in the 'out' variable
    stat:
      path: /usr/local/example.txt
    register: out
...

 

In this example, the command module is used to move the /usr/local/example.txt file to the /tmp directory if the example.txt file exists.

---
- hosts: localhost
  tasks:
  - name: "move example.txt to the /tmp directory"
    command: "mv example.txt /tmp"
    when: out.stat.exists == true
...

 

Or the shell module can be used.

---
- hosts: localhost
  tasks:
  - name: "move /usr/local/example.txt to the /tmp directory"
    shell: "mv /usr/local/example.txt /tmp"
    when: out.stat.exists == true
...

 

Or like this, using the chdir argument.

---
- hosts: localhost
  tasks:
  - name: "move /usr/local/example.txt to the /tmp directory"
    shell: "mv example.txt /tmp"
    arg:
      chdir: /usr/local
    when: out.stat.exists == true
...

 


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 move a file, permission denied will be returned. To resolve this, the become module can be used to become root.

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 08d966 in the box below so that we can be sure you are a human.