robbles
robbles

Reputation: 2809

Pass a file glob to an Ansible role

I'm trying to pass a list of file paths to a role, so that it can process them using with_items. The use case is having a generic role (logstash) that can be given a set of configuration files, which it'll place in the right directory on the host.

Role use (ideally)

- hosts: logstash
    roles:
      - role: logstash
        logstash_conf_files:
          - ../analytics/logstash/*.conf

Task in role

- name: Create Logstash configuration files.
  template:
    src: "{{ item }}"
    dest: "/etc/logstash/conf.d/{{ item | basename }}"
  with_items: logstash_conf_files
  notify: restart logstash

I know that I can explicitly list out the filenames in a list for logstash_conf_files, but I'd rather have it pick them up automatically from a set of directories. It'll also work if the configuration files are located inside the role, but this would make the role non-reusable.

What's the recommended way to achieve this?

EDIT: @tedder42's solution works if I use a directory relative to roles/logstash/files/:

- hosts: logstash
    roles:
      - role: logstash
        logstash_conf_files: ../../../../analytics/logstash/*.conf

In role task:

- name: Create Logstash configuration files.
  template:
    src: "{{ item }}"
    dest: "/etc/logstash/conf.d/{{ item | basename }}"
  with_fileglob: logstash_conf_files

Upvotes: 0

Views: 2679

Answers (1)

300D7309EF17
300D7309EF17

Reputation: 24653

Here's a fully working example.

configuration

cat glob.yml # (playbook)
---
- name: glob
  connection: local
  hosts: localhost
  roles:
    - { role: ls, list_dir: "/etc/*" }

cat roles/ls/tasks/main.yml
---
- name: list files
  command: ls {{item}}
  with_fileglob: list_dir

execution

$ ansible-playbook -i hosts.ini glob.yml

PLAY [glob] ******************************************************************* 

GATHERING FACTS *************************************************************** 
ok: [127.0.0.1]

TASK: [ls | list files] ******************************************************* 
changed: [127.0.0.1] => (item=/etc/afpovertcp.cfg)
changed: [127.0.0.1] => (item=/etc/aliases)
changed: [127.0.0.1] => (item=/etc/aliases.db)
changed: [127.0.0.1] => (item=/etc/asl.conf)
[...]

Upvotes: 2

Related Questions