Filter list of variables by their value

Hi,
I’m trying to filter a list of variables by their values, and I want to do this without looping, so only with filters.

I have these variables:

    # flags
    foo_service_enable: true
    bar_service_enable: true
    boz_service_enable: false
    db_service_enable: false

    # group of services
    customer_services:
      - foo_service_enable
      - bar_service_enable
      - boz_service_enable
      - db_service_enable

I am looking to find the list of enabled services, so:

enabled_stuff:
  - foo_service_enable
  - bar_service_enable

I can lookup the values with:

customer_services|map('extract',vars)

but that is just a list of booleans.
How can I use that to select only the enable services?

FYI i use this demo playbook:

---
- hosts: localhost
  connection: local
  gather_facts: no

  tasks:

    - debug: var=customer_services
    - debug: var=customer_services|map('extract',vars)


  vars:
    # flags
    foo_service_enable: true
    bar_service_enable: true
    boz_service_enable: false
    db_service_enable: false

    # group of services
    customer_services:
      - foo_service_enable
      - bar_service_enable
      - boz_service_enable
      - db_service_enable

You could use zip filter to combine the keys and value into list of tuples and then filter and map the keys.

customer_services | zip(customer_services | map('extract', vars)) | selectattr('1') | map(attribute='0')

Although for sanity, I’d suggest to use dictionary instead.

    - ansible.builtin.debug:
        msg: "{{ customer_services | dict2items | selectattr('value') | map(attribute='key') }}"
      vars:
        customer_services:
          foo_service_enable: true
          bar_service_enable: true
          boz_service_enable: false
          db_service_enable: false

If you really need the variables to be top-level, you could proxy the values:

      customer_services:
        foo_service_enable: "{{ foo_service_enable }}"
        bar_service_enable: "{{ bar_service_enable }}"
        boz_service_enable: "{{ boz_service_enable }}"
        db_service_enable: "{{ db_service_enable }}"
2 Likes