Try this:
---
- hosts: pg_servers
vars:
path: postgresql.conf
splibs_regex: "^#?(shared_preload_libraries\\s+=\\s+')([^']*)('.*$)"
extra_splibs:
- pg_stat_statements
tasks:
- name: read file
ansible.builtin.slurp:
src: "{{ path }}"
register: pgconf
- ansible.builtin.set_fact:
matches: "{{ pgconf.content | b64decode | regex_search(splibs_regex, '\\1', '\\2', '\\3', multiline=True) }}"
- ansible.builtin.lineinfile:
path: "{{ path }}"
regexp: "{{ splibs_regex }}"
line: "{{ matches[0] ~ matches[1] | split(',') | reject('equalto', '') | union(extra_splibs) | join(',') ~ matches[2] }}"
when: matches