- name: Install postgres packages apt: name: - python3-psycopg2 - postgresql-{{ postgres_version }} - postgresql-contrib-{{ postgres_version }} - libpq-dev state: present tags: - role::postgres - name: Check postgres is started and enabled on boot service: name: '{{ postgres_daemon }}' state: started enabled: true tags: - role::postgres - name: Add postgres users become: true become_user: "{{ postgres_user }}" community.postgresql.postgresql_user: name: "{{ item.name }}" password: "{{ item.password }}" state: present loop_control: label: "{{ item.name }}" loop: "{{ postgres_users }}" environment: PGOPTIONS: "-c password_encryption=scram-sha-256" tags: - role::postgres - name: Add postgres databases become: true become_user: "{{ postgres_user }}" community.postgresql.postgresql_db: name: "{{ item.name }}" owner: "{{ item.owner }}" state: present loop: "{{ postgres_databases }}" tags: - role::postgres - name: Set host based authentication rules for all postgres users at once ansible.builtin.blockinfile: path: /etc/postgresql/{{ postgres_version }}/main/pg_hba.conf insertafter: "# Put your actual configuration here" marker: "# {mark} ANSIBLE MANAGED HBA CONF BLOCK" block: | {% for db in postgres_databases %} host {{ db.name }} {{ db.owner }} all scram-sha-256 {% endfor %} loop: "{{ postgres_databases }}" notify: - Reload the postgres service tags: - role::postgres