Filter list of variables by their value

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