Verifying Successful File Transfer
After using the copy
module to transfer files, it's important to verify that the file transfer was successful. Ansible provides several ways to ensure the integrity and correctness of the copied files.
Checking the File Existence
The simplest way to verify a successful file transfer is to check if the target file exists on the remote host. You can use the stat
module in Ansible to retrieve information about the remote file, including its existence.
- hosts: all
tasks:
- name: Copy file to remote host
copy:
src: /path/to/local/file.txt
dest: /path/to/remote/file.txt
- name: Verify file existence
stat:
path: /path/to/remote/file.txt
register: remote_file
- debug:
msg: "File transfer successful"
when: remote_file.stat.exists
In this example, the stat
module is used to check if the remote file exists. If the stat.exists
property is true
, the file transfer is considered successful.
Comparing File Checksums
To ensure the integrity of the copied file, you can compare the checksum of the local file with the checksum of the remote file. This helps verify that the file was transferred without any corruption.
- hosts: all
tasks:
- name: Copy file to remote host
copy:
src: /path/to/local/file.txt
dest: /path/to/remote/file.txt
- name: Get local file checksum
stat:
path: /path/to/local/file.txt
register: local_file
- name: Get remote file checksum
stat:
path: /path/to/remote/file.txt
register: remote_file
- debug:
msg: "File transfer successful"
when: local_file.stat.checksum == remote_file.stat.checksum
In this example, the stat
module is used to retrieve the checksum of both the local and remote files. If the checksums match, the file transfer is considered successful.
By verifying the existence and integrity of the copied files, you can ensure that the file transfer process was completed successfully and that the remote systems have the correct files.