Reputation: 23
I have ansible list variable
- sites:
- x.domain.com.ex
- y.domain.com.ex
- z.domain.com.ex
I need to make two variables as follows: list with the first level x y z and anther one with just the rest of domain name "domain.com.ex"
Your help is highly appreciated, thank you.
Upvotes: 2
Views: 1019
Reputation: 68394
For example, put the below declarations into the vars
hostnames: "{{ sites|map('split', '.')|
map('first')|list }}"
domains: "{{ sites|map('reverse')|
map('splitext')|
map('first')|
map('reverse')|list }}"
give (abridged)
hostnames:
- x
- y
- z
domains:
- domain.com.ex
- domain.com.ex
- domain.com.ex
Example of a complete playbook for testing
- hosts: localhost
vars:
sites:
- x.domain.com.ex
- y.domain.com.ex
- z.domain.com.ex
hostnames: "{{ sites|map('split', '.')|
map('first')|list }}"
domains: "{{ sites|map('reverse')|
map('splitext')|
map('first')|
map('reverse')|list }}"
tasks:
- debug:
var: hostnames
- debug:
var: domains
Q: "I need the second variable."
A: Use Python slices. For example, split and flatten all items
s: "{{ sites|map('split', '.')|flatten }}"
gives
s:
- x
- domain
- com
- ex
- y
- domain
- com
- ex
- z
- domain
- com
- ex
Then, select second variable with the step of 4
sites_1: "{{ s[1::4] }}"
gives
sites_1:
- domain
- domain
- domain
This way you can create any combination you want. For example,
sites_domns: "{{ s[1::4]|zip(s[2::4])|zip(s[3::4])|
map('flatten')|map('join', '.')|list }}"
gives
sites_domns:
- domain.com.ex
- domain.com.ex
- domain.com.ex
Upvotes: 2