summaryrefslogtreecommitdiff
path: root/tasks/copy-rendered-templates-recursive.yml
blob: 2b83834897135e5f995d8c3abc31c7b2ecd5b4f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
---

- name: Create temporary directory on localhost
  delegate_to: localhost
  become: false
  ansible.builtin.tempfile:
    state: directory
  register: tempdir

- name: Ensure parent directories exist for all files
  delegate_to: localhost
  become: false
  ansible.builtin.file:
    path: "{{ tempdir.path }}/{{ item.path | dirname }}"
    state: directory
    mode: "{{ mode | default('0755') }}"
  with_filetree: "{{ render_dir }}"
  when: item.state == "file"

- name: Check if each file is text or binary
  delegate_to: localhost
  become: false
  ansible.builtin.command:
    cmd: file --mime-type "{{ item.src }}"
  register: file_type_check
  changed_when: false
  with_filetree: "{{ render_dir }}"
  when: item.state == "file"
  loop_control:
    label: "{{ item.path }}"

- name: Separate text and binary files
  set_fact:
    text_files: >-
      {{
        file_type_check.results
        | selectattr('stdout', 'defined')
        | selectattr('stdout', 'search', '^.*: text/')
        | map(attribute='item')
        | list
      }}
    binary_files: >-
      {{
        file_type_check.results
        | selectattr('stdout', 'defined')
        | rejectattr('stdout', 'search', '^.*: text/')
        | map(attribute='item')
        | list
      }}

- name: Render templates (text files only)
  delegate_to: localhost
  become: false
  ansible.builtin.template:
    src: "{{ item.src }}"
    dest: "{{ tempdir.path }}/{{ item.path }}"
    mode: "{{ mode | default('0755') }}"
  loop: "{{ text_files }}"

- name: Copy binary files directly
  delegate_to: localhost
  become: false
  ansible.builtin.copy:
    src: "{{ item.src }}"
    dest: "{{ tempdir.path }}/{{ item.path }}"
    mode: "{{ mode | default('0644') }}"
  loop: "{{ binary_files }}"

- name: Sync rendered and copied files to remote host
  delegate_to: localhost
  become: false
  ansible.builtin.synchronize:
    src: "{{ tempdir.path }}/"
    dest: "{{ tempdir.path }}/"
    recursive: true

- name: Ensure destination exists
  ansible.builtin.file:
    path: "{{ destination_dir }}"
    state: directory

- name: Copy files to final destination
  ansible.builtin.command:
    cmd: bash -c 'cp -r {{ tempdir.path }}/* {{ destination_dir }}/'

- name: Remove local temporary directory
  delegate_to: localhost
  become: false
  ansible.builtin.file:
    path: "{{ tempdir.path }}"
    state: absent

- name: Remove remote temporary directory
  ansible.builtin.file:
    path: "{{ tempdir.path }}"
    state: absent