Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: get files list from local directory

Tags:

ansible

I use ansible 1.9.4 and I would like to get the list of files from a local directory.

In 2.0 version, there is the find module but this version is beta.

How to do this in < 2.0 ?

like image 921
Kiva Avatar asked Jan 14 '16 11:01

Kiva


People also ask

What is With_fileglob?

with_fileglob matches all files in a single directory, non-recursively, that match a pattern. It calls Python's glob library. (plus a warning about relative paths with roles).

What is Local_action in Ansible?

In an Ansible playbook, when local_action is used, Ansible will run the module work mentioned under it on the controller node. Mostly modules used with local_action are shell and command. As you can do almost all the tasks using these modules on the controller node.

What is slurp Ansible?

slurp - Slurps a file from remote nodes This module works like fetch. It is used for fetching a base64- encoded blob containing the data in a remote file. This module is also supported for Windows targets.


3 Answers

Some time ago I was building an automation that required something like that - see Ansible send file to the first met destination.

Prior to ansible 2.0 there's no way to do this without using command or shell.

If you really can't upgrade to ansible 2.0, use the command module:

vars:
  directory: /path/to/dir

tasks:

  - command: "ls {{directory}}"
    register: dir_out

  - debug: var={{item}}
    with_items: dir_out.stdout_lines
like image 138
Bernardo Vale Avatar answered Oct 01 '22 15:10

Bernardo Vale


This is an example of listing all the files with .j2 extension in the directory templates and passing them to a module.

template: src="{{ item }}" dest="generated/{{ inventory_hostname }}/{{ item | basename | replace('.j2', '')}}"
  delegate_to: 127.0.0.1
  with_fileglob: templates/*.j2
like image 34
user43731 Avatar answered Oct 01 '22 15:10

user43731


Now there is a find module you can use. Example: show folders with name starting with "ansible" and location /tmp, so /tmp/ansible*

- name: ls -d /tmp/ansible*
  find:
    paths: /tmp
    patterns: "ansible*"
    recurse: no
    file_type: directory
  register: found_directories

- debug:
    msg: "{{ [item.path] }} "
  with_items: "{{ found_directories.files }}"
like image 8
Peter De Zwart Avatar answered Oct 01 '22 13:10

Peter De Zwart