Use Ansible Synchronize Module to Sync Files Include Templates
Inspired by this post, I finally find the way to sync a directory include template files to remote.
Put you files in {{ role_path }}/files/
, if you need to put in another directory, please replace all the role_path
variable.
1- name: "Create temporary directory"
2 local_action: tempfile state=directory
3 register: temp_file_path
4
5- name: "Find j2 files"
6 local_action:
7 module: find
8 paths: "{{ role_path }}/files/"
9 patterns: "*.j2"
10 file_type: file
11 use_regex: no
12 recurse: yes
13 register: files_j2
14
15- name: "Find normal files"
16 local_action:
17 module: find
18 paths: "{{ role_path }}/files/"
19 excludes: "*.j2"
20 file_type: file
21 use_regex: no
22 recurse: yes
23 register: files_normal
24
25- name: "Ensure directory exists"
26 local_action:
27 module: file
28 path: "{{ item.path | replace(role_path + '/files', temp_file_path.path) | dirname }}"
29 state: directory
30 with_items:
31 - "{{ files_j2.files }}"
32 - "{{ files_normal.files }}"
33
34- name: "Copy templates files"
35 local_action:
36 module: template
37 src: "{{ item.path }}"
38 mode: "preserve"
39 dest: "{{ item.path | replace(role_path + '/files', temp_file_path.path) | regex_replace('.j2$', '') }}"
40 with_items: "{{ files_j2.files }}"
41
42- name: "Copy normal files to temp directory"
43 local_action:
44 module: template
45 src: "{{ item.path }}"
46 mode: "preserve"
47 dest: "{{ item.path | replace(role_path + '/files', temp_file_path.path) }}"
48 with_items: "{{ files_normal.files }}"
49
50- name: "Sync these to the destination"
51 synchronize:
52 src: "{{ temp_file_path.path }}/"
53 dest: "{{ config_root }}/"
54 delete: yes
55 rsync_opts:
56 - "--chown=root:root"