Bruce
Bruce

Reputation: 1380

Iterate over unique list created from string split

I have a list of domains:

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

I have tasks, where I need to iterate over these domains, extract domain tail, make an unique list of these tails and then create directories named by these tails.

Something like this but AFAIK jinja2 doesn't support list comprehension:

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

Is it possible or do I need to create a custom jinja2 filter? Will this work?

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

Thanks!

Upvotes: 1

Views: 2030

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68269

You can achieve this with map and regex_search:

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

\w+$ match the last word (i.e. domain tail after dot).
Note that the slash is escaped, because it is inside double quotes.

Upvotes: 2

Related Questions