0

I would like to write a loop for this Use Case:

I have an Ansible templates directory and inside this directory files with extension .j2, for example I have like this files.

data-service01.service.j2
data-relation.service.j2
data-query.service.j2
data-analysis.service.j2

So I want to write a task in Ansible to loop in templates directory to transfer files inside the templates to the destination by writing src: data-* it can loop to all files start with data- to transfer to directory.

Can I do this because I using the normal way

 src: data-service01.service.j2
 dest: data-service01.service

But I want to looping inside templates directory by

 src: data-*.j2 

How I can do this with loop?

U880D
  • 8,601
  • 6
  • 24
  • 40

1 Answers1

0

According fileglob lookup – list files matching a pattern

Matching is against local system files on the Ansible controller.

you may have a look into the following minimal example

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Template out each file that matches the given pattern
    ansible.builtin.template:
      src: "{{ item }}"
      dest: "/tmp/{{ item.split('.') | first | basename }}.service"
    with_fileglob:
      - "templates/data-*.j2"

which

resulting into an output of

TASK [Template out each file that matches the given pattern] ****************
changed: [localhost] => (item=/home/user/test/templates/data-relation.service.j2)
changed: [localhost] => (item=/home/user/test/templates/data-service01.service.j2)
changed: [localhost] => (item=/home/user/test/templates/data-query.service.j2)
changed: [localhost] => (item=/home/user/test/templates/data-analysis.service.j2)

and finally the requested files.

~/test$ ls /tmp/data-*
/tmp/data-analysis.service  /tmp/data-query.service  /tmp/data-relation.service  /tmp/data-service01.service

Further Q&A and Documentation

U880D
  • 8,601
  • 6
  • 24
  • 40