首页 > 解决方案 > How to create list of files containing only filename in one set_fact task

问题描述

In Ansible 2.9 I am trying to create a list of files using the lookup plugin with the fileglob parameter that contains only the names of the files (not the path) and can be done in a single set_fact. My problem seems to be that I cannot figure out how to properly use regex when calling the replace method. I'm probably confusing some of the terminology there.

This is what I have so far, and once this works was going to send to split to build list.

- name: compile list of template files
  set_fact:
    list_of_files: "{{ lookup('fileglob', 'mydir/*').replace('/', '') }}"

But I cannot get any wildcard or regex I try to work. I have tried dozens of different options, that probably aren't worth repeating here.

标签: replaceansible

解决方案


This is a non-regex solution using basename filer, this would use ansible's in-built logic to filter out the file name from the full path.

- name: compile list of template files
  set_fact:
    list_of_files: "{{ lookup('fileglob', 'mydir/*').split(',')|map('basename') |list}}"

map function feeds on an iterable(in this case output of lookup and split) and applies the function inside map (in this case basename) to all the elements of the iterable.


推荐阅读