1

I'm looking for a way to sync files between 2 hosts in ansible. The scenario is as follows. I have a CSV file which contains 3 columns indicating directories which needs to be synced between 2 servers. the first 2 columns indicate the source and target servers and the third column indicates the directory

source, target, directory
src01, tgt02, dir0003
src02, tgt05, dir0004
src10, tgt68, dir1022

I found this answer for syncing files between 2 hosts - How to copy files between two nodes using ansible

Is there any way to parameterize this using a csv config file?

Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63

1 Answers1

0

Yes. It's possible. In the first play read the CSV file and create group of targets. Use the new group in the second play and loop the synchronize module. For example the playbook

- hosts: localhost
  tasks:
    - read_csv:
        path: db.csv
      register: my_db
    - add_host:
        hostname: "{{ item.target }}"
        groups: my_targets
        my_list: "{{ my_db.list }}"
      loop: "{{ my_db.list }}"

- hosts: my_targets
  tasks:
    - debug:
        msg: "Copy {{ item.directory }} from {{ item.source }} to {{ inventory_hostname }}"
      loop: "{{ my_list|json_query(query) }}"
      vars:
        query: "[?target == '{{ inventory_hostname }}']"

    - name: Copy
      synchronize:
        src: "{{ item.directory }}"
        dest: "{{ item.directory }}"
      delegate_to: "{{ item.source }}"
      loop: "{{ my_list|json_query(query) }}"
      vars:
        query: "[?target == '{{ inventory_hostname }}']"

(not tested)

gives

    "msg": "Copy dir0004 from src02 to tgt05"
    "msg": "Copy dir0003 from src01 to tgt02"
    "msg": "Copy dir1022 from src10 to tgt68"
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63