templatesnetwork-programmingcopyansible

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?


Solution

  • Not in a single task.

    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
        delegate_to: localhost
    
      - 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
        delegate_to: localhost
    

    Explanation:

    This playbook was written to target localhost and connect using the local method.
    I developed it to look for all .j2 files in ./source/*.j2 and rsync, and the created files to ./dest/ on my workstation.

    I ran it using ansible-playbook -i localhost, playbook_name.yml --connection=local

    Task 1. 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 (.j2) from "./source/" tothe directory created in task 1.

    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.