I'm trying to automate my deployment process using Ansible and need to move a local configuration folder containing multiple subdirectories and files to my remote web servers. I initially tried the copy module, but I'm struggling with preserving the directory structure and setting the correct permissions for all nested items. Is copy the right choice for recursive transfers, or should I be looking at the synchronize module? Also, how can I ensure that files already present on the remote are updated only if they've changed locally?
3 answers
For recursive copying in Ansible, the copy module is actually quite capable. If you specify a directory as the src and ensure the path does not end with a trailing slash, Ansible will copy the directory itself and all its contents to the dest. However, for large directories, the synchronize module is much more efficient as it acts as a wrapper around rsync. This significantly reduces transfer time by only sending the deltas of changed files. When using synchronize, remember that it requires rsync to be installed on both the control node and the managed host. Also, pay close attention to the owner and group parameters to maintain your security baseline on the destination.
Have you considered how you want to handle existing files on the remote side that aren't in your source folder? Do you need to delete those "orphaned" files to keep the environments perfectly synced?
The simplest way is using the copy module. Just point src: to your local folder and dest: to the remote path. Ansible handles the recursion automatically for you.
I agree with Jennifer. For small sets of config files, copy is easier because it doesn't require the rsync dependency, making it more portable across different Linux distributions
Steven, that is a vital distinction! If Thomas uses the synchronize module, he can set the delete: yes parameter to ensure the remote directory is a mirror image of the source. This is common in CI/CD pipelines to prevent old, unused config files from causing "configuration drift." However, he should be extremely careful—if the source path is wrong, he could accidentally wipe out important data on the production server. I always recommend running a --check (dry run) first to see exactly what files would be deleted before committing to the task.