Search code examples
ansibleansible-2.xansible-template

Ansible: How to copy file from `files` directory to `templates` directory in a role directory?


I want to write an Ansible task to copy file from files directory to templates directory.

For example, I have an Ansible role named data and inside this role's directory

~/data$ tree
.
├── defaults
├── tasks
├── templates
└── files
    └── application.j2

So I have a file inside the files directory named application.j2

I want to copy this file application.j2 into the templates directory using an Ansible task.

I've tried to use the below task in the src: path I use files/application.j2 but I don't know what I should write in dest: path.

- name: Transfer File.
   copy:
    src: "{{ item }}"
    dest: 
  with_fileglob:
    - "files/application.j2"

Ansible: How to copy file from files directory to templates directory in a role directory?


Solution

  • Let's assume one like to

    • Copy files with patterns between different folders
    • Let the task run on the Ansible Control Node only

    A minimal example playbook

    ---
    - hosts: localhost 
      become: false
      gather_facts: false
    
      tasks:
    
      - name: Copy each file that matches the given pattern
        copy:
          src: "{{ item }}"
          dest: "templates/{{ item.split('.') | first | basename }}.j2"
        with_fileglob:
          - "files/app*.j2"
    

    will result into the requested output.

    Similar Q&A

    For a more detailed explanation see the answer under