How to rename a file or directory using an Ansible task on a remote system?
I'm going to show you a live Playbook with some simple Ansible code.
I'm Luca Berton and welcome to today's episode of Ansible Pilot.
Ansible rename file/directory
First of all let me demystify that I'd like to propose a solution using only Ansible native modules, so no shell module to invoke the Unix utility mv.
Today we're talking about Ansible two modules copy and file
The full names are ansible.builtin.copy and ansible.builtin.file which means are part of the collection of modules "builtin" with ansible and shipped with it.
Both are these modules are pretty stable and out for years.
The purpose of the copy module is to copy files to remote locations.
Once the file is successfully copied we could use the module file to delete the source file.
Parameters
Module copy
- dest path - destination
- src string - source
- remote_src boolean - no / yes
Module file
- path string (dest, name) - file path
- state string - file/absent/directory/hard/link/touch
The parameter list is pretty wide but I'll summarize the most useful.
The only required parameter is "dest" which specifies the destination path.
The "src" specifies the source file presumed in the controller host. It could be a relative or absolute path.
From version 2.0, in the copy module, you can use the "remote_src" parameter.
If True it will search the file in the remote/target machine for the src.
From version 2.8 copy module remote_src supports recursive copying.
The only required is "path", where you specify the filesystem path of the file you're going to edit.
The state defines the type of object we are modifying, the default is "file" but we could also handle directories, hardlink, symlink, or only update the access time with the "touch" option.
For our use case, we are going to use the "absent" option.
Demo
Let's jump in a real-life playbook to rename files or directories with Ansible
code
- rename/file.yml
``yaml
---
- name: rename file or directory
hosts: all
vars:
mysrc: "~/foo"
mydst: "~/bar"
tasks:
- name: Check if file exists
ansible.builtin.stat:
path: "{{ mysrc }}"
register: check_file_name
- name: print debug
ansible.builtin.debug:
var: check_file_name
- name: Copy file with new name
ansible.builtin.copy:
remote_src: true
src: "{{ mysrc }}"
dest: "{{ mydst }}"
when: check_file_name.stat.exists
- name: Remove old file
ansible.builtin.file:
path: "{{ mysrc }}"
state: absent
when: check_file_name.stat.exists
`
execution
- output file does not exist:
``bash
$ ansible-playbook -i Playbook/inventory rename/file.yml
PLAY [rename file or directory] *
TASK [Gathering Facts]
ok