As an example I have an ansible playbook that looks like this:
---
- hosts: localhost
vars:
filename: "me-0.0.1"
tasks:
- name: get filenames
find:
paths: /home/vagrant/test
patterns: 'me\-[\d]\.[\d]\.[\d]\.jar'
use_regex: yes
register: fn
- name: remove old files
file:
path: "{{ item }}"
state: absent
with_items:
"{{ (fn.files | sort(attribute='ctime')) | map(attribute='path') | reject('search', 'me-0.0.1') | list }}"
The object here is to get the value stored in the filename variable into the expression in with items replacing the hardcoded me-0.0.1
but I am not sure how to go about that.
So the question here is how do I substitute an Ansible variable into an expression so that the filter is dynamic?
To answer my own question the answer is this:
{{ (fn.files | sort(attribute='ctime')) | map(attribute='path') | reject('search', (filename)) | list }}"
Meaning you drop the literal quotes and include the externally registered variable in brackets, I hope this helps others also.