Extract file names without extension – Ansible

Question:

I have a variable file in ansible like below

while iterating it in tasks i am using {{item}}

with_items:
- "{{check}}"
,

Is there a way to extract the filenames without extension while iterating? i.e i need file1 from file1.tar.gz and file2 from file2.tar.gz

Answer:

Ansible has as splitext filter but unfortunately it only splits the extension after the last dot.

The only solution to reliably achieve your requirement IMO is to extract the characters before the first dot using either the split() python method available on string objects or the regex_replace filter

The regexp solution is a bit of an overkill for your current requirement. Meanwhile it is very flexible as you can easily adapt it to more complex situations (matching a semantic version in the name, look for a particular pattern). Moreover, since it is a filter (vs a python native method for .split()), you can either use it:

  • while you loop, applying the filter on each item
  • before you loop applying it to the entire list with the map filter.

Here is an example for each solution in the below playbook:

Here is the result.

Note: for my own knowledge, I used the profile_task callback plugin when running the playbook. You will see that on this small list of files, each method has an equivalent performance

Leave a Reply