'There is 1 other session using the database AWS RDS postgressql using Ansible

When I try to remove the postgressql database using ansible module "postgresql_db" I am getting below error

FAILED! => {"changed": false, "msg": "Database query failed: database "ansible" is being accessed by other users\nDETAIL: There is 1 other session using the database.\n"}

I used rescue and until, Nothing works..

- name: Remove the DB ansible
  postgresql_db:
    login_host: "{{ db_endpoint }}"
    login_user: ansible
    login_password: "{{ pg_passd }}"
    name: ansible
    state: absent
  register: db
  until: db.changed == "true" ### I just tried this one, even with delay and retry

Any input will be much appreciated!!!!

I also tried with postgresql_query module -

- name: Remove the DB ansible
  postgresql_query:
     login_host: "{{ db_endpoint }}"
     login_user: ansible
     login_password: "{{ pg_passd }}"
     query: "{{ item }}"
  loop:
    - SELECT * FROM pg_stat_activity WHERE datname = 'ansible'
    - SELECT pg_terminate_backend (pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'ansible'
    - set AUTOCOMMIT on
    - DROP DATABASE ansible

Error is same as i tried manually mentioned below

Manually tried result is below

psql --host=db-host --username=ansible

ansible=> SELECT pg_terminate_backend (pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'ansible';
FATAL:  terminating connection due to administrator command
SSL connection has been closed unexpectedly
The connection to the server was lost. Attempting reset: Succeeded.
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
ansible=> DROP DATABASE ansible;
ERROR:  cannot drop the currently open database




Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source