Ansible | Set_fact with condition

Viewed 1869

I have the list:

val_list:
    - val: "D"
    - val: "A"
    - val: "B"
    - val: "C"

I would like to set variable true if list contain val: B without creating register variable task, for example:

- set_fact:
    containB: false

- set_fact:
    containB: true
  when: item.val=='B'
  with_items
    - "{{ val_list }}"

I would like to convert to something like that:

- set_fact: 
    containB: true if item.val=='B' | default(false)
#or containB: true if any val in val_list is 'B'
  with_items
    - "{{ val_list }}"
2 Answers
  1. extract values from the list with the map filter
  2. check that 'B' is an element of the resulting list

In a nutshell:

- hosts: localhost

  vars:
    val_list:
      - val: "D"
      - val: "A"
      - val: "B"
      - val: "C"

    list_contains_B: "{{ 'B' in (val_list | map(attribute='val')) }}"

  tasks:

    - name: Does list contain B ?
      debug:
        var: list_contains_B

Which gives:

PLAY [localhost] ***********************************************************************************************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************************************************************************************
ok: [localhost]

TASK [Does list contain B ?] ***********************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "list_contains_B": true
}

PLAY RECAP *****************************************************************************************************************************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

You can use the in operator to check if a list contains a value. For example:

- set_fact:
    list_contains_b: "{{ {'val': 'B'} in val_list }}"

As a runnable playbook:

- hosts: localhost
  vars:
    val_list:
      - val: "D"
      - val: "A"
      - val: "B"
      - val: "C"
  tasks:
    - set_fact:
        list_contains_b: "{{ {'val': 'B'} in val_list }}"

    - debug:
        var: list_contains_b
Related