0

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?

krystan honour
  • 6,523
  • 3
  • 36
  • 63
  • erm no this is a legitimate question, I'll give a reason for that, this question deals with substituting a value into an expression, it is therefore not unique to my problem and a legitimate question to this site which aims to create a repository of information, so the close votes here are invalid. – krystan honour Jun 18 '18 at 14:43

1 Answers1

1

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.

krystan honour
  • 6,523
  • 3
  • 36
  • 63