ansiblejinja2ansible-tower

Filter list in Ansible for files ending with j2


I am trying to filter a list but have only limited success.

The list is hardcoded (all_files) and filtering starting with anchor '^' works just fine.

But what I really need is identify all *.j2 files

My Ansible version is 2.9.25

- name: Execute any command on localhost
  hosts: localhost
  gather_facts: false
  tasks:
    - set_fact:   
        all_files: [
            "ansible_vars/dev-deploy-vars.yml",
            "Precompiled/Application/config.js.j2",
            "Precompiled/Application/web.config.j2"
        ]

    - set_fact:
        files_starting_with_pattern: "{{ j2_files | select('match', '^Precompiled') | list }}"
        files_ending_with_pattern: "{{ j2_files | select('match', 'j2$') | list }}"
    

Any idea? All I need is a list of jinja2 files (which can be empty)

Thanks!


Solution

  • Your problem is that you're using match instead of search to look for a pattern at the end of the string. From the documentation:

    match succeeds if it finds the pattern at the beginning of the string, while search succeeds if it finds the pattern anywhere within string. By default, regex works like search, but regex can be configured to perform other tests as well, by passing the match_type keyword argument. In particular, match_type determines the re method that gets used to perform the search. The full list can be found in the relevant Python documentation here.

    So you want:

    - name: Execute any command on localhost
      hosts: localhost
      gather_facts: false
      vars:
        all_files:
          - ansible_vars/dev-deploy-vars.yml
          - Precompiled/Application/config.js.j2
          - Precompiled/Application/web.config.j2
      tasks:
        - set_fact:
            files_starting_with_pattern: >-
              {{ all_files | select("match", "^Precompiled") | list }}
            files_ending_with_pattern: >-
              {{ all_files | select("search", "j2$") | list }}
    
        - debug:
            var: files_starting_with_pattern
    
        - debug:
            var: files_ending_with_pattern
    

    You could alternately use match if you modify your search pattern:

        - set_fact:
            files_starting_with_pattern: >-
              {{ all_files | select("match", "^Precompiled") | list }}
            files_ending_with_pattern: >-
              {{ all_files | select("match", ".*j2$") | list }}