Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use ansible templating but rysnc to move files

I have quite a few files (Nginx configs) that are candidates for templating but I want to move them using rysnc/synchronize modules.

Is there a way to achieve this?

Right now I do this

- name: Copy configuration 
  synchronize:
   src: "{{ nginx_path }}/"
   dest: /etc/nginx/
   rsync_path: "sudo rsync"
   rsync_opts:
    - "--no-motd"
    - "--exclude=.git"
    - "--exclude=modules"
    - "--delete"
  notify:
   - Reload Nginx

The templating engine is combined with the move/copy action and therefore I can’t use it to apply the templates and keep it in the source itself and then use rsync to move it.

Edit:
Another way to rephrase this would be:

Is there a way to apply templates, and keep the applied output it in the source machine itself?

like image 983
Quintin Par Avatar asked Jul 23 '18 20:07

Quintin Par


1 Answers

Not in a single task no. However, the following playbook stub achieves what, I believe, you desire:

---

- hosts: localhost
  gather_facts: no

  tasks:

  - name: "1. Create temporary directory"
    tempfile:
      state: directory
    register: temp_file_path

  - name: "2. Template source files to temp directory"
    template:
      src: "{{ item }}"
      dest: "{{ temp_file_path.path }}/{{ item | basename | regex_replace('.j2$', '') }}"
    loop: "{{ query('fileglob', 'source/*.j2') }}"
    delegate_to: localhost

  - name: "3. Sync these to the destination"
    synchronize:
      src: "{{ temp_file_path.path }}/"
      dest: "dest"
      delete: yes

  - name: "4. Delete the temporary directory (optional)"
    file:
      path: "{{ temp_file_path.path }}"
      state: absent

Explanation:

For testing, this playbook was written to target localhost and connect using the local method, I developed it to simply look for all .j2 files in ./source/*.j2 and rsync the created files to ./dest/ on my workstation. I ran it using ansible-playbook -i localhost, playbook_name.yml --connection=local

Task 1. We are going to template out the source files to the local host first (using the delegate_to: localhost option on the template task). You can either create a specific directory to do this, or use Ansible's tempfile module to create one somewhere (typically) under /tmp.

Task 2. Use the template module to convert your jinja templates (with arbitrary filenames ending in .j2) found in "./source/" to output files written to the directory created in task 1 above.

Task 3. Use the synchronize module to rsync these to the destination server (for testing I used ./dest on the same box).

Task 4. Delete the temporary directory created in task 1 above.

like image 145
Chris Avatar answered Oct 18 '22 04:10

Chris