Ansible – How to Check for a List of Items

ansible

I have a list of strings that I expect in some command's output. How can I create an ansible script that tests and – in case one or several of the entries is not contained – executes a task?

So my ansible script might look like:

vars:
  musthave:
    - value1
    - value2
tasks:
- name: Check the configured values
  command: "cat configfile"
  register: current_configuration
  changed_when: false

- set a variable if one or more of the musthave's are missing in current_configuration.stdout
  ...

- name: Execute task to reconfigure system
  command: "reconfigure..."
  when: true = variable

So is there something like

variable = false
for s in musthave:
    if not s in current_configuration.stdout:
        variable |= true

Best Answer

While it may be easier to resolve using the suggested community module I preferred a solution that does not imply more libraries to be installed. Here is the solution I came up with.

My original request was looking to check for existence of specific values that may appear somewhere in the command's output. Preparing a list for difference to work is a disadvantage, the side effect is that you can calculate the difference in both directions.

So now I can not only check for missing entries but also for those that are too much.

- name: print hostvars
  debug:
    var: hostvars[{{ ansible_host }}]['certificate_domains']

- name: print certificate
  delegate_to: silver.fritz.box
  command: "openssl x509 -in /home/hiran/homeserver.crt -noout -text"
  register: certificate

- name: grab subject's common name and alternative names
  set_fact:
    commonName: "{{ certificate.stdout | regex_search('Subject.*CN\\s=\\s([\\.a-zA-Z]+)', '\\1') }}"
    altNames: "{{ certificate.stdout | regex_findall('DNS:([\\.a-zA-Z]+)') }}"
- name: prepare the lists so they can be subtracted from each other
  set_fact:
    contained: "{{ (commonName + altNames) | unique }}"
    musthave: "{{ hostvars[{{ ansible_host }}]['certificate_domains'] | unique }}"
- name: calculate differences
  set_fact:
    missing: "{{ musthave | difference(contained) }}"
    toomuch: "{{ contained | difference(musthave) }}"

- name: show difference
  debug:
    msg: Something is wrong
  when: (missing | length)>0 or (toomuch | length)>0