迭代从字符串拆分创建的唯一列表

Iterate over unique list created from string split

我有一个域列表:

---
domains:
 - foo.bar
 - baz.bar

我有一些任务需要遍历这些域,提取域尾部,制作这些尾部的唯一列表,然后创建由这些尾部命名的目录。

类似这样,但 AFAIK jinja2 不支持列表理解:

---
- name: Ensure all directories exist
  file:
    path: "/tmp/sandbox/{{ item }}"
    state: directory
  with_items: "[domain.split('.')[-1] for domain in domains] | unique"

是否可以或我需要创建一个自定义的 jinja2 过滤器?这行得通吗?

---
- name: Ensure all directories exist
  file:
    path: "/tmp/sandbox/{{ item }}"
    state: directory
  with_items: "{{ domain_tails | my_custom_filter }}"

谢谢!

您可以使用 mapregex_search 实现此目的:

- debug: msg="Ensure dir for {{ item }}"
  with_items: "{{ domains | map('regex_search','\w+$') | list | unique }}"

\w+$ 匹配最后一个词(即域尾在点之后)。
请注意,斜线被转义了,因为它在双引号内。