Home > Enterprise >  Compare two lists and create list of matches
Compare two lists and create list of matches

Time:07-06

Basically I am creating a playbook where I detect the running processes on a host, then want to check if there is a match against a defined static list in order to create a list of those.

The list of matches will be used in a later playbook.
Is there a function in Ansible to check if a value exists in a list or do I need to iterate over them with nested loop?

- name: get running procs
  win_command: powershell.exe -
  args:
    stdin: Get-Process | select name
  register: running_procs

- name: match procs 
  set_fact:     
    procs: "{{ running_procs | select('match','({{item}})') }}"     
  loop: "{{ static_procs }}" 

CodePudding user response:

Digging into this my scenario the static list wasn't matching the stdout list because of the messiness. realized I didn't need the gathered list of processes to be a list but I could run the search against a string.

I joined the get-process | name output then iterated over static list and used regex filter. If item from static list tests true I add it to the result list.

- name: get running procs
  win_command: powershell.exe -
  args:
    stdin: Get-Process | select name
  register: running_procs

- name: combine running procs
  set_fact:
    running_procs: "{{running_procs.stdout_lines | join(',')}}"


- name: Print running_procs
  ansible.builtin.debug:
    msg: running_procs is  {{ running_procs }} 
- name: Print static_procs
  loop: "{{static_procs}}"
  ansible.builtin.debug:
    msg: static_procs is {{ item }} 

- name: match procs 
  set_fact:     
    procs: "{{ procs   [proc]  }}"  
  loop: "{{static_procs}}"
  when: running_procs is regex(proc)
  vars:
    proc: "{{ item }}"
  • Related