Synchronize a directory structure with Ansible

Disclaimer: this is not ideal. We should manage the whole configuration with Ansible. “Baby steps” I guess… :)
Consider this as a workaround I hope you’ll never have to resort to, but I’m sharing it just in case…

We’re migrating from some old scripts to using Ansible to handle some of our clients deploys.

One of the tasks that were handled by these bash scripts is to synchronize a directory structure, so that the application log files would always find the same directory structure on every application server.

We used rsync for that, copying only the directories:

rsync -av -f"+ */" -f"- *" /path/to/app/ $target:/path/to/app/

To translate this to Ansible we used two tasks:

---
- name: Deploy log directories
  vars:
    dir_log_path: /var/log/nginx
  hosts: webservers
  serial: 10%
  tasks:
  - name: find log directories
    find:
      paths:
      - '{{ dir_log_path }}'
      file_type: directory
    register: log_dirs
    delegate_to: ws-deploy

  - name: create log directories
    file:
      path: "{{ item.path }}"
      state: directory
      owner: "{{ item.uid }}"
      group: "{{ item.gid }}"
      mode: "{{ item.mode }}"
    with_items: "{{ log_dirs.files }}"

We record in the log_dirs variable the directories existing on ws-deploy, the server where we have the latest configuration loaded on, then we recreate the same structure using the file module in Ansible on all the other webservers.

Advertisements

How to exclude everything except a specific pattern with rsync

Just a quick tip (and reminder for me): if you want to rsync only a specific file, or pattern, and exclude everything else, the syntax is:

rsync -a --include="*/" --include="*your-pattern*" --exclude="*" /source/path/ /destination/path/

In my specific case I wanted to copy only gzipped files, and my command line was:

rsync -avP --include="*/" --include="*your-pattern*" --exclude="*" /source/path/ /destination/path/

The first --include directive allows rsync to descend into subdirectories, while the second provides the actual filename or pattern we want to access.