List comparison and retireval of items on match

21 views
Skip to first unread message

Akshay Kumar

unread,
Jan 12, 2021, 5:35:42 AM1/12/21
to Ansible Project
Hi All,

Good day to all.

I am currently working on a scenario where i need to compare two lists and print out the items which match on both lists .

List1 :  ['dba','admin','developer']
List2 :  [' user1: dba admin' , 'user2 : dba developer', 'user3 : operator']

So as per my scenario in comparing above two list sets , the output should be 
user1
user2
as both users have dba/admin/developer item in there strings of list 1.

i tried below code but it doesnt seem to give me the output i need: 

- name: checking
    debug:
      msg: "item"
    with_nested:
      - "{{ VlclNewList }}"
      - "{{ VlclOldList }}"
    when: "(item[1] | difference(item[0]))"


Any help is highly appreciated.
Thanks.

Vladimir Botka

unread,
Jan 12, 2021, 6:40:49 AM1/12/21
to Akshay Kumar, ansible...@googlegroups.com
On Tue, 12 Jan 2021 02:35:42 -0800 (PST)
Akshay Kumar <aksha...@gmail.com> wrote:

> List1 : ['dba','admin','developer']
> List2 : [' user1: dba admin' , 'user2 : dba developer', 'user3 : operator']
>
> ... comparing above two list sets , the output should be
> user1
> user2
> as both users have dba/admin/developer item in there strings of list 1.

Try

- set_fact:
List3: "{{ List2|
select('search', my_regex1)|
map('regex_replace', my_regex2, my_replace)|
map('trim')|
list }}"
vars:
my_regex1: '{{ List1|join("|") }}'
my_regex2: '^(.*):(.*)$'
my_replace: '\1'

--
Vladimir Botka

Vladimir Botka

unread,
Jan 12, 2021, 1:12:50 PM1/12/21
to Akshay Kumar, ansible...@googlegroups.com
On Tue, 12 Jan 2021 16:03:14 +0100
Akshay Kumar <aksha...@gmail.com> wrote:

> List1: ['dba','admin','developer']
> List2: [' user1: dba admin' ,
> 'user2 : dba developer',
> 'user3 : operator',
> 'testdbauser: root']
>
> ... i can still get testdbauser in the output of List3

Try

- set_fact:
List3: "{{ List3|default([]) + [key|trim] }}"
loop: "{{ List2 }}"
vars:
key: "{{ item.split(':').0 }}"
val: "{{ item.split(':').1.split() }}"
when: val|intersect(List1)

--
Vladimir Botka
Reply all
Reply to author
Forward
0 new messages