Ansible 中以 j2 结尾的文件的过滤器列表

Filter list in Ansible for files ending with j2

我正在尝试过滤列表,但收效甚微。

该列表是硬编码的 (all_files),以锚点“^”开头的过滤效果很好。

但我真正需要的是识别所有 *.j2 文件

我的 Ansible 版本是 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 }}"
    

有什么想法吗?我只需要一个 jinja2 文件列表(可以为空)

谢谢!

您的问题是您使用 match 而不是 search 来查找字符串末尾的模式。来自文档:

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.

所以你想要:

- 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

如果您修改搜索模式,您可以交替使用 match

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