- hosts: postgre
  gather_facts: no
  vars:
    ansible_python_interpreter: /opt/py3/bin/python
    check_ssl: "{{ jms_asset.spec_info.use_ssl }}"
    ca_cert: "{{ jms_asset.secret_info.ca_cert | default('') }}"
    ssl_cert: "{{ jms_asset.secret_info.client_cert | default('') }}"
    ssl_key: "{{ jms_asset.secret_info.client_key | default('') }}"

  tasks:
    - name: Test PostgreSQL connection
      community.postgresql.postgresql_ping:
        login_user: "{{ jms_account.username }}"
        login_password: "{{ jms_account.secret }}"
        login_host: "{{ jms_asset.address }}"
        login_port: "{{ jms_asset.port }}"
        login_db: "{{ jms_asset.spec_info.db_name }}"
        ca_cert: "{{ ca_cert if check_ssl and ca_cert | length > 0 else omit }}"
        ssl_cert: "{{ ssl_cert if check_ssl and ssl_cert | length > 0 else omit }}"
        ssl_key: "{{ ssl_key if check_ssl and ssl_key | length > 0 else omit }}"
        ssl_mode: "{{ jms_asset.spec_info.pg_ssl_mode }}"
      register: result
      failed_when: not result.is_available

    - name: Display PostgreSQL version
      debug:
        var: result.server_version.full
      when: result is succeeded

    - name: Change PostgreSQL password
      community.postgresql.postgresql_user:
        login_user: "{{ jms_account.username }}"
        login_password: "{{ jms_account.secret }}"
        login_host: "{{ jms_asset.address }}"
        login_port: "{{ jms_asset.port }}"
        db: "{{ jms_asset.spec_info.db_name }}"
        name: "{{ account.username }}"
        password: "{{ account.secret }}"
        ca_cert: "{{ ca_cert if check_ssl and ca_cert | length > 0 else omit }}"
        ssl_cert: "{{ ssl_cert if check_ssl and ssl_cert | length > 0 else omit }}"
        ssl_key: "{{ ssl_key if check_ssl and ssl_key | length > 0 else omit }}"
        ssl_mode: "{{ jms_asset.spec_info.pg_ssl_mode }}"
        role_attr_flags: LOGIN
      ignore_errors: true
      when: result is succeeded

    - name: Verify password
      community.postgresql.postgresql_ping:
        login_user: "{{ account.username }}"
        login_password: "{{ account.secret }}"
        login_host: "{{ jms_asset.address }}"
        login_port: "{{ jms_asset.port }}"
        db: "{{ jms_asset.spec_info.db_name }}"
        ca_cert: "{{ ca_cert if check_ssl and ca_cert | length > 0 else omit }}"
        ssl_cert: "{{ ssl_cert if check_ssl and ssl_cert | length > 0 else omit }}"
        ssl_key: "{{ ssl_key if check_ssl and ssl_key | length > 0 else omit }}"
        ssl_mode: "{{ jms_asset.spec_info.pg_ssl_mode }}"
