]> git.immae.eu Git - github/fretlink/ansible-postgresql-role.git/commitdiff
Initial commit open sourcing Postgresql Ansible role 1.0.0
authorPaul B <paul.bonaud@capitainetrain.com>
Fri, 31 Aug 2018 09:49:09 +0000 (11:49 +0200)
committerPaul B <paul.bonaud@capitainetrain.com>
Fri, 31 Aug 2018 10:00:24 +0000 (12:00 +0200)
31 files changed:
.travis.yml [new file with mode: 0644]
LICENSE [new file with mode: 0644]
README.md [new file with mode: 0644]
defaults/main.yml [new file with mode: 0644]
meta/main.yml [new file with mode: 0644]
tasks/main.yml [new file with mode: 0644]
tasks/postgres-cluster.yml [new file with mode: 0644]
tasks/postgres-common-postinstall.yml [new file with mode: 0644]
tasks/postgres-common-preinstall.yml [new file with mode: 0644]
tasks/postgres-data-directory.yml [new file with mode: 0644]
tasks/postgres-database.yml [new file with mode: 0644]
tasks/postgres-log-directory.yml [new file with mode: 0644]
tasks/postgres-pgupgrades.yml [new file with mode: 0644]
tasks/postgres-standby-barman.yml [new file with mode: 0644]
tasks/postgres-user.yml [new file with mode: 0644]
templates/logrotate-postgresql-common.j2 [new file with mode: 0644]
templates/pgBadger.sh.j2 [new file with mode: 0644]
templates/pg_hba.conf.j2 [new file with mode: 0644]
templates/pg_upgrade.sh.j2 [new file with mode: 0755]
templates/postgresql.10.conf.j2 [new file with mode: 0644]
templates/postgresql.9.1.conf.j2 [new file with mode: 0644]
templates/postgresql.9.4.conf.j2 [new file with mode: 0644]
templates/postgresql.9.5.conf.j2 [new file with mode: 0644]
templates/postgresql.9.6.conf.j2 [new file with mode: 0644]
templates/recovery.conf.j2 [new file with mode: 0644]
templates/standby-clone.sh.j2 [new file with mode: 0755]
test/hosts [new file with mode: 0644]
test/main.yml [new file with mode: 0644]
test/requirements.txt [new file with mode: 0644]
test/requirements.yml [new file with mode: 0644]
test/roles/postgresql [new symlink]

diff --git a/.travis.yml b/.travis.yml
new file mode 100644 (file)
index 0000000..1ffbc33
--- /dev/null
@@ -0,0 +1,25 @@
+---
+language: python
+python: "3.5"
+
+# Use the new container infrastructure
+sudo: false
+
+# Install pip
+addons:
+  apt:
+    packages:
+    - python-pip
+
+install:
+  # Install ansible
+  - pip install ansible
+  # Check ansible version
+  - ansible --version
+
+script:
+  # Basic role syntax check
+  - ansible-playbook test/main.yml -i test --syntax-check
+
+notifications:
+  webhooks: https://galaxy.ansible.com/api/v1/notifications/
diff --git a/LICENSE b/LICENSE
new file mode 100644 (file)
index 0000000..82a74ff
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright (c) 2018 Trainline SAS
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644 (file)
index 0000000..f07f2d4
--- /dev/null
+++ b/README.md
@@ -0,0 +1,103 @@
+## PostgreSQL Ansible role [![Build Status](https://travis-ci.org/trainline-eu/postgresql.svg?branch=master)](https://travis-ci.org/trainline-eu/postgresql)
+
+Ansible role which installs and configures PostgreSQL clusters, databases and users.
+
+#### Installation
+
+This role has been tested on Ansible 2.3.0 and higher.
+
+To install:
+
+```
+ansible-galaxy install trainline-eu.postgresql
+```
+
+
+#### Dependencies
+
+No dependencies
+
+Recommended dependencies:
+- trainline-eu.barman
+
+#### Compatibility matrix
+
+This table lists the tested version of OS/PostgreSQL couples.
+
+| Distribution / PostgreSQL | 9.1 | 9.4 | 9.5 | 9.6 | 10  | 11  |
+| ------------------------- |:---:|:---:|:---:|:---:|:---:|:---:|
+| Debian 8.x | :no_entry: :white_check_mark:| :white_check_mark:| :white_check_mark:| :white_check_mark:| :white_check_mark:| :grey_question:|
+| Debian 9.x | :no_entry: :white_check_mark:| :white_check_mark:| :white_check_mark:| :white_check_mark:| :white_check_mark:| :grey_question:|
+
+- :white_check_mark: - tested, works fine
+- :grey_question: - will work in the future (help out if you can)
+- :interrobang: - maybe works, not tested
+- :no_entry: - PostgreSQL has reached EOL
+
+
+#### Variables
+
+```yaml
+# Basic settings
+postgres_listen_addresses: [ '127.0.0.1' ] # Optional
+postgres_log_dir: '/home/postgres-logs'    # Optional
+postgres_data_dir: '/home/postgres'        # Optional
+postgres_clusters:                         # Mandatory
+  - version: 10                              # Mandatory
+    name: 'main'                             # Mandatory
+    port: 5432                               # Mandatory
+    checksums: True                          # Optional
+    fsync_enabled: False                     # Optional
+    archive_enabled: False                   # Optional
+    # List of users to be created (optional)
+    users:
+      - username: 'replicator'                 # Mandatory
+        password: 'SuperSecret'                # Mandatory
+        permissions: 'REPLICATION'             # Mandatory
+    # List of databases to be created (optional)
+    databases:
+      - dbname: my_database                    # Mandatory
+        owner: john                            # Mandatory
+
+# Postgres config (Optional)
+postgres_log_line_prefix: '%m [%p] database: %d host: %h user: %u '
+postgres_datestyle: 'iso, dmy'
+postgres_locale_formats: fr_FR.UTF-8
+postgres_text_search_config: pg_catalog.french
+
+# Postgres pg_hba config (optional)
+postgres_allowed_hosts:
+  - user: all
+    range: 10.0.0.0/24
+postgres_replication_hosts:
+  - user: replicator
+    range: 10.0.0.0/24
+```
+
+#### Testing
+
+This project comes with a `test/main.yml` testing playbook. It uses `Docker` to provision containers locally and sets up a 3 node postgresql cluster with a barman server.
+
+Coverage of this playbook is probably not complete but at least it's there.
+
+If you are contributing, please first test your changes in a new playbook in the `test/` directory within docker containers, (using the targeted distribution), and if possible, ensure your change is covered in the tests found in [.travis.yml](./.travis.yml).
+
+#### License
+
+Licensed under the MIT License. See the [LICENSE](./LICENSE) file for details.
+
+
+#### Thanks
+
+Creators:
+- [Gaëtan Duchaussois](https://twitter.com/gduchaussois)
+- [Théophile Helleboid](https://twitter.com/chtitux)
+- [Paul Bonaud](https://twitter.com/paulRb_r)
+
+Maintainers:
+- [Théophile Helleboid](https://twitter.com/chtitux)
+- [Paul Bonaud](https://twitter.com/paulRb_r)
+
+#### Feedback, bug-reports, requests, ...
+
+Are [welcome](https://github.com/trainline-eu/postgresql/issues)!
diff --git a/defaults/main.yml b/defaults/main.yml
new file mode 100644 (file)
index 0000000..59db662
--- /dev/null
@@ -0,0 +1,18 @@
+---
+postgres_listen_addresses:
+  - '127.0.0.1'
+postgres_clusters: []
+# postgres_data_dir: ~
+# postgres_log_dir: ~
+# postgres_pgbadger_server: ~
+postgres_backup_enabled: false
+#------------------------------------------------------------#
+#------------ Postgresql Configuration defaults -------------#
+#- WARNING: defaults can change with major version upgrades -#
+postgres_log_line_prefix: '%m [%p] %q%u@%d '
+postgres_datestyle: 'iso, mdy'
+postgres_locale_system: C.UTF-8
+postgres_locale_formats: C.UTF-8
+postgres_text_search_config: pg_catalog.english
+#------------------------------------------------------------#
+
diff --git a/meta/main.yml b/meta/main.yml
new file mode 100644 (file)
index 0000000..e0a9f49
--- /dev/null
@@ -0,0 +1,20 @@
+
+galaxy_info:
+  author: Trainline SAS
+  description: "Install, configure and manage PostgreSQL clusters"
+  license: MIT
+
+  min_ansible_version: 2.0
+
+  platforms:
+  - name: Ubuntu
+    versions:
+      - xenial
+  - name: Debian
+    versions:
+      - jessie
+      - stretch
+
+  galaxy_tags: ['postgresql', 'cluster', 'ha', 'database', 'replication']
+
+dependencies: []
diff --git a/tasks/main.yml b/tasks/main.yml
new file mode 100644 (file)
index 0000000..ad6b5bb
--- /dev/null
@@ -0,0 +1,80 @@
+---
+- include: postgres-common-preinstall.yml
+  tags:
+    - postgres
+
+- include: postgres-log-directory.yml
+  tags:
+    - postgres
+  when:
+   - postgres_log_dir is defined and postgres_log_dir
+
+- include: postgres-data-directory.yml
+  tags:
+    - postgres
+  when: postgres_data_dir is defined and postgres_data_dir
+
+- name: fail if no clusters are defined
+  fail:
+    msg: "You probably forgot to define a PostgreSQL cluster on your host (`postgres_clusters` variable). Stopping run of the PostgreSQL role."
+  when: (postgres_clusters is not defined) or (postgres_clusters|length == 0)
+
+- include: postgres-cluster.yml
+    postgres_version={{ item.version }}
+    postgres_cluster_name={{ item.name }}
+    postgres_port={{ item.port }}
+    postgres_fsync_enabled={{ item.fsync_enabled }}
+    postgres_archive_enabled={{ item.archive_enabled }}
+    postgres_max_replication_slots={{ item.max_replication_slots | default(10) }}
+    postgres_extra_config={{ item.extra_config | default({}) }}
+    barman_directory={{ item.barman_directory | default(None) }}
+    postgres_primary={{ item.primary | default(None) }}
+    postgres_checksums={{ item.checksums | default(True) }}
+  with_items: "{{ postgres_clusters }}"
+  tags:
+    - postgres
+
+- include: postgres-common-postinstall.yml
+  tags:
+    - postgres
+
+- include: postgres-user.yml
+    postgres_username={{ item.1.username }}
+    postgres_password={{ item.1.password }}
+    postgres_port={{ item.0.port }}
+    postgres_permissions={{ item.1.permissions | default('') }}
+  with_subelements:
+    - "{{ postgres_clusters }}"
+    - users
+    - skip_missing: true
+  tags:
+    - postgres
+    - postgres-users
+
+- include: postgres-database.yml
+    postgres_dbname={{ item.1.dbname }}
+    postgres_owner={{ item.1.owner }}
+    postgres_port={{ item.0.port }}
+  with_subelements:
+    - "{{ postgres_clusters }}"
+    - databases
+    - skip_missing: true
+  tags:
+    - postgres
+    - postgres-databases
+
+- include: postgres-pgupgrades.yml
+    postgres_dbname={{ item.dbname }}
+    postgres_pgbouncer_uri={{ item.pgbouncer_uri|default(None) }}
+    postgres_old_cluster_version={{ item.old_cluster_version }}
+    postgres_old_cluster_name={{ item.old_cluster_name }}
+    postgres_new_cluster_version={{ item.new_cluster_version }}
+    postgres_new_cluster_name={{ item.new_cluster_name }}
+    postgres_standby_server={{ item.standby_server }}
+    postgres_standby_old_cluster_name={{ item.standby_old_cluster_name|default(item.old_cluster_name) }}
+    postgres_standby_new_cluster_name={{ item.standby_new_cluster_name|default(item.new_cluster_name) }}
+  with_items: "{{ postgres_pgupgrades }}"
+  when: postgres_pgupgrades is defined
+  tags:
+    - postgres
+    - postgres-pgupgrades
diff --git a/tasks/postgres-cluster.yml b/tasks/postgres-cluster.yml
new file mode 100644 (file)
index 0000000..83958d2
--- /dev/null
@@ -0,0 +1,85 @@
+- name: Install postgresql version {{ postgres_version }}
+  apt: name=postgresql-{{ postgres_version }}
+  when: ansible_distribution_release != 'NA'
+
+- name: Install pg_repack version {{ postgres_version }}
+  apt: name=postgresql-{{ postgres_version }}-repack
+  when:
+   - ansible_distribution_release != 'NA'
+   - postgres_version in ['9.3', '9.4', '9.5', '9.6', '10']
+
+- name: Set initdb options
+  set_fact: postgres_initdb_option="{% if postgres_checksums %}--data-checksums{% endif %}"
+
+- name: Create postgres cluster {{ postgres_version }}/{{ postgres_cluster_name }} if needed
+  command: /usr/bin/pg_createcluster {{ postgres_version }} {{ postgres_cluster_name }} -- {{ postgres_initdb_option }}
+  args:
+    creates: /var/lib/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/
+
+- name: Check postgres server key
+  stat: path=/var/lib/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/server.key
+  register: server_key
+
+- name: Copy snakeoil key in postgres dir
+  copy:
+    src=/etc/ssl/private/ssl-cert-snakeoil.key
+    dest=/var/lib/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/server.key
+    remote_src=true
+    owner=postgres
+    group=postgres
+    mode="0600"
+  when: not server_key.stat.exists or server_key.stat.islnk
+
+- name: Check postgres server certificate
+  stat: path=/var/lib/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/server.crt
+  register: server_crt
+
+- name: Copy snakeoil certificate in postgres dir
+  copy:
+    src=/etc/ssl/certs/ssl-cert-snakeoil.pem
+    dest=/var/lib/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/server.crt
+    remote_src=true
+    owner=postgres
+    group=postgres
+    mode="0644"
+  when: not server_crt.stat.exists or server_crt.stat.islnk
+
+- name: Add standby clone from barman script
+  include: postgres-standby-barman.yml
+  when: postgres_barman_server is defined
+
+- name: Determine SSD or rotational disks
+  raw: 'lsblk --noheadings --nodeps --raw --output=rota | grep -q 1'
+  check_mode: no
+  ignore_errors: yes
+  register: rotational_disk
+
+- name: Set specific random page cost for SSDs
+  set_fact:
+    postgres_specific_random_page_cost: "1.0"
+  when:
+    - rotational_disk.failed is defined
+    - rotational_disk.failed
+
+- name: Upload postgresql.conf
+  template: src=postgresql.{{ postgres_version }}.conf.j2 dest=/etc/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/postgresql.conf
+
+- name: Upload pg_hba.conf
+  template: src=pg_hba.conf.j2 dest=/etc/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/pg_hba.conf
+
+- name: Upload recovery.conf
+  template: src=recovery.conf.j2 dest=/var/lib/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/recovery.conf owner=postgres group=postgres mode=0600
+  when: postgres_primary
+  no_log: True
+
+- name: Create log file
+  file:
+    path={{ postgres_log_dir }}/postgresql-{{ postgres_version }}-{{ postgres_cluster_name }}.log
+    state=touch
+    owner=postgres
+    group=adm
+  when: postgres_log_dir is defined and postgres_log_dir
+
+- name: Create log symlink for pg_lsclusters
+  file: dest=/etc/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/log src={{ postgres_log_dir }}/postgresql-{{ postgres_version }}-{{ postgres_cluster_name }}.log state=link
+  when: postgres_log_dir is defined and postgres_log_dir
diff --git a/tasks/postgres-common-postinstall.yml b/tasks/postgres-common-postinstall.yml
new file mode 100644 (file)
index 0000000..277fafd
--- /dev/null
@@ -0,0 +1,46 @@
+- user: name=postgres append=yes groups=ssl-cert
+
+- name: Creates .ssh directory
+  file: path=/var/lib/postgresql/.ssh state=directory owner=postgres group=postgres mode=0700
+
+- name: Create postgres SSH key
+  command: ssh-keygen -b 4096 -f /var/lib/postgresql/.ssh/id_rsa -N "" -q
+  become: yes
+  become_user: postgres
+  become_method: su
+  args:
+    creates: /var/lib/postgresql/.ssh/id_rsa
+
+- slurp:
+    src: /var/lib/postgresql/.ssh/id_rsa.pub
+  register: db_server_pub_key
+
+- name: Allow SSH access on barman server
+  authorized_key:
+    user: "barman"
+    key: "{{ db_server_pub_key['content']|b64decode }}"
+    state: present
+  delegate_to: "{{ postgres_barman_server_public|default(postgres_barman_server) }}"
+  when: postgres_barman_server is defined
+
+- name: Copy logrotate configuration for postgresql
+  template: src=logrotate-postgresql-common.j2 dest=/etc/logrotate.d/postgresql-common owner=root group=root mode=0644
+
+- name: Create /root/scripts needed directory
+  file: path=/root/scripts/ state=directory
+
+- name: Create pgbadger user
+  user: name=pgbadger home=/home/pgbadger
+  when: postgres_pgbadger_server is defined and postgres_pgbadger_server
+
+- name: Copy pbBadger script
+  template: src=pgBadger.sh.j2 dest=/root/scripts/pgBadger.sh owner=root group=root mode=0755
+  when: postgres_pgbadger_server is defined and postgres_pgbadger_server
+
+- name: Ensure dedicated log directory is owned by postgres
+  file: path={{ postgres_log_dir }} state=directory owner=postgres group=postgres
+  when: postgres_log_dir is defined and postgres_log_dir
+
+- name: Ensure dedicated data directory is owned by postgres
+  file: path={{ postgres_data_dir }} state=directory owner=postgres group=postgres
+  when: postgres_data_dir is defined and postgres_data_dir
diff --git a/tasks/postgres-common-preinstall.yml b/tasks/postgres-common-preinstall.yml
new file mode 100644 (file)
index 0000000..32bcf58
--- /dev/null
@@ -0,0 +1,23 @@
+- name: Add Postgres repository key
+  apt_key: id=7FCC7D46ACCC4CF8 url=https://apt.postgresql.org/pub/repos/apt/ACCC4CF8.asc state=present
+  when: ansible_distribution_release != 'NA'
+
+- name: Add Postgres repository
+  apt_repository: repo="deb http://apt.postgresql.org/pub/repos/apt/ {{ ansible_distribution_release }}-pgdg main"
+  when: ansible_distribution_release != 'NA'
+
+- name: Increase shmmax sysctl paramater
+  sysctl: name="kernel.shmmax" value=586162176 sysctl_set=yes state=present reload=yes
+
+- name: Install rsync
+  apt: name=rsync
+  when: ansible_distribution_release != 'NA'
+
+- name: Install time
+  apt: name=time state=present
+
+- name: Install barman-cli
+  apt: name=barman-cli state=present
+
+- name: Install pg-activity
+  apt: name=pg-activity state=present
diff --git a/tasks/postgres-data-directory.yml b/tasks/postgres-data-directory.yml
new file mode 100644 (file)
index 0000000..02b6df8
--- /dev/null
@@ -0,0 +1,10 @@
+- name: Create dedicated data directory
+  file: path={{ postgres_data_dir }} state=directory owner=postgres group=postgres
+
+- name: Check /var/lib/postgresql directory
+  stat: path=/var/lib/postgresql/
+  register: var_lib_postgresql
+
+- name: Create a symlink between regular data directory and dedicated one
+  file: src={{ postgres_data_dir }} dest=/var/lib/postgresql state=link
+  when: not var_lib_postgresql.stat.exists
diff --git a/tasks/postgres-database.yml b/tasks/postgres-database.yml
new file mode 100644 (file)
index 0000000..c7b09a8
--- /dev/null
@@ -0,0 +1,20 @@
+- name: Test if the PostgreSQL server is up
+  become: true
+  become_user: postgres
+  become_method: su
+  command: psql --port={{ postgres_port }} --command='select NOW()'
+  register: postgres_up
+  ignore_errors: yes
+  check_mode: no
+  changed_when: false
+
+- name: Create PostgreSQL database
+  become: true
+  become_user: postgres
+  become_method: su
+  postgresql_db:
+    port:             "{{ postgres_port }}"
+    name:             "{{ postgres_dbname }}"
+    owner:            "{{ postgres_owner }}"
+  when:
+    - postgres_up.rc == 0
diff --git a/tasks/postgres-log-directory.yml b/tasks/postgres-log-directory.yml
new file mode 100644 (file)
index 0000000..df7ede0
--- /dev/null
@@ -0,0 +1,13 @@
+- name: Create dedicated log directory
+  file: path={{ postgres_log_dir }} state=directory
+
+- name: Check /var/log/postgresql
+  stat: path=/var/log/postgresql
+  register: var_log_postgresql
+
+- name: Move /var/log/postgresql directory if not a link
+  command: mv /var/log/postgresql /var/log/old-postgresql
+  when: var_log_postgresql.stat.isdir is defined and var_log_postgresql.stat.isdir
+
+- name: Create a symlink so regular log path points to dedicated log directory
+  file: src={{ postgres_log_dir }} dest=/var/log/postgresql state=link
diff --git a/tasks/postgres-pgupgrades.yml b/tasks/postgres-pgupgrades.yml
new file mode 100644 (file)
index 0000000..a0b17b4
--- /dev/null
@@ -0,0 +1,12 @@
+---
+- name: Find matching new cluster
+  set_fact:
+    postgres_new_cluster: "{{ postgres_clusters|selectattr('name','equalto',postgres_new_cluster_name)|selectattr('version','equalto',postgres_new_cluster_version|float)|list|first }}"
+
+- name: Extract database port of new matching cluster
+  set_fact:
+    postgres_new_cluster_port: "{{ (postgres_new_cluster|default({'port': 5432}))['port'] }}"
+
+- name: Upload pg_upgrade.sh script
+  template: src=pg_upgrade.sh.j2 dest=/var/lib/postgresql/pg_upgrade_{{ postgres_old_cluster_version }}_{{ postgres_new_cluster_version }}_{{ postgres_dbname }} owner=postgres group=postgres mode=0700
+  no_log: True
diff --git a/tasks/postgres-standby-barman.yml b/tasks/postgres-standby-barman.yml
new file mode 100644 (file)
index 0000000..793b942
--- /dev/null
@@ -0,0 +1,12 @@
+---
+- name: Copy secondary script
+  template: src=standby-clone.sh.j2 dest=/root/standby-clone-{{ postgres_version }}-{{ postgres_cluster_name }}.sh mode=0755
+
+- name: Copy rsync password file
+  copy:
+    content: "{{ barman_rsync_password }}"
+    dest: /var/lib/postgresql/.rsync_pass
+    owner: postgres
+    group: postgres
+    mode: 0400
+  no_log: True
diff --git a/tasks/postgres-user.yml b/tasks/postgres-user.yml
new file mode 100644 (file)
index 0000000..308dab8
--- /dev/null
@@ -0,0 +1,22 @@
+- name: Test if the PostgreSQL server is up
+  become: true
+  become_user: postgres
+  become_method: su
+  command: psql --port={{ postgres_port }} --command='select NOW()'
+  register: postgres_up
+  ignore_errors: yes
+  check_mode: no
+  changed_when: false
+
+- name: Create PostgreSQL user
+  become: true
+  become_user: postgres
+  become_method: su
+  postgresql_user:
+    port:             "{{ postgres_port }}"
+    name:             "{{ postgres_username }}"
+    password:         "{{ postgres_password }}"
+    encrypted:        true
+    role_attr_flags:  "{{ postgres_permissions }}"
+  when:
+    - postgres_up.rc == 0
diff --git a/templates/logrotate-postgresql-common.j2 b/templates/logrotate-postgresql-common.j2
new file mode 100644 (file)
index 0000000..06245b6
--- /dev/null
@@ -0,0 +1,16 @@
+{{ postgres_log_dir|default('/var/log/postgresql') }}/*.log
+{
+       daily
+       rotate 60
+       copytruncate
+       delaycompress
+       compress
+       notifempty
+       missingok
+       su root root
+{% if postgres_pgbadger_server is defined and postgres_pgbadger_server %}
+       lastaction
+          /root/scripts/pgBadger.sh
+       endscript
+{% endif -%}
+}
diff --git a/templates/pgBadger.sh.j2 b/templates/pgBadger.sh.j2
new file mode 100644 (file)
index 0000000..93a2247
--- /dev/null
@@ -0,0 +1,10 @@
+#!/bin/bash
+# {{ ansible_managed }}
+
+{% for cluster in postgres_clusters %}
+install --mode=0644 --owner=pgbadger {{ postgres_log_dir | default("/var/log/postgresql") }}/postgresql-{{ cluster.version }}-{{ cluster.name }}.log.1 ~pgbadger/
+sudo -H -u pgbadger scp ~pgbadger/postgresql-{{ cluster.version }}-{{ cluster.name }}.log.1 {{ postgres_pgbadger_server }}:postgresql-{{ ansible_nodename }}-{{ cluster.version }}-{{ cluster.name }}.log.1
+sudo -H -u pgbadger ssh {{ postgres_pgbadger_server }} ./update.sh {{ ansible_nodename }}-{{ cluster.version }}-{{ cluster.name }}
+{% else %}
+# No servers are configured for sending logs to pgbadger
+{% endfor %}
diff --git a/templates/pg_hba.conf.j2 b/templates/pg_hba.conf.j2
new file mode 100644 (file)
index 0000000..930ed2a
--- /dev/null
@@ -0,0 +1,107 @@
+# {{ ansible_managed }}
+# PostgreSQL Client Authentication Configuration File
+# ===================================================
+#
+# Refer to the "Client Authentication" section in the PostgreSQL
+# documentation for a complete description of this file.  A short
+# synopsis follows.
+#
+# This file controls: which hosts are allowed to connect, how clients
+# are authenticated, which PostgreSQL user names they can use, which
+# databases they can access.  Records take one of these forms:
+#
+# local      DATABASE  USER  METHOD  [OPTIONS]
+# host       DATABASE  USER  ADDRESS  METHOD  [OPTIONS]
+# hostssl    DATABASE  USER  ADDRESS  METHOD  [OPTIONS]
+# hostnossl  DATABASE  USER  ADDRESS  METHOD  [OPTIONS]
+#
+# (The uppercase items must be replaced by actual values.)
+#
+# The first field is the connection type: "local" is a Unix-domain
+# socket, "host" is either a plain or SSL-encrypted TCP/IP socket,
+# "hostssl" is an SSL-encrypted TCP/IP socket, and "hostnossl" is a
+# plain TCP/IP socket.
+#
+# DATABASE can be "all", "sameuser", "samerole", "replication", a
+# database name, or a comma-separated list thereof. The "all"
+# keyword does not match "replication". Access to replication
+# must be enabled in a separate record (see example below).
+#
+# USER can be "all", a user name, a group name prefixed with "+", or a
+# comma-separated list thereof.  In both the DATABASE and USER fields
+# you can also write a file name prefixed with "@" to include names
+# from a separate file.
+#
+# ADDRESS specifies the set of hosts the record matches.  It can be a
+# host name, or it is made up of an IP address and a CIDR mask that is
+# an integer (between 0 and 32 (IPv4) or 128 (IPv6) inclusive) that
+# specifies the number of significant bits in the mask.  A host name
+# that starts with a dot (.) matches a suffix of the actual host name.
+# Alternatively, you can write an IP address and netmask in separate
+# columns to specify the set of hosts.  Instead of a CIDR-address, you
+# can write "samehost" to match any of the server's own IP addresses,
+# or "samenet" to match any address in any subnet that the server is
+# directly connected to.
+#
+# METHOD can be "trust", "reject", "md5", "password", "gss", "sspi",
+# "ident", "peer", "pam", "ldap", "radius" or "cert".  Note that
+# "password" sends passwords in clear text; "md5" is preferred since
+# it sends encrypted passwords.
+#
+# OPTIONS are a set of options for the authentication in the format
+# NAME=VALUE.  The available options depend on the different
+# authentication methods -- refer to the "Client Authentication"
+# section in the documentation for a list of which options are
+# available for which authentication methods.
+#
+# Database and user names containing spaces, commas, quotes and other
+# special characters must be quoted.  Quoting one of the keywords
+# "all", "sameuser", "samerole" or "replication" makes the name lose
+# its special character, and just match a database or username with
+# that name.
+#
+# This file is read on server startup and when the postmaster receives
+# a SIGHUP signal.  If you edit the file on a running system, you have
+# to SIGHUP the postmaster for the changes to take effect.  You can
+# use "pg_ctl reload" to do that.
+
+# Put your actual configuration here
+# ----------------------------------
+#
+# If you want to allow non-local connections, you need to add more
+# "host" records.  In that case you will also need to make PostgreSQL
+# listen on a non-local interface via the listen_addresses
+# configuration parameter, or via the -i or -h command line switches.
+
+
+
+
+# DO NOT DISABLE!
+# If you change this first entry you will need to make sure that the
+# database superuser can access the database using some other method.
+# Noninteractive access to all databases is required during automatic
+# maintenance (custom daily cronjobs, replication, and similar tasks).
+#
+# Database administrative login by Unix domain socket
+local   all             postgres                                peer
+
+# TYPE  DATABASE        USER            ADDRESS                 METHOD
+
+# "local" is for Unix domain socket connections only
+local   all             all                                     peer
+# IPv4 local connections:
+host    all             all             127.0.0.1/32            md5
+{% for host in postgres_allowed_hosts %}
+host    all             {{ host.user }} {{ host.range }}        md5
+{% endfor %}
+
+# IPv6 local connections:
+host    all             all             ::1/128                 md5
+# Allow replication connections from localhost, by a user with the
+# replication privilege.
+#local   replication     postgres                                peer
+#host    replication     postgres        127.0.0.1/32            md5
+#host    replication     postgres        ::1/128                 md5
+{% for host in postgres_replication_hosts %}
+hostssl replication   {{ host.user }}    {{ host.range }}        md5
+{% endfor %}
diff --git a/templates/pg_upgrade.sh.j2 b/templates/pg_upgrade.sh.j2
new file mode 100755 (executable)
index 0000000..e4f87e1
--- /dev/null
@@ -0,0 +1,175 @@
+#!/bin/bash -ex
+# {{ ansible_managed }}
+#
+# WARNING: Please read both the documentation and this script if you want to run it
+# Authors:
+# - Théophile Helleboid
+# - Paul Bonaud
+# Description:
+#   This helper tries to strictly follow the official documentation of PostgreSQL
+#   from the pg_upgrade page: https://www.postgresql.org/docs/9.5/static/pgupgrade.html
+# Usage:
+#   WARNING: Please read both the documentation and this script if you want to run it
+#   1. edit this file and remove the "DRY_RUN=1" line
+#   2. execute this script as the postgres admin user
+
+{% if postgres_pgbouncer_uri is defined and postgres_pgbouncer_uri %}
+PGBOUNCER_PG_URI={{ postgres_pgbouncer_uri }}
+{% endif %}
+DATABASE_NAME={{ postgres_dbname }}
+DATABASE_PORT={{ postgres_new_cluster_port }}
+
+OLD_CLUSTER_VERSION={{ postgres_old_cluster_version }}
+OLD_CLUSTER_NAME={{ postgres_old_cluster_name }}
+OLD_CLUSTER_DATADIR=/var/lib/postgresql/$OLD_CLUSTER_VERSION/$OLD_CLUSTER_NAME
+NEW_CLUSTER_VERSION={{ postgres_new_cluster_version }}
+NEW_CLUSTER_NAME={{ postgres_new_cluster_name }}
+NEW_CLUSTER_DATADIR=/var/lib/postgresql/$NEW_CLUSTER_VERSION/$NEW_CLUSTER_NAME
+
+STANDBY_SERVER={{ postgres_standby_server }}
+STANDBY_OLD_CLUSTER_NAME={{ postgres_standby_old_cluster_name }}
+STANDBY_OLD_CLUSTER_DATADIR=/var/lib/postgresql/$OLD_CLUSTER_VERSION/$STANDBY_OLD_CLUSTER_NAME
+STANDBY_NEW_CLUSTER_NAME={{ postgres_standby_new_cluster_name }}
+STANDBY_NEW_CLUSTER_DATADIR=/var/lib/postgresql/$NEW_CLUSTER_VERSION/$STANDBY_NEW_CLUSTER_NAME
+
+DRY_RUN=1
+
+if [ "$(whoami)" != "postgres" ]; then
+    echo "ERROR: you must run this script as the 'postgres' admin local user"
+    exit 1
+fi
+
+{% if postgres_pgbouncer_uri is defined and postgres_pgbouncer_uri %}
+# Test the configuration is correcly deployed on pgbouncer
+psql $PGBOUNCER_PG_URI --command 'show databases;'  | grep "^ $DATABASE_NAME "
+# Test connection to pgbouncer is OK
+psql $PGBOUNCER_PG_URI --command 'show pools;'
+{% endif %}
+
+if [ ! -f /usr/lib/postgresql/$NEW_CLUSTER_VERSION/bin/pg_upgrade ]; then
+    echo "ERROR: /usr/lib/postgresql/$NEW_CLUSTER_VERSION/bin/pg_upgrade is not available on this machine."
+    exit 1
+fi
+# We need ssh access to the standby server
+ssh $STANDBY_SERVER "ls -A $STANDBY_OLD_CLUSTER_DATADIR 2>&1>/dev/null"
+ssh $STANDBY_SERVER "ls -A $STANDBY_NEW_CLUSTER_DATADIR 2>&1>/dev/null"
+if [ ! -d $OLD_CLUSTER_DATADIR ] || [ ! -d $NEW_CLUSTER_DATADIR ]; then
+    echo "ERROR: Make sure both old cluster and new cluster data dirs exists"
+    echo "ERROR: on both primary and standby servers ($STANDBY_SERVER)."
+    echo "ERROR: old_cluster datadir: $OLD_CLUSTER_DATADIR"
+    echo "ERROR: new_cluster datadir: $NEW_CLUSTER_DATADIR"
+    #exit 1
+fi
+
+echo "WARNING: You are about to:"
+{% if postgres_pgbouncer_uri is defined and postgres_pgbouncer_uri %}
+echo "WARNING: * PAUSE connections to $DATABASE_NAME database."
+{% endif %}
+echo "WARNING: * STOP the primary database in $OLD_CLUSTER_VERSION version (and standbys)"
+echo "WARNING: * dry-run the pg_upgrade from $OLD_CLUSTER_VERSION to $NEW_CLUSTER_VERSION"
+echo "WARNING: * run the pg_upgrade in place with hardlinks"
+echo "WARNING: * START the primary database in $NEW_CLUSTER_VERSION version (and standbys)"
+{% if postgres_pgbouncer_uri is defined and postgres_pgbouncer_uri %}
+echo "WARNING: * RESUME connections to $DATABASE_NAME."
+{% endif %}
+echo "================"
+read -p "Are you sure? (y/n)" -n 1 -r
+echo "================"
+if [[ -z $DRY_RUN ]] && [[ $REPLY =~ ^[Yy]$ ]]; then
+    {% if postgres_pgbouncer_uri is defined and postgres_pgbouncer_uri %}
+    # Pause the databases;
+    psql $PGBOUNCER_PG_URI --command "PAUSE $DATABASE_NAME;"
+    {% endif %}
+
+    # Stop the $OLD_CLUSTER_VERSION server
+    pg_ctlcluster $OLD_CLUSTER_VERSION $OLD_CLUSTER_NAME stop -m fast
+
+    # Get latest checkpoint location of primary
+    echo "INFO: Primary PG controldata with latest checkpoint location"
+    /usr/lib/postgresql/$OLD_CLUSTER_VERSION/bin/pg_controldata $OLD_CLUSTER_DATADIR | head -n8
+
+    # Wait for standbys to catch up latest checkpoint
+    # TODO: how long to wait?
+    echo "Waiting for 9 seconds..."
+    sleep 9
+    echo "INFO: Standby PG controldata with latest checkpoint location (after shutdown)"
+    ssh $STANDBY_SERVER pg_ctlcluster $OLD_CLUSTER_VERSION $STANDBY_OLD_CLUSTER_NAME stop -m fast
+    ssh $STANDBY_SERVER /usr/lib/postgresql/$OLD_CLUSTER_VERSION/bin/pg_controldata $STANDBY_OLD_CLUSTER_DATADIR | head -n8
+
+    echo "WARNING: 'Latest Checkpoint location' values should match on primary and on standby"
+    echo "================"
+    read -p "Do they match? PLEASE ANSWER (y/n)" -n 1 -r
+    echo "================"
+
+    if [[ $REPLY =~ ^[Yy]$ ]]; then
+        # Test to upgrade the data
+        time /usr/lib/postgresql/$NEW_CLUSTER_VERSION/bin/pg_upgrade --check --link        \
+             -b /usr/lib/postgresql/$OLD_CLUSTER_VERSION/bin                                \
+             -B /usr/lib/postgresql/$NEW_CLUSTER_VERSION/bin                                \
+             -d $OLD_CLUSTER_DATADIR                  \
+             -D $NEW_CLUSTER_DATADIR                  \
+             -o " -c config_file=/etc/postgresql/$OLD_CLUSTER_VERSION/$OLD_CLUSTER_NAME/postgresql.conf" \
+             -O " -c config_file=/etc/postgresql/$NEW_CLUSTER_VERSION/$NEW_CLUSTER_NAME/postgresql.conf"
+
+        # Really upgrade the data
+        time /usr/lib/postgresql/$NEW_CLUSTER_VERSION/bin/pg_upgrade         --link        \
+             -b /usr/lib/postgresql/$OLD_CLUSTER_VERSION/bin                                \
+             -B /usr/lib/postgresql/$NEW_CLUSTER_VERSION/bin                                \
+             -d $OLD_CLUSTER_DATADIR                  \
+             -D $NEW_CLUSTER_DATADIR                  \
+             -o " -c config_file=/etc/postgresql/$OLD_CLUSTER_VERSION/$OLD_CLUSTER_NAME/postgresql.conf" \
+             -O " -c config_file=/etc/postgresql/$NEW_CLUSTER_VERSION/$NEW_CLUSTER_NAME/postgresql.conf"
+
+        ## Upgrade standby server
+
+        ### Making sure new datadir is empty
+        if [ -z "$(ssh $STANDBY_SERVER ls -A $STANDBY_NEW_CLUSTER_DATADIR)" ]; then
+            echo "INFO: New cluster datadir is empty on standby server. Good."
+        else
+            echo "WARNING: New cluster datadir is NOT empty on standby server. Deleting the content of $STANDBY_NEW_CLUSTER_DATADIR on $STANDBY_SERVER now..."
+            ssh $STANDBY_SERVER rm -rf $STANDBY_NEW_CLUSTER_DATADIR
+        fi
+
+        ### Save configuration files
+        TMPDIR=$(ssh $STANDBY_SERVER mktemp -d -t pg_upgrade_XXXX)
+        ssh $STANDBY_SERVER mv $STANDBY_OLD_CLUSTER_DATADIR/recovery.conf $TMPDIR
+
+        ### Upgrade (via rsync)
+        rsync --archive --delete --hard-links --size-only --no-inc-recursive $OLD_CLUSTER_DATADIR $NEW_CLUSTER_DATADIR $STANDBY_SERVER:$(dirname $STANDBY_NEW_CLUSTER_DATADIR)
+
+        ### Restore saved configured files
+        ssh $STANDBY_SERVER mv $TMPDIR/recovery.conf $STANDBY_NEW_CLUSTER_DATADIR/
+        ssh $STANDBY_SERVER rm -rf $TMPDIR
+
+        # Start the $NEW_CLUSTER_VERSION primary server
+        pg_ctlcluster $NEW_CLUSTER_VERSION $NEW_CLUSTER_NAME start
+
+        # Test local primary is accepting connections
+        psql --port=$DATABASE_PORT --dbname=$DATABASE_NAME --command="SELECT NOW();"
+
+        {% if postgres_pgbouncer_uri is defined and postgres_pgbouncer_uri %}
+        # Resume the connexions
+        psql $PGBOUNCER_PG_URI --command "RESUME $DATABASE_NAME;"
+        {% endif %}
+
+        # Start the $NEW_CLUSTER_VERSION standby server
+        ssh $STANDBY_SERVER pg_ctlcluster $NEW_CLUSTER_VERSION $STANDBY_NEW_CLUSTER_NAME start
+
+        echo "DONE. Upgrade of PG cluster from $OLD_CLUSTER_VERSION/$OLD_CLUSTER_NAME to $NEW_CLUSTER_VESION/$NEW_CLUSTER_NAME is finished! Well done!"
+    else
+        # Start the $OLD_CLUSTER_VERSION primary server
+        pg_ctlcluster $OLD_CLUSTER_VERSION $OLD_CLUSTER_NAME start
+        # Start the $OLD_CLUSTER_VERSION standby server
+        ssh $STANDBY_SERVER pg_ctlcluster $OLD_CLUSTER_VERSION $OLD_CLUSTER_NAME start
+
+        # Test local primary is accepting connections
+        psql --dbname=$DATABASE_NAME --command="SELECT NOW();"
+
+        {% if postgres_pgbouncer_uri is defined and postgres_pgbouncer_uri %}
+        # Resume the connexions
+        psql $PGBOUNCER_PG_URI --command "RESUME $DATABASE_NAME;"
+        {% endif %}
+    fi
+else
+    echo "INFO: You didn't want to continue or was in 'dry-run' mode"
+fi
diff --git a/templates/postgresql.10.conf.j2 b/templates/postgresql.10.conf.j2
new file mode 100644 (file)
index 0000000..588020f
--- /dev/null
@@ -0,0 +1,694 @@
+# {{ ansible_managed }}
+# -----------------------------
+# PostgreSQL configuration file
+# -----------------------------
+#
+# This file consists of lines of the form:
+#
+#   name = value
+#
+# (The "=" is optional.)  Whitespace may be used.  Comments are introduced with
+# "#" anywhere on a line.  The complete list of parameter names and allowed
+# values can be found in the PostgreSQL documentation.
+#
+# The commented-out settings shown in this file represent the default values.
+# Re-commenting a setting is NOT sufficient to revert it to the default value;
+# you need to reload the server.
+#
+# This file is read on server startup and when the server receives a SIGHUP
+# signal.  If you edit the file on a running system, you have to SIGHUP the
+# server for the changes to take effect, run "pg_ctl reload", or execute
+# "SELECT pg_reload_conf()".  Some parameters, which are marked below,
+# require a server shutdown and restart to take effect.
+#
+# Any parameter can also be given as a command-line option to the server, e.g.,
+# "postgres -c log_connections=on".  Some parameters can be changed at run time
+# with the "SET" SQL command.
+#
+# Memory units:  kB = kilobytes        Time units:  ms  = milliseconds
+#                MB = megabytes                     s   = seconds
+#                GB = gigabytes                     min = minutes
+#                TB = terabytes                     h   = hours
+#                                                   d   = days
+
+
+#------------------------------------------------------------------------------
+# FILE LOCATIONS
+#------------------------------------------------------------------------------
+
+# The default values of these variables are driven from the -D command-line
+# option or PGDATA environment variable, represented here as ConfigDir.
+
+data_directory = '/var/lib/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}'              # use data in another directory
+                                       # (change requires restart)
+hba_file = '/etc/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/pg_hba.conf'    # host-based authentication file
+                                       # (change requires restart)
+ident_file = '/etc/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/pg_ident.conf'        # ident configuration file
+                                       # (change requires restart)
+
+# If external_pid_file is not explicitly set, no extra PID file is written.
+external_pid_file = '/var/run/postgresql/{{ postgres_version }}-{{ postgres_cluster_name }}.pid'               # write an extra PID file
+                                       # (change requires restart)
+
+
+#------------------------------------------------------------------------------
+# CONNECTIONS AND AUTHENTICATION
+#------------------------------------------------------------------------------
+
+# - Connection Settings -
+
+listen_addresses = '{{ postgres_listen_addresses | reject("none") | join(",") }}' # what IP address(es) to listen on;
+                                       # comma-separated list of addresses;
+                                       # defaults to 'localhost'; use '*' for all
+                                       # (change requires restart)
+port = {{ postgres_port }}                             # (change requires restart)
+max_connections = 400                  # (change requires restart)
+# Note:  Increasing max_connections costs ~400 bytes of shared memory per
+# connection slot, plus lock space (see max_locks_per_transaction).
+#superuser_reserved_connections = 3    # (change requires restart)
+unix_socket_directories = '/var/run/postgresql'        # comma-separated list of directories
+                                       # (change requires restart)
+#unix_socket_group = ''                        # (change requires restart)
+#unix_socket_permissions = 0777                # begin with 0 to use octal notation
+                                       # (change requires restart)
+#bonjour = off                         # advertise server via Bonjour
+                                       # (change requires restart)
+#bonjour_name = ''                     # defaults to the computer name
+                                       # (change requires restart)
+
+# - Security and Authentication -
+
+#authentication_timeout = 1min         # 1s-600s
+ssl = on
+#ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL' # allowed SSL ciphers
+#ssl_prefer_server_ciphers = on
+#ssl_ecdh_curve = 'prime256v1'
+#ssl_dh_params_file = ''
+# ssl_cert_file = '/etc/ssl/certs/ssl-cert-snakeoil.pem'
+# ssl_key_file = '/etc/ssl/private/ssl-cert-snakeoil.key'
+#ssl_ca_file = ''
+#ssl_crl_file = ''
+#password_encryption = md5             # md5 or scram-sha-256
+#db_user_namespace = off
+#row_security = on
+
+# GSSAPI using Kerberos
+#krb_server_keyfile = ''
+#krb_caseins_users = off
+
+# - TCP Keepalives -
+# see "man 7 tcp" for details
+
+#tcp_keepalives_idle = 0               # TCP_KEEPIDLE, in seconds;
+                                       # 0 selects the system default
+#tcp_keepalives_interval = 0           # TCP_KEEPINTVL, in seconds;
+                                       # 0 selects the system default
+#tcp_keepalives_count = 0              # TCP_KEEPCNT;
+                                       # 0 selects the system default
+
+
+#------------------------------------------------------------------------------
+# RESOURCE USAGE (except WAL)
+#------------------------------------------------------------------------------
+
+# - Memory -
+
+{% if ansible_memtotal_mb > 65536 %}
+shared_buffers = 16GB                  # min 128kB
+{% else %}
+shared_buffers = {{ ansible_memtotal_mb // 4 }}MB                      # min 128kB
+{% endif %}
+                                       # (change requires restart)
+#huge_pages = try                      # on, off, or try
+                                       # (change requires restart)
+temp_buffers = 24MB                    # min 800kB
+#max_prepared_transactions = 0         # zero disables the feature
+                                       # (change requires restart)
+# Caution: it is not advisable to set max_prepared_transactions nonzero unless
+# you actively intend to use prepared transactions.
+work_mem = 512MB                               # min 64kB
+maintenance_work_mem = 1024MB          # min 1MB
+#replacement_sort_tuples = 150000      # limits use of replacement selection sort
+#autovacuum_work_mem = -1              # min 1MB, or -1 to use maintenance_work_mem
+#max_stack_depth = 2MB                 # min 100kB
+dynamic_shared_memory_type = posix     # the default is the first option
+                                       # supported by the operating system:
+                                       #   posix
+                                       #   sysv
+                                       #   windows
+                                       #   mmap
+                                       # use none to disable dynamic shared memory
+                                       # (change requires restart)
+
+# - Disk -
+
+#temp_file_limit = -1                  # limits per-process temp file space
+                                       # in kB, or -1 for no limit
+
+# - Kernel Resource Usage -
+
+#max_files_per_process = 1000          # min 25
+                                       # (change requires restart)
+#shared_preload_libraries = ''         # (change requires restart)
+
+# - Cost-Based Vacuum Delay -
+
+#vacuum_cost_delay = 0                 # 0-100 milliseconds
+#vacuum_cost_page_hit = 1              # 0-10000 credits
+#vacuum_cost_page_miss = 10            # 0-10000 credits
+#vacuum_cost_page_dirty = 20           # 0-10000 credits
+#vacuum_cost_limit = 200               # 1-10000 credits
+
+# - Background Writer -
+
+bgwriter_delay = 2000ms                        # 10-10000ms between rounds
+#bgwriter_lru_maxpages = 100           # 0-1000 max buffers written/round
+#bgwriter_lru_multiplier = 2.0         # 0-10.0 multiplier on buffers scanned/round
+#bgwriter_flush_after = 512kB          # measured in pages, 0 disables
+
+# - Asynchronous Behavior -
+
+#effective_io_concurrency = 1          # 1-1000; 0 disables prefetching
+#max_worker_processes = 8              # (change requires restart)
+#max_parallel_workers_per_gather = 2   # taken from max_parallel_workers
+#max_parallel_workers = 8              # maximum number of max_worker_processes that
+                                       # can be used in parallel queries
+#old_snapshot_threshold = -1           # 1min-60d; -1 disables; 0 is immediate
+                                       # (change requires restart)
+#backend_flush_after = 0               # measured in pages, 0 disables
+
+
+#------------------------------------------------------------------------------
+# WRITE AHEAD LOG
+#------------------------------------------------------------------------------
+
+# - Settings -
+
+wal_level = logical                    # minimal, replica, or logical
+                                       # (change requires restart)
+{% if postgres_fsync_enabled %}
+#fsync = on                            # flush data to disk for crash safety
+                                       # (turning this off can cause
+                                       # unrecoverable data corruption)
+#synchronous_commit = on               # synchronization level;
+# off, local, remote_write, remote_apply, or on
+{% else %}
+fsync = off                            # turns forced synchronization on or off
+synchronous_commit = off               # synchronization level;
+{% endif %}
+#wal_sync_method = fsync               # the default is the first option
+                                       # supported by the operating system:
+                                       #   open_datasync
+                                       #   fdatasync (default on Linux)
+                                       #   fsync
+                                       #   fsync_writethrough
+                                       #   open_sync
+#full_page_writes = on                 # recover from partial page writes
+#wal_compression = off                 # enable compression of full-page writes
+wal_log_hints = on                     # also do full page writes of non-critical updates
+                                       # (change requires restart)
+#wal_buffers = -1                      # min 32kB, -1 sets based on shared_buffers
+                                       # (change requires restart)
+#wal_writer_delay = 200ms              # 1-10000 milliseconds
+#wal_writer_flush_after = 1MB          # measured in pages, 0 disables
+
+#commit_delay = 0                      # range 0-100000, in microseconds
+#commit_siblings = 5                   # range 1-1000
+
+# - Checkpoints -
+
+#checkpoint_timeout = 5min             # range 30s-1d
+#max_wal_size = 1GB
+#min_wal_size = 80MB
+#checkpoint_completion_target = 0.5    # checkpoint target duration, 0.0 - 1.0
+#checkpoint_flush_after = 256kB                # measured in pages, 0 disables
+#checkpoint_warning = 30s              # 0 disables
+
+# - Archiving -
+
+{% if postgres_archive_enabled %}
+archive_mode = on
+archive_command = 'rsync -a %p barman@{{ postgres_barman_server }}:/var/lib/barman/{{ barman_directory }}/incoming/%f'
+{% else %}
+archive_mode = off
+archive_command = ''
+{% endif %}
+
+#archive_mode = off            # enables archiving; off, on, or always
+                               # (change requires restart)
+#archive_command = ''          # command to use to archive a logfile segment
+                               # placeholders: %p = path of file to archive
+                               #               %f = file name only
+                               # e.g. 'test ! -f /mnt/server/archivedir/%f && cp %p /mnt/server/archivedir/%f'
+#archive_timeout = 0           # force a logfile segment switch after this
+                               # number of seconds; 0 disables
+
+
+#------------------------------------------------------------------------------
+# REPLICATION
+#------------------------------------------------------------------------------
+
+# - Sending Server(s) -
+
+# Set these on the master and on any standby that will send replication data.
+
+max_wal_senders = 10           # max number of walsender processes
+                               # (change requires restart)
+wal_keep_segments = 16         # in logfile segments, 16MB each; 0 disables
+#wal_sender_timeout = 60s      # in milliseconds; 0 disables
+
+{% if postgres_max_replication_slots is defined %}
+max_replication_slots = {{ postgres_max_replication_slots }} # max number of replication slots
+{% else %}
+#max_replication_slots = 0     # max number of replication slots
+{% endif %}
+                               # (change requires restart)
+#track_commit_timestamp = off  # collect timestamp of transaction commit
+                               # (change requires restart)
+
+# - Master Server -
+
+# These settings are ignored on a standby server.
+
+#synchronous_standby_names = ''        # standby servers that provide sync rep
+                               # method to choose sync standbys, number of sync standbys,
+                               # and comma-separated list of application_name
+                               # from standby(s); '*' = all
+#vacuum_defer_cleanup_age = 0  # number of xacts by which cleanup is delayed
+
+# - Standby Servers -
+
+# These settings are ignored on a master server.
+
+hot_standby = on                       # "off" disallows queries during recovery
+                                       # (change requires restart)
+#max_standby_archive_delay = 30s       # max delay before canceling queries
+                                       # when reading WAL from archive;
+                                       # -1 allows indefinite delay
+max_standby_streaming_delay = {{ postgres_extra_config.max_standby_streaming_delay | default('600s') }}        # max delay before canceling queries
+                                       # when reading streaming WAL;
+                                       # -1 allows indefinite delay
+#wal_receiver_status_interval = 10s    # send replies at least this often
+                                       # 0 disables
+#hot_standby_feedback = off            # send info from standby to prevent
+                                       # query conflicts
+#wal_receiver_timeout = 60s            # time that receiver waits for
+                                       # communication from master
+                                       # in milliseconds; 0 disables
+#wal_retrieve_retry_interval = 5s      # time to wait before retrying to
+                                       # retrieve WAL after a failed attempt
+
+# - Subscribers -
+
+# These settings are ignored on a publisher.
+
+#max_logical_replication_workers = 4   # taken from max_worker_processes
+                                       # (change requires restart)
+#max_sync_workers_per_subscription = 2 # taken from max_logical_replication_workers
+
+
+#------------------------------------------------------------------------------
+# QUERY TUNING
+#------------------------------------------------------------------------------
+
+# - Planner Method Configuration -
+
+#enable_bitmapscan = on
+#enable_hashagg = on
+#enable_hashjoin = on
+#enable_indexscan = on
+#enable_indexonlyscan = on
+#enable_material = on
+#enable_mergejoin = on
+#enable_nestloop = on
+#enable_seqscan = on
+#enable_sort = on
+#enable_tidscan = on
+
+# - Planner Cost Constants -
+
+#seq_page_cost = 1.0                   # measured on an arbitrary scale
+{% if postgres_specific_random_page_cost is defined -%}
+# Random page cost is an arbitrary value relative to the seq_page_cost conf (default 1.0)
+# On SSD disk it is better to lower the default value from 4.0 to 1.0 for instance.
+random_page_cost = {{ postgres_specific_random_page_cost }}                    # same scale as above
+{% else -%}
+#random_page_cost = 4.0                        # same scale as above
+{% endif %}
+#cpu_tuple_cost = 0.01                 # same scale as above
+#cpu_index_tuple_cost = 0.005          # same scale as above
+#cpu_operator_cost = 0.0025            # same scale as above
+#parallel_tuple_cost = 0.1             # same scale as above
+#parallel_setup_cost = 1000.0  # same scale as above
+#min_parallel_table_scan_size = 8MB
+#min_parallel_index_scan_size = 512kB
+#effective_cache_size = 4GB
+effective_cache_size = {{ ansible_memtotal_mb // 2 }}MB
+
+# - Genetic Query Optimizer -
+
+#geqo = on
+#geqo_threshold = 12
+#geqo_effort = 5                       # range 1-10
+#geqo_pool_size = 0                    # selects default based on effort
+#geqo_generations = 0                  # selects default based on effort
+#geqo_selection_bias = 2.0             # range 1.5-2.0
+#geqo_seed = 0.0                       # range 0.0-1.0
+
+# - Other Planner Options -
+
+#default_statistics_target = 100       # range 1-10000
+#constraint_exclusion = partition      # on, off, or partition
+#cursor_tuple_fraction = 0.1           # range 0.0-1.0
+#from_collapse_limit = 8
+#join_collapse_limit = 8               # 1 disables collapsing of explicit
+                                       # JOIN clauses
+#force_parallel_mode = off
+
+
+#------------------------------------------------------------------------------
+# ERROR REPORTING AND LOGGING
+#------------------------------------------------------------------------------
+
+# - Where to Log -
+
+#log_destination = 'stderr'            # Valid values are combinations of
+                                       # stderr, csvlog, syslog, and eventlog,
+                                       # depending on platform.  csvlog
+                                       # requires logging_collector to be on.
+
+# This is used when logging to stderr:
+#logging_collector = off               # Enable capturing of stderr and csvlog
+                                       # into log files. Required to be on for
+                                       # csvlogs.
+                                       # (change requires restart)
+
+# These are only used if logging_collector is on:
+#log_directory = 'log'                 # directory where log files are written,
+                                       # can be absolute or relative to PGDATA
+#log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'       # log file name pattern,
+                                       # can include strftime() escapes
+#log_file_mode = 0600                  # creation mode for log files,
+                                       # begin with 0 to use octal notation
+#log_truncate_on_rotation = off                # If on, an existing log file with the
+                                       # same name as the new log file will be
+                                       # truncated rather than appended to.
+                                       # But such truncation only occurs on
+                                       # time-driven rotation, not on restarts
+                                       # or size-driven rotation.  Default is
+                                       # off, meaning append to existing files
+                                       # in all cases.
+#log_rotation_age = 1d                 # Automatic rotation of logfiles will
+                                       # happen after that time.  0 disables.
+#log_rotation_size = 10MB              # Automatic rotation of logfiles will
+                                       # happen after that much log output.
+                                       # 0 disables.
+
+# These are relevant when logging to syslog:
+#syslog_facility = 'LOCAL0'
+#syslog_ident = 'postgres'
+#syslog_sequence_numbers = on
+#syslog_split_messages = on
+
+# This is only relevant when logging to eventlog (win32):
+# (change requires restart)
+#event_source = 'PostgreSQL'
+
+# - When to Log -
+
+#client_min_messages = notice          # values in order of decreasing detail:
+                                       #   debug5
+                                       #   debug4
+                                       #   debug3
+                                       #   debug2
+                                       #   debug1
+                                       #   log
+                                       #   notice
+                                       #   warning
+                                       #   error
+
+#log_min_messages = warning            # values in order of decreasing detail:
+                                       #   debug5
+                                       #   debug4
+                                       #   debug3
+                                       #   debug2
+                                       #   debug1
+                                       #   info
+                                       #   notice
+                                       #   warning
+                                       #   error
+                                       #   log
+                                       #   fatal
+                                       #   panic
+
+#log_min_error_statement = error       # values in order of decreasing detail:
+                                       #   debug5
+                                       #   debug4
+                                       #   debug3
+                                       #   debug2
+                                       #   debug1
+                                       #   info
+                                       #   notice
+                                       #   warning
+                                       #   error
+                                       #   log
+                                       #   fatal
+                                       #   panic (effectively off)
+
+log_min_duration_statement = 10000     # -1 is disabled, 0 logs all statements
+                                       # and their durations, > 0 logs only
+                                       # statements running at least this number
+                                       # of milliseconds
+
+
+# - What to Log -
+
+#debug_print_parse = off
+#debug_print_rewritten = off
+#debug_print_plan = off
+#debug_pretty_print = on
+#log_checkpoints = off
+#log_connections = off
+#log_disconnections = off
+#log_duration = off
+#log_error_verbosity = default         # terse, default, or verbose messages
+#log_hostname = off
+
+log_line_prefix = '{{ postgres_log_line_prefix }}'
+#log_line_prefix = '%m [%p] %q%u@%d '  # special values:
+                                       #   %a = application name
+                                       #   %u = user name
+                                       #   %d = database name
+                                       #   %r = remote host and port
+                                       #   %h = remote host
+                                       #   %p = process ID
+                                       #   %t = timestamp without milliseconds
+                                       #   %m = timestamp with milliseconds
+                                       #   %n = timestamp with milliseconds (as a Unix epoch)
+                                       #   %i = command tag
+                                       #   %e = SQL state
+                                       #   %c = session ID
+                                       #   %l = session line number
+                                       #   %s = session start timestamp
+                                       #   %v = virtual transaction ID
+                                       #   %x = transaction ID (0 if none)
+                                       #   %q = stop here in non-session
+                                       #        processes
+                                       #   %% = '%'
+                                       # e.g. '<%u%%%d> '
+#log_lock_waits = off                  # log lock waits >= deadlock_timeout
+#log_statement = 'none'                        # none, ddl, mod, all
+#log_replication_commands = off
+#log_temp_files = -1                   # log temporary files equal or larger
+                                       # than the specified size in kilobytes;
+                                       # -1 disables, 0 logs all temp files
+log_timezone = 'UTC'
+
+
+# - Process Title -
+
+cluster_name = '{{ postgres_version }}/{{ postgres_cluster_name }}'                    # added to process titles if nonempty
+                                       # (change requires restart)
+#update_process_title = on
+
+
+#------------------------------------------------------------------------------
+# RUNTIME STATISTICS
+#------------------------------------------------------------------------------
+
+# - Query/Index Statistics Collector -
+
+#track_activities = on
+#track_counts = on
+#track_io_timing = off
+#track_functions = none                        # none, pl, all
+#track_activity_query_size = 1024      # (change requires restart)
+stats_temp_directory = '/var/run/postgresql/{{ postgres_version }}-{{ postgres_cluster_name }}.pg_stat_tmp'
+
+
+# - Statistics Monitoring -
+
+#log_parser_stats = off
+#log_planner_stats = off
+#log_executor_stats = off
+#log_statement_stats = off
+
+
+#------------------------------------------------------------------------------
+# AUTOVACUUM PARAMETERS
+#------------------------------------------------------------------------------
+
+#autovacuum = on                       # Enable autovacuum subprocess?  'on'
+                                       # requires track_counts to also be on.
+#log_autovacuum_min_duration = -1      # -1 disables, 0 logs all actions and
+                                       # their durations, > 0 logs only
+                                       # actions running at least this number
+                                       # of milliseconds.
+#autovacuum_max_workers = 3            # max number of autovacuum subprocesses
+                                       # (change requires restart)
+#autovacuum_naptime = 1min             # time between autovacuum runs
+#autovacuum_vacuum_threshold = 50      # min number of row updates before
+                                       # vacuum
+#autovacuum_analyze_threshold = 50     # min number of row updates before
+                                       # analyze
+#autovacuum_vacuum_scale_factor = 0.2  # fraction of table size before vacuum
+#autovacuum_analyze_scale_factor = 0.1 # fraction of table size before analyze
+#autovacuum_freeze_max_age = 200000000 # maximum XID age before forced vacuum
+                                       # (change requires restart)
+#autovacuum_multixact_freeze_max_age = 400000000       # maximum multixact age
+                                       # before forced vacuum
+                                       # (change requires restart)
+#autovacuum_vacuum_cost_delay = 20ms   # default vacuum cost delay for
+                                       # autovacuum, in milliseconds;
+                                       # -1 means use vacuum_cost_delay
+#autovacuum_vacuum_cost_limit = -1     # default vacuum cost limit for
+                                       # autovacuum, -1 means use
+                                       # vacuum_cost_limit
+
+
+#------------------------------------------------------------------------------
+# CLIENT CONNECTION DEFAULTS
+#------------------------------------------------------------------------------
+
+# - Statement Behavior -
+
+#search_path = '"$user", public'       # schema names
+#default_tablespace = ''               # a tablespace name, '' uses the default
+#temp_tablespaces = ''                 # a list of tablespace names, '' uses
+                                       # only default tablespace
+#check_function_bodies = on
+#default_transaction_isolation = 'read committed'
+#default_transaction_read_only = off
+#default_transaction_deferrable = off
+#session_replication_role = 'origin'
+#statement_timeout = 0                 # in milliseconds, 0 is disabled
+#lock_timeout = 0                      # in milliseconds, 0 is disabled
+#idle_in_transaction_session_timeout = 0       # in milliseconds, 0 is disabled
+#vacuum_freeze_min_age = 50000000
+#vacuum_freeze_table_age = 150000000
+#vacuum_multixact_freeze_min_age = 5000000
+#vacuum_multixact_freeze_table_age = 150000000
+#bytea_output = 'hex'                  # hex, escape
+#xmlbinary = 'base64'
+#xmloption = 'content'
+#gin_fuzzy_search_limit = 0
+#gin_pending_list_limit = 4MB
+
+# - Locale and Formatting -
+
+datestyle = '{{ postgres_datestyle }}'
+#intervalstyle = 'postgres'
+#timezone = '(defaults to server environment setting)'
+{% if postgres_timezone is defined %}
+timezone = '{{ postgres_timezone }}'
+{% endif %}
+#timezone_abbreviations = 'Default'     # Select the set of available time zone
+                                       # abbreviations.  Currently, there are
+                                       #   Default
+                                       #   Australia (historical usage)
+                                       #   India
+                                       # You can create your own file in
+                                       # share/timezonesets/.
+#extra_float_digits = 0                        # min -15, max 3
+#client_encoding = sql_ascii           # actually, defaults to database
+                                       # encoding
+
+# These settings are initialized by initdb, but they can be changed.
+lc_messages = '{{ postgres_locale_system }}'   # locale for system error message
+                                       # strings
+lc_monetary = '{{ postgres_locale_formats }}'  # locale for monetary formatting
+lc_numeric = '{{ postgres_locale_formats }}'   # locale for number formatting
+lc_time = '{{ postgres_locale_formats }}'      # locale for time formatting
+
+# default configuration for text search
+default_text_search_config = '{{ postgres_text_search_config }}'
+
+# - Other Defaults -
+
+#dynamic_library_path = '$libdir'
+#local_preload_libraries = ''
+#session_preload_libraries = ''
+
+
+#------------------------------------------------------------------------------
+# LOCK MANAGEMENT
+#------------------------------------------------------------------------------
+
+#deadlock_timeout = 1s
+#max_locks_per_transaction = 64                # min 10
+                                       # (change requires restart)
+#max_pred_locks_per_transaction = 64   # min 10
+                                       # (change requires restart)
+#max_pred_locks_per_relation = -2      # negative values mean
+                                       # (max_pred_locks_per_transaction
+                                       #  / -max_pred_locks_per_relation) - 1
+#max_pred_locks_per_page = 2            # min 0
+
+
+#------------------------------------------------------------------------------
+# VERSION/PLATFORM COMPATIBILITY
+#------------------------------------------------------------------------------
+
+# - Previous PostgreSQL Versions -
+
+#array_nulls = on
+#backslash_quote = safe_encoding       # on, off, or safe_encoding
+#default_with_oids = off
+#escape_string_warning = on
+#lo_compat_privileges = off
+#operator_precedence_warning = off
+#quote_all_identifiers = off
+#standard_conforming_strings = on
+#synchronize_seqscans = on
+
+# - Other Platforms and Clients -
+
+#transform_null_equals = off
+
+
+#------------------------------------------------------------------------------
+# ERROR HANDLING
+#------------------------------------------------------------------------------
+
+#exit_on_error = off                   # terminate session on any error?
+#restart_after_crash = on              # reinitialize after backend crash?
+
+
+#------------------------------------------------------------------------------
+# CONFIG FILE INCLUDES
+#------------------------------------------------------------------------------
+
+# These options allow settings to be loaded from files other than the
+# default postgresql.conf.
+
+#include_dir = 'conf.d'                        # include files ending in '.conf' from
+                                       # directory 'conf.d'
+#include_if_exists = 'exists.conf'     # include file only if it exists
+#include = 'special.conf'              # include file
+
+
+#------------------------------------------------------------------------------
+# CUSTOMIZED OPTIONS
+#------------------------------------------------------------------------------
+
+# Add settings for extensions here
diff --git a/templates/postgresql.9.1.conf.j2 b/templates/postgresql.9.1.conf.j2
new file mode 100644 (file)
index 0000000..e15dfed
--- /dev/null
@@ -0,0 +1,589 @@
+# {{ ansible_managed }}
+# -----------------------------
+# PostgreSQL configuration file
+# -----------------------------
+#
+# This file consists of lines of the form:
+#
+#   name = value
+#
+# (The "=" is optional.)  Whitespace may be used.  Comments are introduced with
+# "#" anywhere on a line.  The complete list of parameter names and allowed
+# values can be found in the PostgreSQL documentation.
+#
+# The commented-out settings shown in this file represent the default values.
+# Re-commenting a setting is NOT sufficient to revert it to the default value;
+# you need to reload the server.
+#
+# This file is read on server startup and when the server receives a SIGHUP
+# signal.  If you edit the file on a running system, you have to SIGHUP the
+# server for the changes to take effect, or use "pg_ctl reload".  Some
+# parameters, which are marked below, require a server shutdown and restart to
+# take effect.
+#
+# Any parameter can also be given as a command-line option to the server, e.g.,
+# "postgres -c log_connections=on".  Some parameters can be changed at run time
+# with the "SET" SQL command.
+#
+# Memory units:  kB = kilobytes        Time units:  ms  = milliseconds
+#                MB = megabytes                     s   = seconds
+#                GB = gigabytes                     min = minutes
+#                                                   h   = hours
+#                                                   d   = days
+
+
+#------------------------------------------------------------------------------
+# FILE LOCATIONS
+#------------------------------------------------------------------------------
+
+# The default values of these variables are driven from the -D command-line
+# option or PGDATA environment variable, represented here as ConfigDir.
+
+data_directory = '/var/lib/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}'              # use data in another directory
+                                       # (change requires restart)
+hba_file = '/etc/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/pg_hba.conf'    # host-based authentication file
+                                       # (change requires restart)
+ident_file = '/etc/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/pg_ident.conf'        # ident configuration file
+                                       # (change requires restart)
+
+# If external_pid_file is not explicitly set, no extra PID file is written.
+external_pid_file = '/var/run/postgresql/{{ postgres_version }}-{{ postgres_cluster_name }}.pid'               # write an extra PID file
+                                       # (change requires restart)
+
+
+#------------------------------------------------------------------------------
+# CONNECTIONS AND AUTHENTICATION
+#------------------------------------------------------------------------------
+
+# - Connection Settings -
+
+listen_addresses = '{{ postgres_listen_addresses | reject("none") | join(",") }}' # what IP address(es) to listen on;
+                                       # comma-separated list of addresses;
+                                       # defaults to 'localhost', '*' = all
+                                       # (change requires restart)
+port = {{ postgres_port }}                             # (change requires restart)
+max_connections = 400                  # (change requires restart)
+# Note:  Increasing max_connections costs ~400 bytes of shared memory per
+# connection slot, plus lock space (see max_locks_per_transaction).
+#superuser_reserved_connections = 3    # (change requires restart)
+unix_socket_directory = '/var/run/postgresql'          # (change requires restart)
+#unix_socket_group = ''                        # (change requires restart)
+#unix_socket_permissions = 0777                # begin with 0 to use octal notation
+                                       # (change requires restart)
+#bonjour = off                         # advertise server via Bonjour
+                                       # (change requires restart)
+#bonjour_name = ''                     # defaults to the computer name
+                                       # (change requires restart)
+
+# - Security and Authentication -
+
+#authentication_timeout = 1min         # 1s-600s
+ssl = true                             # (change requires restart)
+#ssl_ciphers = 'ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH'     # allowed SSL ciphers
+                                       # (change requires restart)
+#ssl_renegotiation_limit = 512MB       # amount of data between renegotiations
+#password_encryption = on
+#db_user_namespace = off
+
+# Kerberos and GSSAPI
+#krb_server_keyfile = ''
+#krb_srvname = 'postgres'              # (Kerberos only)
+#krb_caseins_users = off
+
+# - TCP Keepalives -
+# see "man 7 tcp" for details
+
+#tcp_keepalives_idle = 0               # TCP_KEEPIDLE, in seconds;
+                                       # 0 selects the system default
+#tcp_keepalives_interval = 0           # TCP_KEEPINTVL, in seconds;
+                                       # 0 selects the system default
+#tcp_keepalives_count = 0              # TCP_KEEPCNT;
+                                       # 0 selects the system default
+
+
+#------------------------------------------------------------------------------
+# RESOURCE USAGE (except WAL)
+#------------------------------------------------------------------------------
+
+# - Memory -
+
+shared_buffers = 512MB                 # min 128kB
+                                       # (change requires restart)
+temp_buffers = 24MB                    # min 800kB
+#max_prepared_transactions = 0         # zero disables the feature
+                                       # (change requires restart)
+# Note:  Increasing max_prepared_transactions costs ~600 bytes of shared memory
+# per transaction slot, plus lock space (see max_locks_per_transaction).
+# It is not advisable to set max_prepared_transactions nonzero unless you
+# actively intend to use prepared transactions.
+#work_mem = 1MB                                # min 64kB
+#maintenance_work_mem = 16MB           # min 1MB
+#max_stack_depth = 2MB                 # min 100kB
+
+work_mem = 512MB
+maintenance_work_mem = 1024MB
+
+
+# - Kernel Resource Usage -
+
+#max_files_per_process = 1000          # min 25
+                                       # (change requires restart)
+#shared_preload_libraries = ''         # (change requires restart)
+
+# - Cost-Based Vacuum Delay -
+
+#vacuum_cost_delay = 0ms               # 0-100 milliseconds
+#vacuum_cost_page_hit = 1              # 0-10000 credits
+#vacuum_cost_page_miss = 10            # 0-10000 credits
+#vacuum_cost_page_dirty = 20           # 0-10000 credits
+#vacuum_cost_limit = 200               # 1-10000 credits
+
+# - Background Writer -
+
+bgwriter_delay = 2000ms                        # 10-10000ms between rounds
+#bgwriter_lru_maxpages = 100           # 0-1000 max buffers written/round
+#bgwriter_lru_multiplier = 2.0         # 0-10.0 multipler on buffers scanned/round
+
+# - Asynchronous Behavior -
+
+#effective_io_concurrency = 1          # 1-1000. 0 disables prefetching
+
+
+#------------------------------------------------------------------------------
+# WRITE AHEAD LOG
+#------------------------------------------------------------------------------
+
+# - Settings -
+
+#barman and replication
+#wal_level = 'archive' # For PostgreSQL >= 9.0
+wal_level = 'hot_standby' # For PostgreSQL >= 9.0
+
+{% if postgres_archive_enabled %}
+archive_mode = on
+archive_command = 'rsync -a %p barman@{{ postgres_barman_server }}:/var/lib/barman/{{ barman_directory }}/incoming/%f'
+{% else %}
+archive_mode = off
+archive_command = ''
+{% endif %}
+
+max_wal_senders = 5
+checkpoint_segments = 8
+wal_keep_segments = 16
+hot_standby = on
+wal_level = hot_standby                        # minimal, archive, or hot_standby
+
+                                       # (change requires restart)
+{% if postgres_fsync_enabled %}
+#fsync = on                            # turns forced synchronization on or off
+#synchronous_commit = on               # synchronization level;
+{% else %}
+fsync = off                            # turns forced synchronization on or off
+synchronous_commit = off               # synchronization level;
+{% endif %}
+#wal_sync_method = fsync               # the default is the first option
+                                       # supported by the operating system:
+                                       #   open_datasync
+                                       #   fdatasync (default on Linux)
+                                       #   fsync
+                                       #   fsync_writethrough
+                                       #   open_sync
+#full_page_writes = on                 # recover from partial page writes
+#wal_buffers = -1                      # min 32kB, -1 sets based on shared_buffers
+                                       # (change requires restart)
+#wal_writer_delay = 200ms              # 1-10000 milliseconds
+
+#commit_delay = 0                      # range 0-100000, in microseconds
+#commit_siblings = 5                   # range 1-1000
+
+# - Checkpoints -
+
+#checkpoint_segments = 3               # in logfile segments, min 1, 16MB each
+#checkpoint_timeout = 5min             # range 30s-1h
+#checkpoint_completion_target = 0.5    # checkpoint target duration, 0.0 - 1.0
+#checkpoint_warning = 30s              # 0 disables
+
+# - Archiving -
+
+#archive_mode = off            # allows archiving to be done
+                               # (change requires restart)
+#archive_command = ''          # command to use to archive a logfile segment
+#archive_timeout = 0           # force a logfile segment switch after this
+                               # number of seconds; 0 disables
+
+
+#------------------------------------------------------------------------------
+# REPLICATION
+#------------------------------------------------------------------------------
+
+# - Master Server -
+
+# These settings are ignored on a standby server
+
+#max_wal_senders = 0           # max number of walsender processes
+                               # (change requires restart)
+#wal_sender_delay = 1s         # walsender cycle time, 1-10000 milliseconds
+#wal_keep_segments = 0         # in logfile segments, 16MB each; 0 disables
+#vacuum_defer_cleanup_age = 0  # number of xacts by which cleanup is delayed
+#replication_timeout = 60s     # in milliseconds; 0 disables
+#synchronous_standby_names = ''        # standby servers that provide sync rep
+                               # comma-separated list of application_name
+                               # from standby(s); '*' = all
+
+# - Standby Servers -
+
+# These settings are ignored on a master server
+
+#hot_standby = off                     # "on" allows queries during recovery
+                                       # (change requires restart)
+#max_standby_archive_delay = 30s       # max delay before canceling queries
+                                       # when reading WAL from archive;
+                                       # -1 allows indefinite delay
+max_standby_streaming_delay = 600s
+#max_standby_streaming_delay = 30s     # max delay before canceling queries
+                                       # when reading streaming WAL;
+                                       # -1 allows indefinite delay
+#wal_receiver_status_interval = 10s    # send replies at least this often
+                                       # 0 disables
+#hot_standby_feedback = off            # send info from standby to prevent
+                                       # query conflicts
+
+
+#------------------------------------------------------------------------------
+# QUERY TUNING
+#------------------------------------------------------------------------------
+
+# - Planner Method Configuration -
+
+#enable_bitmapscan = on
+#enable_hashagg = on
+#enable_hashjoin = on
+#enable_indexscan = on
+#enable_material = on
+#enable_mergejoin = on
+#enable_nestloop = on
+#enable_seqscan = on
+#enable_sort = on
+#enable_tidscan = on
+
+# - Planner Cost Constants -
+
+#seq_page_cost = 1.0                   # measured on an arbitrary scale
+#random_page_cost = 4.0                        # same scale as above
+#cpu_tuple_cost = 0.01                 # same scale as above
+#cpu_index_tuple_cost = 0.005          # same scale as above
+#cpu_operator_cost = 0.0025            # same scale as above
+#effective_cache_size = 128MB
+
+# - Genetic Query Optimizer -
+
+#geqo = on
+#geqo_threshold = 12
+#geqo_effort = 5                       # range 1-10
+#geqo_pool_size = 0                    # selects default based on effort
+#geqo_generations = 0                  # selects default based on effort
+#geqo_selection_bias = 2.0             # range 1.5-2.0
+#geqo_seed = 0.0                       # range 0.0-1.0
+
+# - Other Planner Options -
+
+#default_statistics_target = 100       # range 1-10000
+#constraint_exclusion = partition      # on, off, or partition
+#cursor_tuple_fraction = 0.1           # range 0.0-1.0
+#from_collapse_limit = 8
+#join_collapse_limit = 8               # 1 disables collapsing of explicit
+                                       # JOIN clauses
+
+
+#------------------------------------------------------------------------------
+# ERROR REPORTING AND LOGGING
+#------------------------------------------------------------------------------
+
+# - Where to Log -
+
+#log_destination = 'stderr'            # Valid values are combinations of
+                                       # stderr, csvlog, syslog, and eventlog,
+                                       # depending on platform.  csvlog
+                                       # requires logging_collector to be on.
+
+# This is used when logging to stderr:
+#logging_collector = off               # Enable capturing of stderr and csvlog
+                                       # into log files. Required to be on for
+                                       # csvlogs.
+                                       # (change requires restart)
+
+# These are only used if logging_collector is on:
+#log_directory = 'pg_log'              # directory where log files are written,
+                                       # can be absolute or relative to PGDATA
+#log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'       # log file name pattern,
+                                       # can include strftime() escapes
+#log_file_mode = 0600                  # creation mode for log files,
+                                       # begin with 0 to use octal notation
+#log_truncate_on_rotation = off                # If on, an existing log file with the
+                                       # same name as the new log file will be
+                                       # truncated rather than appended to.
+                                       # But such truncation only occurs on
+                                       # time-driven rotation, not on restarts
+                                       # or size-driven rotation.  Default is
+                                       # off, meaning append to existing files
+                                       # in all cases.
+#log_rotation_age = 1d                 # Automatic rotation of logfiles will
+                                       # happen after that time.  0 disables.
+#log_rotation_size = 10MB              # Automatic rotation of logfiles will
+                                       # happen after that much log output.
+                                       # 0 disables.
+
+# These are relevant when logging to syslog:
+#syslog_facility = 'LOCAL0'
+#syslog_ident = 'postgres'
+
+#silent_mode = off                     # Run server silently.
+                                       # DO NOT USE without syslog or
+                                       # logging_collector
+                                       # (change requires restart)
+
+
+# - When to Log -
+
+client_min_messages = notice           # values in order of decreasing detail:
+                                       #   debug5
+                                       #   debug4
+                                       #   debug3
+                                       #   debug2
+                                       #   debug1
+                                       #   log
+                                       #   notice
+                                       #   warning
+                                       #   error
+
+log_min_messages = warning             # values in order of decreasing detail:
+                                       #   debug5
+                                       #   debug4
+                                       #   debug3
+                                       #   debug2
+                                       #   debug1
+                                       #   info
+                                       #   notice
+                                       #   warning
+                                       #   error
+                                       #   log
+                                       #   fatal
+                                       #   panic
+
+log_min_error_statement = error        # values in order of decreasing detail:
+                                       #   debug5
+                                       #   debug4
+                                       #   debug3
+                                       #   debug2
+                                       #   debug1
+                                       #   info
+                                       #   notice
+                                       #   warning
+                                       #   error
+                                       #   log
+                                       #   fatal
+                                       #   panic (effectively off)
+
+log_min_duration_statement = 10000     # -1 is disabled, 0 logs all statements
+                                       # and their durations, > 0 logs only
+                                       # statements running at least this number
+                                       # of milliseconds
+
+
+# - What to Log -
+
+#debug_print_parse = off
+#debug_print_rewritten = off
+#debug_print_plan = off
+#debug_pretty_print = on
+#log_checkpoints = off
+#log_connections = off
+#log_disconnections = off
+#log_duration = off
+#log_error_verbosity = default         # terse, default, or verbose messages
+#log_hostname = off
+
+log_line_prefix = '{{ postgres_log_line_prefix }}'
+#log_line_prefix = '%t '               # special values:
+                                       #   %a = application name
+                                       #   %u = user name
+                                       #   %d = database name
+                                       #   %r = remote host and port
+                                       #   %h = remote host
+                                       #   %p = process ID
+                                       #   %t = timestamp without milliseconds
+                                       #   %m = timestamp with milliseconds
+                                       #   %i = command tag
+                                       #   %e = SQL state
+                                       #   %c = session ID
+                                       #   %l = session line number
+                                       #   %s = session start timestamp
+                                       #   %v = virtual transaction ID
+                                       #   %x = transaction ID (0 if none)
+                                       #   %q = stop here in non-session
+                                       #        processes
+                                       #   %% = '%'
+                                       # e.g. '<%u%%%d> '
+#log_lock_waits = off                  # log lock waits >= deadlock_timeout
+#log_statement = 'none'                        # none, ddl, mod, all
+#log_temp_files = -1                   # log temporary files equal or larger
+                                       # than the specified size in kilobytes;
+                                       # -1 disables, 0 logs all temp files
+log_timezone = 'GMT'
+
+
+#------------------------------------------------------------------------------
+# RUNTIME STATISTICS
+#------------------------------------------------------------------------------
+
+# - Query/Index Statistics Collector -
+
+#track_activities = on
+#track_counts = on
+#track_functions = none                        # none, pl, all
+#track_activity_query_size = 1024      # (change requires restart)
+#update_process_title = on
+stats_temp_directory = '/var/run/postgresql/{{ postgres_version }}-{{ postgres_cluster_name }}.pg_stat_tmp'
+
+
+# - Statistics Monitoring -
+
+#log_parser_stats = off
+#log_planner_stats = off
+#log_executor_stats = off
+#log_statement_stats = off
+
+
+#------------------------------------------------------------------------------
+# AUTOVACUUM PARAMETERS
+#------------------------------------------------------------------------------
+
+autovacuum = on                                # Enable autovacuum subprocess?  'on'
+                                       # requires track_counts to also be on.
+#log_autovacuum_min_duration = -1      # -1 disables, 0 logs all actions and
+                                       # their durations, > 0 logs only
+                                       # actions running at least this number
+                                       # of milliseconds.
+#autovacuum_max_workers = 3            # max number of autovacuum subprocesses
+                                       # (change requires restart)
+#autovacuum_naptime = 1min             # time between autovacuum runs
+#autovacuum_vacuum_threshold = 50      # min number of row updates before
+                                       # vacuum
+#autovacuum_analyze_threshold = 50     # min number of row updates before
+                                       # analyze
+#autovacuum_vacuum_scale_factor = 0.2  # fraction of table size before vacuum
+#autovacuum_analyze_scale_factor = 0.1 # fraction of table size before analyze
+#autovacuum_freeze_max_age = 200000000 # maximum XID age before forced vacuum
+                                       # (change requires restart)
+#autovacuum_vacuum_cost_delay = 20ms   # default vacuum cost delay for
+                                       # autovacuum, in milliseconds;
+                                       # -1 means use vacuum_cost_delay
+#autovacuum_vacuum_cost_limit = -1     # default vacuum cost limit for
+                                       # autovacuum, -1 means use
+                                       # vacuum_cost_limit
+
+
+#------------------------------------------------------------------------------
+# CLIENT CONNECTION DEFAULTS
+#------------------------------------------------------------------------------
+
+# - Statement Behavior -
+
+#search_path = '"$user",public'                # schema names
+#default_tablespace = ''               # a tablespace name, '' uses the default
+#temp_tablespaces = ''                 # a list of tablespace names, '' uses
+                                       # only default tablespace
+#check_function_bodies = on
+#default_transaction_isolation = 'read committed'
+#default_transaction_read_only = off
+#default_transaction_deferrable = off
+#session_replication_role = 'origin'
+#statement_timeout = 0                 # in milliseconds, 0 is disabled
+#vacuum_freeze_min_age = 50000000
+#vacuum_freeze_table_age = 150000000
+#bytea_output = 'hex'                  # hex, escape
+#xmlbinary = 'base64'
+#xmloption = 'content'
+
+# - Locale and Formatting -
+
+datestyle = '{{ postgres_datestyle }}'
+#intervalstyle = 'postgres'
+#timezone = '(defaults to server environment setting)'
+{% if postgres_timezone is defined %}
+timezone = '{{ postgres_timezone }}'
+{% endif %}
+#timezone_abbreviations = 'Default'     # Select the set of available time zone
+                                       # abbreviations.  Currently, there are
+                                       #   Default
+                                       #   Australia (historical usage)
+                                       #   India
+                                       # You can create your own file in
+                                       # share/timezonesets/.
+#extra_float_digits = 0                        # min -15, max 3
+#client_encoding = sql_ascii           # actually, defaults to database
+                                       # encoding
+
+# These settings are initialized by initdb, but they can be changed.
+lc_messages = '{{ postgres_locale_system }}'   # locale for system error message
+                                       # strings
+lc_monetary = '{{ postgres_locale_formats }}'  # locale for monetary formatting
+lc_numeric = '{{ postgres_locale_formats }}'   # locale for number formatting
+lc_time = '{{ postgres_locale_formats }}'      # locale for time formatting
+
+# default configuration for text search
+default_text_search_config = '{{ postgres_text_search_config }}'
+
+# - Other Defaults -
+
+#dynamic_library_path = '$libdir'
+#local_preload_libraries = ''
+
+
+#------------------------------------------------------------------------------
+# LOCK MANAGEMENT
+#------------------------------------------------------------------------------
+
+#deadlock_timeout = 1s
+#max_locks_per_transaction = 64                # min 10
+                                       # (change requires restart)
+# Note:  Each lock table slot uses ~270 bytes of shared memory, and there are
+# max_locks_per_transaction * (max_connections + max_prepared_transactions)
+# lock table slots.
+#max_pred_locks_per_transaction = 64   # min 10
+                                       # (change requires restart)
+
+#------------------------------------------------------------------------------
+# VERSION/PLATFORM COMPATIBILITY
+#------------------------------------------------------------------------------
+
+# - Previous PostgreSQL Versions -
+
+#array_nulls = on
+#backslash_quote = safe_encoding       # on, off, or safe_encoding
+#default_with_oids = off
+#escape_string_warning = on
+#lo_compat_privileges = off
+#quote_all_identifiers = off
+#sql_inheritance = on
+#standard_conforming_strings = on
+#synchronize_seqscans = on
+
+# - Other Platforms and Clients -
+
+#transform_null_equals = off
+
+
+#------------------------------------------------------------------------------
+# ERROR HANDLING
+#------------------------------------------------------------------------------
+
+#exit_on_error = off                           # terminate session on any error?
+#restart_after_crash = on                      # reinitialize after backend crash?
+
+
+#------------------------------------------------------------------------------
+# CUSTOMIZED OPTIONS
+#------------------------------------------------------------------------------
+
+#custom_variable_classes = ''          # list of custom variable class names
diff --git a/templates/postgresql.9.4.conf.j2 b/templates/postgresql.9.4.conf.j2
new file mode 100644 (file)
index 0000000..c251bfa
--- /dev/null
@@ -0,0 +1,647 @@
+# {{ ansible_managed }}
+# -----------------------------
+# PostgreSQL configuration file
+# -----------------------------
+#
+# This file consists of lines of the form:
+#
+#   name = value
+#
+# (The "=" is optional.)  Whitespace may be used.  Comments are introduced with
+# "#" anywhere on a line.  The complete list of parameter names and allowed
+# values can be found in the PostgreSQL documentation.
+#
+# The commented-out settings shown in this file represent the default values.
+# Re-commenting a setting is NOT sufficient to revert it to the default value;
+# you need to reload the server.
+#
+# This file is read on server startup and when the server receives a SIGHUP
+# signal.  If you edit the file on a running system, you have to SIGHUP the
+# server for the changes to take effect, or use "pg_ctl reload".  Some
+# parameters, which are marked below, require a server shutdown and restart to
+# take effect.
+#
+# Any parameter can also be given as a command-line option to the server, e.g.,
+# "postgres -c log_connections=on".  Some parameters can be changed at run time
+# with the "SET" SQL command.
+#
+# Memory units:  kB = kilobytes        Time units:  ms  = milliseconds
+#                MB = megabytes                     s   = seconds
+#                GB = gigabytes                     min = minutes
+#                TB = terabytes                     h   = hours
+#                                                   d   = days
+
+
+#------------------------------------------------------------------------------
+# FILE LOCATIONS
+#------------------------------------------------------------------------------
+
+# The default values of these variables are driven from the -D command-line
+# option or PGDATA environment variable, represented here as ConfigDir.
+
+data_directory = '/var/lib/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}'              # use data in another directory
+                                       # (change requires restart)
+hba_file = '/etc/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/pg_hba.conf'    # host-based authentication file
+                                       # (change requires restart)
+ident_file = '/etc/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/pg_ident.conf'        # ident configuration file
+                                       # (change requires restart)
+
+# If external_pid_file is not explicitly set, no extra PID file is written.
+external_pid_file = '/var/run/postgresql/{{ postgres_version }}-{{ postgres_cluster_name }}.pid'               # write an extra PID file
+                                       # (change requires restart)
+
+
+#------------------------------------------------------------------------------
+# CONNECTIONS AND AUTHENTICATION
+#------------------------------------------------------------------------------
+
+# - Connection Settings -
+
+listen_addresses = '{{ postgres_listen_addresses | reject("none") | join(",") }}' # what IP address(es) to listen on;
+                                       # comma-separated list of addresses;
+                                       # defaults to 'localhost'; use '*' for all
+                                       # (change requires restart)
+port = {{ postgres_port }}                             # (change requires restart)
+max_connections = 400                  # (change requires restart)
+# Note:  Increasing max_connections costs ~400 bytes of shared memory per
+# connection slot, plus lock space (see max_locks_per_transaction).
+#superuser_reserved_connections = 3    # (change requires restart)
+unix_socket_directories = '/var/run/postgresql'        # comma-separated list of directories
+                                       # (change requires restart)
+#unix_socket_group = ''                        # (change requires restart)
+#unix_socket_permissions = 0777                # begin with 0 to use octal notation
+                                       # (change requires restart)
+#bonjour = off                         # advertise server via Bonjour
+                                       # (change requires restart)
+#bonjour_name = ''                     # defaults to the computer name
+                                       # (change requires restart)
+
+# - Security and Authentication -
+
+#authentication_timeout = 1min         # 1s-600s
+ssl = true                             # (change requires restart)
+#ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL' # allowed SSL ciphers
+                                       # (change requires restart)
+#ssl_prefer_server_ciphers = on                # (change requires restart)
+#ssl_ecdh_curve = 'prime256v1'         # (change requires restart)
+#ssl_renegotiation_limit = 512MB       # amount of data between renegotiations
+ssl_cert_file = '/etc/ssl/certs/ssl-cert-snakeoil.pem'         # (change requires restart)
+ssl_key_file = '/etc/ssl/private/ssl-cert-snakeoil.key'                # (change requires restart)
+#ssl_ca_file = ''                      # (change requires restart)
+#ssl_crl_file = ''                     # (change requires restart)
+#password_encryption = on
+#db_user_namespace = off
+
+# GSSAPI using Kerberos
+#krb_server_keyfile = ''
+#krb_caseins_users = off
+
+# - TCP Keepalives -
+# see "man 7 tcp" for details
+
+#tcp_keepalives_idle = 0               # TCP_KEEPIDLE, in seconds;
+                                       # 0 selects the system default
+#tcp_keepalives_interval = 0           # TCP_KEEPINTVL, in seconds;
+                                       # 0 selects the system default
+#tcp_keepalives_count = 0              # TCP_KEEPCNT;
+                                       # 0 selects the system default
+
+
+#------------------------------------------------------------------------------
+# RESOURCE USAGE (except WAL)
+#------------------------------------------------------------------------------
+
+# - Memory -
+
+{% if ansible_memtotal_mb > 65536 %}
+shared_buffers = 16GB                  # min 128kB
+{% else %}
+shared_buffers = {{ ansible_memtotal_mb // 4 }}MB                      # min 128kB
+{% endif %}
+                                       # (change requires restart)
+#huge_pages = try                      # on, off, or try
+                                       # (change requires restart)
+#temp_buffers = 8MB                    # min 800kB
+#max_prepared_transactions = 0         # zero disables the feature
+                                       # (change requires restart)
+# Note:  Increasing max_prepared_transactions costs ~600 bytes of shared memory
+# per transaction slot, plus lock space (see max_locks_per_transaction).
+# It is not advisable to set max_prepared_transactions nonzero unless you
+# actively intend to use prepared transactions.
+#work_mem = 4MB                                # min 64kB
+#maintenance_work_mem = 64MB           # min 1MB
+#autovacuum_work_mem = -1              # min 1MB, or -1 to use maintenance_work_mem
+#max_stack_depth = 2MB                 # min 100kB
+dynamic_shared_memory_type = posix     # the default is the first option
+                                       # supported by the operating system:
+                                       #   posix
+                                       #   sysv
+                                       #   windows
+                                       #   mmap
+                                       # use none to disable dynamic shared memory
+
+# - Disk -
+
+#temp_file_limit = -1                  # limits per-session temp file space
+                                       # in kB, or -1 for no limit
+
+# - Kernel Resource Usage -
+
+#max_files_per_process = 1000          # min 25
+                                       # (change requires restart)
+#shared_preload_libraries = ''         # (change requires restart)
+
+# - Cost-Based Vacuum Delay -
+
+#vacuum_cost_delay = 0                 # 0-100 milliseconds
+#vacuum_cost_page_hit = 1              # 0-10000 credits
+#vacuum_cost_page_miss = 10            # 0-10000 credits
+#vacuum_cost_page_dirty = 20           # 0-10000 credits
+#vacuum_cost_limit = 200               # 1-10000 credits
+
+# - Background Writer -
+
+#bgwriter_delay = 200ms                        # 10-10000ms between rounds
+#bgwriter_lru_maxpages = 100           # 0-1000 max buffers written/round
+#bgwriter_lru_multiplier = 2.0         # 0-10.0 multipler on buffers scanned/round
+
+# - Asynchronous Behavior -
+
+#effective_io_concurrency = 1          # 1-1000; 0 disables prefetching
+#max_worker_processes = 8
+
+
+#------------------------------------------------------------------------------
+# WRITE AHEAD LOG
+#------------------------------------------------------------------------------
+
+# - Settings -
+
+wal_level = logical                    # minimal, archive, hot_standby, or logical
+                                       # (change requires restart)
+
+{% if postgres_fsync_enabled %}
+#fsync = on                            # turns forced synchronization on or off
+#synchronous_commit = on               # synchronization level;
+{% else %}
+fsync = off                            # turns forced synchronization on or off
+synchronous_commit = off               # synchronization level;
+{% endif %}
+                                       # off, local, remote_write, or on
+#wal_sync_method = fsync               # the default is the first option
+                                       # supported by the operating system:
+                                       #   open_datasync
+                                       #   fdatasync (default on Linux)
+                                       #   fsync
+                                       #   fsync_writethrough
+                                       #   open_sync
+#full_page_writes = on                 # recover from partial page writes
+wal_log_hints = on                     # also do full page writes of non-critical updates
+                                       # (change requires restart)
+#wal_buffers = -1                      # min 32kB, -1 sets based on shared_buffers
+                                       # (change requires restart)
+#wal_writer_delay = 200ms              # 1-10000 milliseconds
+
+#commit_delay = 0                      # range 0-100000, in microseconds
+#commit_siblings = 5                   # range 1-1000
+
+# - Checkpoints -
+
+#checkpoint_segments = 3               # in logfile segments, min 1, 16MB each
+#checkpoint_timeout = 5min             # range 30s-1h
+#checkpoint_completion_target = 0.5    # checkpoint target duration, 0.0 - 1.0
+#checkpoint_warning = 30s              # 0 disables
+
+# - Archiving -
+
+{% if postgres_archive_enabled %}
+archive_mode = on
+archive_command = 'rsync -a %p barman@{{ postgres_barman_server }}:/var/lib/barman/{{ barman_directory }}/incoming/%f'
+{% else %}
+archive_mode = off
+archive_command = ''
+{% endif %}
+
+#archive_mode = off            # enables archiving; off, on, or always
+                               # (change requires restart)
+#archive_command = ''          # command to use to archive a logfile segment
+                               # placeholders: %p = path of file to archive
+                               #               %f = file name only
+                               # e.g. 'test ! -f /mnt/server/archivedir/%f && cp %p /mnt/server/archivedir/%f'
+#archive_timeout = 0           # force a logfile segment switch after this
+                               # number of seconds; 0 disables
+
+
+#------------------------------------------------------------------------------
+# REPLICATION
+#------------------------------------------------------------------------------
+
+# - Sending Server(s) -
+
+# Set these on the master and on any standby that will send replication data.
+
+max_wal_senders = 5            # max number of walsender processes
+                               # (change requires restart)
+wal_keep_segments = 16         # in logfile segments, 16MB each; 0 disables
+#wal_sender_timeout = 60s      # in milliseconds; 0 disables
+
+{% if postgres_max_replication_slots is defined %}
+max_replication_slots = {{ postgres_max_replication_slots }} # max number of replication slots
+{% else %}
+#max_replication_slots = 0     # max number of replication slots
+{% endif %}
+                               # (change requires restart)
+
+# - Master Server -
+
+# These settings are ignored on a standby server.
+
+#synchronous_standby_names = ''        # standby servers that provide sync rep
+                               # comma-separated list of application_name
+                               # from standby(s); '*' = all
+#vacuum_defer_cleanup_age = 0  # number of xacts by which cleanup is delayed
+
+# - Standby Servers -
+
+# These settings are ignored on a master server.
+
+hot_standby = on                       # "on" allows queries during recovery
+                                       # (change requires restart)
+#max_standby_archive_delay = 30s       # max delay before canceling queries
+                                       # when reading WAL from archive;
+                                       # -1 allows indefinite delay
+max_standby_streaming_delay = {{ postgres_extra_config.max_standby_streaming_delay | default('600s') }}        # max delay before canceling queries
+                                       # when reading streaming WAL;
+                                       # -1 allows indefinite delay
+#wal_receiver_status_interval = 10s    # send replies at least this often
+                                       # 0 disables
+#hot_standby_feedback = off            # send info from standby to prevent
+                                       # query conflicts
+#wal_receiver_timeout = 60s            # time that receiver waits for
+                                       # communication from master
+                                       # in milliseconds; 0 disables
+
+
+#------------------------------------------------------------------------------
+# QUERY TUNING
+#------------------------------------------------------------------------------
+
+# - Planner Method Configuration -
+
+#enable_bitmapscan = on
+#enable_hashagg = on
+#enable_hashjoin = on
+#enable_indexscan = on
+#enable_indexonlyscan = on
+#enable_material = on
+#enable_mergejoin = on
+#enable_nestloop = on
+#enable_seqscan = on
+#enable_sort = on
+#enable_tidscan = on
+
+# - Planner Cost Constants -
+
+#seq_page_cost = 1.0                   # measured on an arbitrary scale
+{% if postgres_specific_random_page_cost is defined -%}
+# Random page cost is an arbitrary value relative to the seq_page_cost conf (default 1.0)
+# On SSD disk it is better to lower the default value from 4.0 to 1.0 for instance.
+random_page_cost = {{ postgres_specific_random_page_cost }}                    # same scale as above
+{% else -%}
+#random_page_cost = 4.0                        # same scale as above
+{% endif %}
+#cpu_tuple_cost = 0.01                 # same scale as above
+#cpu_index_tuple_cost = 0.005          # same scale as above
+#cpu_operator_cost = 0.0025            # same scale as above
+effective_cache_size = {{ ansible_memtotal_mb // 2 }}MB
+
+# - Genetic Query Optimizer -
+
+#geqo = on
+#geqo_threshold = 12
+#geqo_effort = 5                       # range 1-10
+#geqo_pool_size = 0                    # selects default based on effort
+#geqo_generations = 0                  # selects default based on effort
+#geqo_selection_bias = 2.0             # range 1.5-2.0
+#geqo_seed = 0.0                       # range 0.0-1.0
+
+# - Other Planner Options -
+
+#default_statistics_target = 100       # range 1-10000
+#constraint_exclusion = partition      # on, off, or partition
+#cursor_tuple_fraction = 0.1           # range 0.0-1.0
+#from_collapse_limit = 8
+#join_collapse_limit = 8               # 1 disables collapsing of explicit
+                                       # JOIN clauses
+
+
+#------------------------------------------------------------------------------
+# ERROR REPORTING AND LOGGING
+#------------------------------------------------------------------------------
+
+# - Where to Log -
+
+#log_destination = 'stderr'            # Valid values are combinations of
+                                       # stderr, csvlog, syslog, and eventlog,
+                                       # depending on platform.  csvlog
+                                       # requires logging_collector to be on.
+
+# This is used when logging to stderr:
+#logging_collector = off               # Enable capturing of stderr and csvlog
+                                       # into log files. Required to be on for
+                                       # csvlogs.
+                                       # (change requires restart)
+
+# These are only used if logging_collector is on:
+#log_directory = 'pg_log'              # directory where log files are written,
+                                       # can be absolute or relative to PGDATA
+#log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'       # log file name pattern,
+                                       # can include strftime() escapes
+#log_file_mode = 0600                  # creation mode for log files,
+                                       # begin with 0 to use octal notation
+#log_truncate_on_rotation = off                # If on, an existing log file with the
+                                       # same name as the new log file will be
+                                       # truncated rather than appended to.
+                                       # But such truncation only occurs on
+                                       # time-driven rotation, not on restarts
+                                       # or size-driven rotation.  Default is
+                                       # off, meaning append to existing files
+                                       # in all cases.
+#log_rotation_age = 1d                 # Automatic rotation of logfiles will
+                                       # happen after that time.  0 disables.
+#log_rotation_size = 10MB              # Automatic rotation of logfiles will
+                                       # happen after that much log output.
+                                       # 0 disables.
+
+# These are relevant when logging to syslog:
+#syslog_facility = 'LOCAL0'
+#syslog_ident = 'postgres'
+
+# This is only relevant when logging to eventlog (win32):
+#event_source = 'PostgreSQL'
+
+# - When to Log -
+
+#client_min_messages = notice          # values in order of decreasing detail:
+                                       #   debug5
+                                       #   debug4
+                                       #   debug3
+                                       #   debug2
+                                       #   debug1
+                                       #   log
+                                       #   notice
+                                       #   warning
+                                       #   error
+
+#log_min_messages = warning            # values in order of decreasing detail:
+                                       #   debug5
+                                       #   debug4
+                                       #   debug3
+                                       #   debug2
+                                       #   debug1
+                                       #   info
+                                       #   notice
+                                       #   warning
+                                       #   error
+                                       #   log
+                                       #   fatal
+                                       #   panic
+
+#log_min_error_statement = error       # values in order of decreasing detail:
+                                       #   debug5
+                                       #   debug4
+                                       #   debug3
+                                       #   debug2
+                                       #   debug1
+                                       #   info
+                                       #   notice
+                                       #   warning
+                                       #   error
+                                       #   log
+                                       #   fatal
+                                       #   panic (effectively off)
+
+log_min_duration_statement = 10000     # -1 is disabled, 0 logs all statements
+                                       # and their durations, > 0 logs only
+                                       # statements running at least this number
+                                       # of milliseconds
+
+
+# - What to Log -
+
+#debug_print_parse = off
+#debug_print_rewritten = off
+#debug_print_plan = off
+#debug_pretty_print = on
+#log_checkpoints = off
+#log_connections = off
+#log_disconnections = off
+#log_duration = off
+#log_error_verbosity = default         # terse, default, or verbose messages
+#log_hostname = off
+
+log_line_prefix = '{{ postgres_log_line_prefix }}'
+#log_line_prefix = '%t '               # special values:
+                                       #   %a = application name
+                                       #   %u = user name
+                                       #   %d = database name
+                                       #   %r = remote host and port
+                                       #   %h = remote host
+                                       #   %p = process ID
+                                       #   %t = timestamp without milliseconds
+                                       #   %m = timestamp with milliseconds
+                                       #   %i = command tag
+                                       #   %e = SQL state
+                                       #   %c = session ID
+                                       #   %l = session line number
+                                       #   %s = session start timestamp
+                                       #   %v = virtual transaction ID
+                                       #   %x = transaction ID (0 if none)
+                                       #   %q = stop here in non-session
+                                       #        processes
+                                       #   %% = '%'
+                                       # e.g. '<%u%%%d> '
+#log_lock_waits = off                  # log lock waits >= deadlock_timeout
+#log_statement = 'none'                        # none, ddl, mod, all
+#log_temp_files = -1                   # log temporary files equal or larger
+                                       # than the specified size in kilobytes;
+                                       # -1 disables, 0 logs all temp files
+log_timezone = 'GMT'
+
+
+#------------------------------------------------------------------------------
+# RUNTIME STATISTICS
+#------------------------------------------------------------------------------
+
+# - Query/Index Statistics Collector -
+
+#track_activities = on
+#track_counts = on
+#track_io_timing = off
+#track_functions = none                        # none, pl, all
+#track_activity_query_size = 1024      # (change requires restart)
+stats_temp_directory = '/var/run/postgresql/{{ postgres_version }}-{{ postgres_cluster_name }}.pg_stat_tmp'
+
+
+# - Statistics Monitoring -
+
+#log_parser_stats = off
+#log_planner_stats = off
+#log_executor_stats = off
+#log_statement_stats = off
+
+
+#------------------------------------------------------------------------------
+# AUTOVACUUM PARAMETERS
+#------------------------------------------------------------------------------
+
+#autovacuum = on                       # Enable autovacuum subprocess?  'on'
+                                       # requires track_counts to also be on.
+#log_autovacuum_min_duration = -1      # -1 disables, 0 logs all actions and
+                                       # their durations, > 0 logs only
+                                       # actions running at least this number
+                                       # of milliseconds.
+#autovacuum_max_workers = 3            # max number of autovacuum subprocesses
+                                       # (change requires restart)
+#autovacuum_naptime = 1min             # time between autovacuum runs
+#autovacuum_vacuum_threshold = 50      # min number of row updates before
+                                       # vacuum
+#autovacuum_analyze_threshold = 50     # min number of row updates before
+                                       # analyze
+#autovacuum_vacuum_scale_factor = 0.2  # fraction of table size before vacuum
+#autovacuum_analyze_scale_factor = 0.1 # fraction of table size before analyze
+#autovacuum_freeze_max_age = 200000000 # maximum XID age before forced vacuum
+                                       # (change requires restart)
+#autovacuum_multixact_freeze_max_age = 400000000       # maximum multixact age
+                                       # before forced vacuum
+                                       # (change requires restart)
+#autovacuum_vacuum_cost_delay = 20ms   # default vacuum cost delay for
+                                       # autovacuum, in milliseconds;
+                                       # -1 means use vacuum_cost_delay
+#autovacuum_vacuum_cost_limit = -1     # default vacuum cost limit for
+                                       # autovacuum, -1 means use
+                                       # vacuum_cost_limit
+
+
+#------------------------------------------------------------------------------
+# CLIENT CONNECTION DEFAULTS
+#------------------------------------------------------------------------------
+
+# - Statement Behavior -
+
+#search_path = '"$user",public'                # schema names
+#default_tablespace = ''               # a tablespace name, '' uses the default
+#temp_tablespaces = ''                 # a list of tablespace names, '' uses
+                                       # only default tablespace
+#check_function_bodies = on
+#default_transaction_isolation = 'read committed'
+#default_transaction_read_only = off
+#default_transaction_deferrable = off
+#session_replication_role = 'origin'
+#statement_timeout = 0                 # in milliseconds, 0 is disabled
+#lock_timeout = 0                      # in milliseconds, 0 is disabled
+#vacuum_freeze_min_age = 50000000
+#vacuum_freeze_table_age = 150000000
+#vacuum_multixact_freeze_min_age = 5000000
+#vacuum_multixact_freeze_table_age = 150000000
+#bytea_output = 'hex'                  # hex, escape
+#xmlbinary = 'base64'
+#xmloption = 'content'
+
+# - Locale and Formatting -
+
+datestyle = '{{ postgres_datestyle }}'
+#intervalstyle = 'postgres'
+#timezone = '(defaults to server environment setting)'
+{% if postgres_timezone is defined %}
+timezone = '{{ postgres_timezone }}'
+{% endif %}
+#timezone_abbreviations = 'Default'     # Select the set of available time zone
+                                       # abbreviations.  Currently, there are
+                                       #   Default
+                                       #   Australia (historical usage)
+                                       #   India
+                                       # You can create your own file in
+                                       # share/timezonesets/.
+#extra_float_digits = 0                        # min -15, max 3
+#client_encoding = sql_ascii           # actually, defaults to database
+                                       # encoding
+
+# These settings are initialized by initdb, but they can be changed.
+lc_messages = '{{ postgres_locale_system }}'   # locale for system error message
+                                       # strings
+lc_monetary = '{{ postgres_locale_formats }}'  # locale for monetary formatting
+lc_numeric = '{{ postgres_locale_formats }}'   # locale for number formatting
+lc_time = '{{ postgres_locale_formats }}'      # locale for time formatting
+
+# default configuration for text search
+default_text_search_config = '{{ postgres_text_search_config }}'
+
+# - Other Defaults -
+
+#dynamic_library_path = '$libdir'
+#local_preload_libraries = ''
+#session_preload_libraries = ''
+
+
+#------------------------------------------------------------------------------
+# LOCK MANAGEMENT
+#------------------------------------------------------------------------------
+
+#deadlock_timeout = 1s
+#max_locks_per_transaction = 64                # min 10
+                                       # (change requires restart)
+# Note:  Each lock table slot uses ~270 bytes of shared memory, and there are
+# max_locks_per_transaction * (max_connections + max_prepared_transactions)
+# lock table slots.
+#max_pred_locks_per_transaction = 64   # min 10
+                                       # (change requires restart)
+
+
+#------------------------------------------------------------------------------
+# VERSION/PLATFORM COMPATIBILITY
+#------------------------------------------------------------------------------
+
+# - Previous PostgreSQL Versions -
+
+#array_nulls = on
+#backslash_quote = safe_encoding       # on, off, or safe_encoding
+#default_with_oids = off
+#escape_string_warning = on
+#lo_compat_privileges = off
+#quote_all_identifiers = off
+#sql_inheritance = on
+#standard_conforming_strings = on
+#synchronize_seqscans = on
+
+# - Other Platforms and Clients -
+
+#transform_null_equals = off
+
+
+#------------------------------------------------------------------------------
+# ERROR HANDLING
+#------------------------------------------------------------------------------
+
+#exit_on_error = off                   # terminate session on any error?
+#restart_after_crash = on              # reinitialize after backend crash?
+
+
+#------------------------------------------------------------------------------
+# CONFIG FILE INCLUDES
+#------------------------------------------------------------------------------
+
+# These options allow settings to be loaded from files other than the
+# default postgresql.conf.
+
+#include_dir = 'conf.d'                        # include files ending in '.conf' from
+                                       # directory 'conf.d'
+#include_if_exists = 'exists.conf'     # include file only if it exists
+#include = 'special.conf'              # include file
+
+
+#------------------------------------------------------------------------------
+# CUSTOMIZED OPTIONS
+#------------------------------------------------------------------------------
+
+# Add settings for extensions here
diff --git a/templates/postgresql.9.5.conf.j2 b/templates/postgresql.9.5.conf.j2
new file mode 100644 (file)
index 0000000..5f666bf
--- /dev/null
@@ -0,0 +1,657 @@
+# {{ ansible_managed }}
+# -----------------------------
+# PostgreSQL configuration file
+# -----------------------------
+#
+# This file consists of lines of the form:
+#
+#   name = value
+#
+# (The "=" is optional.)  Whitespace may be used.  Comments are introduced with
+# "#" anywhere on a line.  The complete list of parameter names and allowed
+# values can be found in the PostgreSQL documentation.
+#
+# The commented-out settings shown in this file represent the default values.
+# Re-commenting a setting is NOT sufficient to revert it to the default value;
+# you need to reload the server.
+#
+# This file is read on server startup and when the server receives a SIGHUP
+# signal.  If you edit the file on a running system, you have to SIGHUP the
+# server for the changes to take effect, or use "pg_ctl reload".  Some
+# parameters, which are marked below, require a server shutdown and restart to
+# take effect.
+#
+# Any parameter can also be given as a command-line option to the server, e.g.,
+# "postgres -c log_connections=on".  Some parameters can be changed at run time
+# with the "SET" SQL command.
+#
+# Memory units:  kB = kilobytes        Time units:  ms  = milliseconds
+#                MB = megabytes                     s   = seconds
+#                GB = gigabytes                     min = minutes
+#                TB = terabytes                     h   = hours
+#                                                   d   = days
+
+
+#------------------------------------------------------------------------------
+# FILE LOCATIONS
+#------------------------------------------------------------------------------
+
+# The default values of these variables are driven from the -D command-line
+# option or PGDATA environment variable, represented here as ConfigDir.
+
+data_directory = '/var/lib/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}'              # use data in another directory
+                                       # (change requires restart)
+hba_file = '/etc/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/pg_hba.conf'    # host-based authentication file
+                                       # (change requires restart)
+ident_file = '/etc/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/pg_ident.conf'        # ident configuration file
+                                       # (change requires restart)
+
+# If external_pid_file is not explicitly set, no extra PID file is written.
+external_pid_file = '/var/run/postgresql/{{ postgres_version }}-{{ postgres_cluster_name }}.pid'               # write an extra PID file
+                                       # (change requires restart)
+
+
+#------------------------------------------------------------------------------
+# CONNECTIONS AND AUTHENTICATION
+#------------------------------------------------------------------------------
+
+# - Connection Settings -
+
+listen_addresses = '{{ postgres_listen_addresses | reject("none") | join(",") }}' # what IP address(es) to listen on;
+                                       # comma-separated list of addresses;
+                                       # defaults to 'localhost'; use '*' for all
+                                       # (change requires restart)
+port = {{ postgres_port }}                             # (change requires restart)
+max_connections = 400                  # (change requires restart)
+# Note:  Increasing max_connections costs ~400 bytes of shared memory per
+# connection slot, plus lock space (see max_locks_per_transaction).
+#superuser_reserved_connections = 3    # (change requires restart)
+unix_socket_directories = '/var/run/postgresql'        # comma-separated list of directories
+                                       # (change requires restart)
+#unix_socket_group = ''                        # (change requires restart)
+#unix_socket_permissions = 0777                # begin with 0 to use octal notation
+                                       # (change requires restart)
+#bonjour = off                         # advertise server via Bonjour
+                                       # (change requires restart)
+#bonjour_name = ''                     # defaults to the computer name
+                                       # (change requires restart)
+
+# - Security and Authentication -
+
+#authentication_timeout = 1min         # 1s-600s
+ssl = true                             # (change requires restart)
+#ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL' # allowed SSL ciphers
+                                       # (change requires restart)
+#ssl_prefer_server_ciphers = on                # (change requires restart)
+#ssl_ecdh_curve = 'prime256v1'         # (change requires restart)
+#ssl_cert_file = '/etc/ssl/certs/ssl-cert-snakeoil.pem'                # (change requires restart)
+# Default will be $PGDATA/server.pem
+#ssl_key_file = '/etc/ssl/private/ssl-cert-snakeoil.key'               # (change requires restart)
+# Default will be $PGDATA/server.key
+#ssl_ca_file = ''                      # (change requires restart)
+#ssl_crl_file = ''                     # (change requires restart)
+#password_encryption = on
+#db_user_namespace = off
+#row_security = on
+
+# GSSAPI using Kerberos
+#krb_server_keyfile = ''
+#krb_caseins_users = off
+
+# - TCP Keepalives -
+# see "man 7 tcp" for details
+
+#tcp_keepalives_idle = 0               # TCP_KEEPIDLE, in seconds;
+                                       # 0 selects the system default
+#tcp_keepalives_interval = 0           # TCP_KEEPINTVL, in seconds;
+                                       # 0 selects the system default
+#tcp_keepalives_count = 0              # TCP_KEEPCNT;
+                                       # 0 selects the system default
+
+
+#------------------------------------------------------------------------------
+# RESOURCE USAGE (except WAL)
+#------------------------------------------------------------------------------
+
+# - Memory -
+
+{% if ansible_memtotal_mb > 65536 %}
+shared_buffers = 16GB                  # min 128kB
+{% else %}
+shared_buffers = {{ ansible_memtotal_mb // 4 }}MB                      # min 128kB
+{% endif %}
+                                       # (change requires restart)
+temp_buffers = 24MB                    # min 800kB
+#max_prepared_transactions = 0         # zero disables the feature
+                                       # (change requires restart)
+# Note:  Increasing max_prepared_transactions costs ~600 bytes of shared memory
+# per transaction slot, plus lock space (see max_locks_per_transaction).
+# It is not advisable to set max_prepared_transactions nonzero unless you
+# actively intend to use prepared transactions.
+work_mem = 512MB                               # min 64kB
+maintenance_work_mem = 1024MB          # min 1MB
+#autovacuum_work_mem = -1              # min 1MB, or -1 to use maintenance_work_mem
+#max_stack_depth = 2MB                 # min 100kB
+dynamic_shared_memory_type = posix     # the default is the first option
+                                       # supported by the operating system:
+                                       #   posix
+                                       #   sysv
+                                       #   windows
+                                       #   mmap
+                                       # use none to disable dynamic shared memory
+
+# - Disk -
+
+#temp_file_limit = -1                  # limits per-session temp file space
+                                       # in kB, or -1 for no limit
+
+# - Kernel Resource Usage -
+
+#max_files_per_process = 1000          # min 25
+                                       # (change requires restart)
+#shared_preload_libraries = ''         # (change requires restart)
+
+# - Cost-Based Vacuum Delay -
+
+#vacuum_cost_delay = 0                 # 0-100 milliseconds
+#vacuum_cost_page_hit = 1              # 0-10000 credits
+#vacuum_cost_page_miss = 10            # 0-10000 credits
+#vacuum_cost_page_dirty = 20           # 0-10000 credits
+#vacuum_cost_limit = 200               # 1-10000 credits
+
+# - Background Writer -
+
+bgwriter_delay = 2000ms                        # 10-10000ms between rounds
+#bgwriter_lru_maxpages = 100           # 0-1000 max buffers written/round
+#bgwriter_lru_multiplier = 2.0         # 0-10.0 multipler on buffers scanned/round
+
+# - Asynchronous Behavior -
+
+#effective_io_concurrency = 1          # 1-1000; 0 disables prefetching
+#max_worker_processes = 8
+
+
+#------------------------------------------------------------------------------
+# WRITE AHEAD LOG
+#------------------------------------------------------------------------------
+
+# - Settings -
+
+wal_level = logical                    # minimal, archive, hot_standby, or logical
+                                       # (change requires restart)
+
+{% if postgres_fsync_enabled %}
+#fsync = on                            # turns forced synchronization on or off
+#synchronous_commit = on               # synchronization level;
+{% else %}
+fsync = off                            # turns forced synchronization on or off
+synchronous_commit = off               # synchronization level;
+{% endif %}
+                                       # off, local, remote_write, or on
+#wal_sync_method = fsync               # the default is the first option
+                                       # supported by the operating system:
+                                       #   open_datasync
+                                       #   fdatasync (default on Linux)
+                                       #   fsync
+                                       #   fsync_writethrough
+                                       #   open_sync
+#full_page_writes = on                 # recover from partial page writes
+#wal_compression = off                 # enable compression of full-page writes
+wal_log_hints = on                     # also do full page writes of non-critical updates
+                                       # (change requires restart)
+#wal_buffers = -1                      # min 32kB, -1 sets based on shared_buffers
+                                       # (change requires restart)
+#wal_writer_delay = 200ms              # 1-10000 milliseconds
+
+#commit_delay = 0                      # range 0-100000, in microseconds
+#commit_siblings = 5                   # range 1-1000
+
+# - Checkpoints -
+
+#checkpoint_timeout = 5min             # range 30s-1h
+#max_wal_size = 1GB
+#min_wal_size = 80MB
+#checkpoint_completion_target = 0.5    # checkpoint target duration, 0.0 - 1.0
+#checkpoint_warning = 30s              # 0 disables
+
+# - Archiving -
+
+{% if postgres_archive_enabled %}
+archive_mode = on
+archive_command = 'rsync -a %p barman@{{ postgres_barman_server }}:/var/lib/barman/{{ barman_directory }}/incoming/%f'
+{% else %}
+archive_mode = off
+archive_command = ''
+{% endif %}
+
+#archive_mode = off            # enables archiving; off, on, or always
+                               # (change requires restart)
+#archive_command = ''          # command to use to archive a logfile segment
+                               # placeholders: %p = path of file to archive
+                               #               %f = file name only
+                               # e.g. 'test ! -f /mnt/server/archivedir/%f && cp %p /mnt/server/archivedir/%f'
+#archive_timeout = 0           # force a logfile segment switch after this
+                               # number of seconds; 0 disables
+
+
+#------------------------------------------------------------------------------
+# REPLICATION
+#------------------------------------------------------------------------------
+
+# - Sending Server(s) -
+
+# Set these on the master and on any standby that will send replication data.
+
+max_wal_senders = 5            # max number of walsender processes
+                               # (change requires restart)
+wal_keep_segments = 16         # in logfile segments, 16MB each; 0 disables
+#wal_sender_timeout = 60s      # in milliseconds; 0 disables
+
+{% if postgres_max_replication_slots is defined %}
+max_replication_slots = {{ postgres_max_replication_slots }} # max number of replication slots
+{% else %}
+#max_replication_slots = 0     # max number of replication slots
+{% endif %}
+                               # (change requires restart)
+#track_commit_timestamp = off  # collect timestamp of transaction commit
+                               # (change requires restart)
+
+# - Master Server -
+
+# These settings are ignored on a standby server.
+
+#synchronous_standby_names = ''        # standby servers that provide sync rep
+                               # comma-separated list of application_name
+                               # from standby(s); '*' = all
+#vacuum_defer_cleanup_age = 0  # number of xacts by which cleanup is delayed
+
+# - Standby Servers -
+
+# These settings are ignored on a master server.
+
+hot_standby = on                       # "on" allows queries during recovery
+                                       # (change requires restart)
+#max_standby_archive_delay = 30s       # max delay before canceling queries
+                                       # when reading WAL from archive;
+                                       # -1 allows indefinite delay
+max_standby_streaming_delay = {{ postgres_extra_config.max_standby_streaming_delay | default('600s') }}        # max delay before canceling queries
+                                       # when reading streaming WAL;
+                                       # -1 allows indefinite delay
+#wal_receiver_status_interval = 10s    # send replies at least this often
+                                       # 0 disables
+#hot_standby_feedback = off            # send info from standby to prevent
+                                       # query conflicts
+#wal_receiver_timeout = 60s            # time that receiver waits for
+                                       # communication from master
+                                       # in milliseconds; 0 disables
+#wal_retrieve_retry_interval = 5s      # time to wait before retrying to
+                                       # retrieve WAL after a failed attempt
+
+
+#------------------------------------------------------------------------------
+# QUERY TUNING
+#------------------------------------------------------------------------------
+
+# - Planner Method Configuration -
+
+#enable_bitmapscan = on
+#enable_hashagg = on
+#enable_hashjoin = on
+#enable_indexscan = on
+#enable_indexonlyscan = on
+#enable_material = on
+#enable_mergejoin = on
+#enable_nestloop = on
+#enable_seqscan = on
+#enable_sort = on
+#enable_tidscan = on
+
+# - Planner Cost Constants -
+
+#seq_page_cost = 1.0                   # measured on an arbitrary scale
+{% if postgres_specific_random_page_cost is defined -%}
+# Random page cost is an arbitrary value relative to the seq_page_cost conf (default 1.0)
+# On SSD disk it is better to lower the default value from 4.0 to 1.0 for instance.
+random_page_cost = {{ postgres_specific_random_page_cost }}                    # same scale as above
+{% else -%}
+#random_page_cost = 4.0                        # same scale as above
+{% endif %}
+#cpu_tuple_cost = 0.01                 # same scale as above
+#cpu_index_tuple_cost = 0.005          # same scale as above
+#cpu_operator_cost = 0.0025            # same scale as above
+effective_cache_size = {{ ansible_memtotal_mb // 2 }}MB
+
+# - Genetic Query Optimizer -
+
+#geqo = on
+#geqo_threshold = 12
+#geqo_effort = 5                       # range 1-10
+#geqo_pool_size = 0                    # selects default based on effort
+#geqo_generations = 0                  # selects default based on effort
+#geqo_selection_bias = 2.0             # range 1.5-2.0
+#geqo_seed = 0.0                       # range 0.0-1.0
+
+# - Other Planner Options -
+
+#default_statistics_target = 100       # range 1-10000
+#constraint_exclusion = partition      # on, off, or partition
+#cursor_tuple_fraction = 0.1           # range 0.0-1.0
+#from_collapse_limit = 8
+#join_collapse_limit = 8               # 1 disables collapsing of explicit
+                                       # JOIN clauses
+
+
+#------------------------------------------------------------------------------
+# ERROR REPORTING AND LOGGING
+#------------------------------------------------------------------------------
+
+# - Where to Log -
+
+#log_destination = 'stderr'            # Valid values are combinations of
+                                       # stderr, csvlog, syslog, and eventlog,
+                                       # depending on platform.  csvlog
+                                       # requires logging_collector to be on.
+
+# This is used when logging to stderr:
+#logging_collector = off               # Enable capturing of stderr and csvlog
+                                       # into log files. Required to be on for
+                                       # csvlogs.
+                                       # (change requires restart)
+
+# These are only used if logging_collector is on:
+#log_directory = 'pg_log'              # directory where log files are written,
+                                       # can be absolute or relative to PGDATA
+#log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'       # log file name pattern,
+                                       # can include strftime() escapes
+#log_file_mode = 0600                  # creation mode for log files,
+                                       # begin with 0 to use octal notation
+#log_truncate_on_rotation = off                # If on, an existing log file with the
+                                       # same name as the new log file will be
+                                       # truncated rather than appended to.
+                                       # But such truncation only occurs on
+                                       # time-driven rotation, not on restarts
+                                       # or size-driven rotation.  Default is
+                                       # off, meaning append to existing files
+                                       # in all cases.
+#log_rotation_age = 1d                 # Automatic rotation of logfiles will
+                                       # happen after that time.  0 disables.
+#log_rotation_size = 10MB              # Automatic rotation of logfiles will
+                                       # happen after that much log output.
+                                       # 0 disables.
+
+# These are relevant when logging to syslog:
+#syslog_facility = 'LOCAL0'
+#syslog_ident = 'postgres'
+
+# This is only relevant when logging to eventlog (win32):
+#event_source = 'PostgreSQL'
+
+# - When to Log -
+
+#client_min_messages = notice          # values in order of decreasing detail:
+                                       #   debug5
+                                       #   debug4
+                                       #   debug3
+                                       #   debug2
+                                       #   debug1
+                                       #   log
+                                       #   notice
+                                       #   warning
+                                       #   error
+
+#log_min_messages = warning            # values in order of decreasing detail:
+                                       #   debug5
+                                       #   debug4
+                                       #   debug3
+                                       #   debug2
+                                       #   debug1
+                                       #   info
+                                       #   notice
+                                       #   warning
+                                       #   error
+                                       #   log
+                                       #   fatal
+                                       #   panic
+
+#log_min_error_statement = error       # values in order of decreasing detail:
+                                       #   debug5
+                                       #   debug4
+                                       #   debug3
+                                       #   debug2
+                                       #   debug1
+                                       #   info
+                                       #   notice
+                                       #   warning
+                                       #   error
+                                       #   log
+                                       #   fatal
+                                       #   panic (effectively off)
+
+log_min_duration_statement = 10000     # -1 is disabled, 0 logs all statements
+                                       # and their durations, > 0 logs only
+                                       # statements running at least this number
+                                       # of milliseconds
+
+
+# - What to Log -
+
+#debug_print_parse = off
+#debug_print_rewritten = off
+#debug_print_plan = off
+#debug_pretty_print = on
+#log_checkpoints = off
+#log_connections = off
+#log_disconnections = off
+#log_duration = off
+#log_error_verbosity = default         # terse, default, or verbose messages
+#log_hostname = off
+
+log_line_prefix = '{{ postgres_log_line_prefix }}'
+#log_line_prefix = '%t '               # special values:
+                                       #   %a = application name
+                                       #   %u = user name
+                                       #   %d = database name
+                                       #   %r = remote host and port
+                                       #   %h = remote host
+                                       #   %p = process ID
+                                       #   %t = timestamp without milliseconds
+                                       #   %m = timestamp with milliseconds
+                                       #   %i = command tag
+                                       #   %e = SQL state
+                                       #   %c = session ID
+                                       #   %l = session line number
+                                       #   %s = session start timestamp
+                                       #   %v = virtual transaction ID
+                                       #   %x = transaction ID (0 if none)
+                                       #   %q = stop here in non-session
+                                       #        processes
+                                       #   %% = '%'
+                                       # e.g. '<%u%%%d> '
+#log_lock_waits = off                  # log lock waits >= deadlock_timeout
+#log_statement = 'none'                        # none, ddl, mod, all
+#log_replication_commands = off
+#log_temp_files = -1                   # log temporary files equal or larger
+                                       # than the specified size in kilobytes;
+                                       # -1 disables, 0 logs all temp files
+log_timezone = 'GMT'
+
+
+#------------------------------------------------------------------------------
+# RUNTIME STATISTICS
+#------------------------------------------------------------------------------
+
+# - Query/Index Statistics Collector -
+
+#track_activities = on
+#track_counts = on
+#track_io_timing = off
+#track_functions = none                        # none, pl, all
+#track_activity_query_size = 1024      # (change requires restart)
+stats_temp_directory = '/var/run/postgresql/{{ postgres_version }}-{{ postgres_cluster_name }}.pg_stat_tmp'
+
+
+# - Statistics Monitoring -
+
+#log_parser_stats = off
+#log_planner_stats = off
+#log_executor_stats = off
+#log_statement_stats = off
+
+
+#------------------------------------------------------------------------------
+# AUTOVACUUM PARAMETERS
+#------------------------------------------------------------------------------
+
+#autovacuum = on                       # Enable autovacuum subprocess?  'on'
+                                       # requires track_counts to also be on.
+#log_autovacuum_min_duration = -1      # -1 disables, 0 logs all actions and
+                                       # their durations, > 0 logs only
+                                       # actions running at least this number
+                                       # of milliseconds.
+#autovacuum_max_workers = 3            # max number of autovacuum subprocesses
+                                       # (change requires restart)
+#autovacuum_naptime = 1min             # time between autovacuum runs
+#autovacuum_vacuum_threshold = 50      # min number of row updates before
+                                       # vacuum
+#autovacuum_analyze_threshold = 50     # min number of row updates before
+                                       # analyze
+#autovacuum_vacuum_scale_factor = 0.2  # fraction of table size before vacuum
+#autovacuum_analyze_scale_factor = 0.1 # fraction of table size before analyze
+#autovacuum_freeze_max_age = 200000000 # maximum XID age before forced vacuum
+                                       # (change requires restart)
+#autovacuum_multixact_freeze_max_age = 400000000       # maximum multixact age
+                                       # before forced vacuum
+                                       # (change requires restart)
+#autovacuum_vacuum_cost_delay = 20ms   # default vacuum cost delay for
+                                       # autovacuum, in milliseconds;
+                                       # -1 means use vacuum_cost_delay
+#autovacuum_vacuum_cost_limit = -1     # default vacuum cost limit for
+                                       # autovacuum, -1 means use
+                                       # vacuum_cost_limit
+
+
+#------------------------------------------------------------------------------
+# CLIENT CONNECTION DEFAULTS
+#------------------------------------------------------------------------------
+
+# - Statement Behavior -
+
+#search_path = '"$user", public'       # schema names
+#default_tablespace = ''               # a tablespace name, '' uses the default
+#temp_tablespaces = ''                 # a list of tablespace names, '' uses
+                                       # only default tablespace
+#check_function_bodies = on
+#default_transaction_isolation = 'read committed'
+#default_transaction_read_only = off
+#default_transaction_deferrable = off
+#session_replication_role = 'origin'
+#statement_timeout = 0                 # in milliseconds, 0 is disabled
+#lock_timeout = 0                      # in milliseconds, 0 is disabled
+#vacuum_freeze_min_age = 50000000
+#vacuum_freeze_table_age = 150000000
+#vacuum_multixact_freeze_min_age = 5000000
+#vacuum_multixact_freeze_table_age = 150000000
+#bytea_output = 'hex'                  # hex, escape
+#xmlbinary = 'base64'
+#xmloption = 'content'
+#gin_fuzzy_search_limit = 0
+#gin_pending_list_limit = 4MB
+
+# - Locale and Formatting -
+
+datestyle = '{{ postgres_datestyle }}'
+#intervalstyle = 'postgres'
+#timezone = '(defaults to server environment setting)'
+{% if postgres_timezone is defined %}
+timezone = '{{ postgres_timezone }}'
+{% endif %}
+#timezone_abbreviations = 'Default'     # Select the set of available time zone
+                                       # abbreviations.  Currently, there are
+                                       #   Default
+                                       #   Australia (historical usage)
+                                       #   India
+                                       # You can create your own file in
+                                       # share/timezonesets/.
+#extra_float_digits = 0                        # min -15, max 3
+#client_encoding = sql_ascii           # actually, defaults to database
+                                       # encoding
+
+# These settings are initialized by initdb, but they can be changed.
+lc_messages = '{{ postgres_locale_system }}'   # locale for system error message
+                                       # strings
+lc_monetary = '{{ postgres_locale_formats }}'  # locale for monetary formatting
+lc_numeric = '{{ postgres_locale_formats }}'   # locale for number formatting
+lc_time = '{{ postgres_locale_formats }}'      # locale for time formatting
+
+# default configuration for text search
+default_text_search_config = '{{ postgres_text_search_config }}'
+
+# - Other Defaults -
+
+#dynamic_library_path = '$libdir'
+#local_preload_libraries = ''
+#session_preload_libraries = ''
+
+
+#------------------------------------------------------------------------------
+# LOCK MANAGEMENT
+#------------------------------------------------------------------------------
+
+#deadlock_timeout = 1s
+#max_locks_per_transaction = 64                # min 10
+                                       # (change requires restart)
+# Note:  Each lock table slot uses ~270 bytes of shared memory, and there are
+# max_locks_per_transaction * (max_connections + max_prepared_transactions)
+# lock table slots.
+#max_pred_locks_per_transaction = 64   # min 10
+                                       # (change requires restart)
+
+
+#------------------------------------------------------------------------------
+# VERSION/PLATFORM COMPATIBILITY
+#------------------------------------------------------------------------------
+
+# - Previous PostgreSQL Versions -
+
+#array_nulls = on
+#backslash_quote = safe_encoding       # on, off, or safe_encoding
+#default_with_oids = off
+#escape_string_warning = on
+#lo_compat_privileges = off
+#operator_precedence_warning = off
+#quote_all_identifiers = off
+#sql_inheritance = on
+#standard_conforming_strings = on
+#synchronize_seqscans = on
+
+# - Other Platforms and Clients -
+
+#transform_null_equals = off
+
+
+#------------------------------------------------------------------------------
+# ERROR HANDLING
+#------------------------------------------------------------------------------
+
+#exit_on_error = off                   # terminate session on any error?
+#restart_after_crash = on              # reinitialize after backend crash?
+
+
+#------------------------------------------------------------------------------
+# CONFIG FILE INCLUDES
+#------------------------------------------------------------------------------
+
+# These options allow settings to be loaded from files other than the
+# default postgresql.conf.
+
+#include_dir = 'conf.d'                        # include files ending in '.conf' from
+                                       # directory 'conf.d'
+#include_if_exists = 'exists.conf'     # include file only if it exists
+#include = 'special.conf'              # include file
+
+
+#------------------------------------------------------------------------------
+# CUSTOMIZED OPTIONS
+#------------------------------------------------------------------------------
+
+# Add settings for extensions here
diff --git a/templates/postgresql.9.6.conf.j2 b/templates/postgresql.9.6.conf.j2
new file mode 100644 (file)
index 0000000..4c756f2
--- /dev/null
@@ -0,0 +1,685 @@
+# {{ ansible_managed }}
+# -----------------------------
+# PostgreSQL configuration file
+# -----------------------------
+#
+# This file consists of lines of the form:
+#
+#   name = value
+#
+# (The "=" is optional.)  Whitespace may be used.  Comments are introduced with
+# "#" anywhere on a line.  The complete list of parameter names and allowed
+# values can be found in the PostgreSQL documentation.
+#
+# The commented-out settings shown in this file represent the default values.
+# Re-commenting a setting is NOT sufficient to revert it to the default value;
+# you need to reload the server.
+#
+# This file is read on server startup and when the server receives a SIGHUP
+# signal.  If you edit the file on a running system, you have to SIGHUP the
+# server for the changes to take effect, or use "pg_ctl reload".  Some
+# parameters, which are marked below, require a server shutdown and restart to
+# take effect.
+#
+# Any parameter can also be given as a command-line option to the server, e.g.,
+# "postgres -c log_connections=on".  Some parameters can be changed at run time
+# with the "SET" SQL command.
+#
+# Memory units:  kB = kilobytes        Time units:  ms  = milliseconds
+#                MB = megabytes                     s   = seconds
+#                GB = gigabytes                     min = minutes
+#                TB = terabytes                     h   = hours
+#                                                   d   = days
+
+
+#------------------------------------------------------------------------------
+# FILE LOCATIONS
+#------------------------------------------------------------------------------
+
+# The default values of these variables are driven from the -D command-line
+# option or PGDATA environment variable, represented here as ConfigDir.
+
+data_directory = '/var/lib/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}'              # use data in another directory
+                                       # (change requires restart)
+hba_file = '/etc/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/pg_hba.conf'    # host-based authentication file
+                                       # (change requires restart)
+ident_file = '/etc/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/pg_ident.conf'        # ident configuration file
+                                       # (change requires restart)
+
+# If external_pid_file is not explicitly set, no extra PID file is written.
+external_pid_file = '/var/run/postgresql/{{ postgres_version }}-{{ postgres_cluster_name }}.pid'               # write an extra PID file
+                                       # (change requires restart)
+
+
+#------------------------------------------------------------------------------
+# CONNECTIONS AND AUTHENTICATION
+#------------------------------------------------------------------------------
+
+# - Connection Settings -
+
+listen_addresses = '{{ postgres_listen_addresses | reject("none") | join(",") }}' # what IP address(es) to listen on;
+                                       # comma-separated list of addresses;
+                                       # defaults to 'localhost'; use '*' for all
+                                       # (change requires restart)
+port = {{ postgres_port }}                             # (change requires restart)
+max_connections = 400                  # (change requires restart)
+# Note:  Increasing max_connections costs ~400 bytes of shared memory per
+# connection slot, plus lock space (see max_locks_per_transaction).
+#superuser_reserved_connections = 3    # (change requires restart)
+unix_socket_directories = '/var/run/postgresql'        # comma-separated list of directories
+                                       # (change requires restart)
+#unix_socket_group = ''                        # (change requires restart)
+#unix_socket_permissions = 0777                # begin with 0 to use octal notation
+                                       # (change requires restart)
+#bonjour = off                         # advertise server via Bonjour
+                                       # (change requires restart)
+#bonjour_name = ''                     # defaults to the computer name
+                                       # (change requires restart)
+
+# - Security and Authentication -
+
+#authentication_timeout = 1min         # 1s-600s
+ssl = true                             # (change requires restart)
+#ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL' # allowed SSL ciphers
+                                       # (change requires restart)
+#ssl_prefer_server_ciphers = on                # (change requires restart)
+#ssl_ecdh_curve = 'prime256v1'         # (change requires restart)
+#ssl_cert_file = '/etc/ssl/certs/ssl-cert-snakeoil.pem'                # (change requires restart)
+# Default will be $PGDATA/server.pem
+#ssl_key_file = '/etc/ssl/private/ssl-cert-snakeoil.key'               # (change requires restart)
+# Default will be $PGDATA/server.key
+#ssl_ca_file = ''                      # (change requires restart)
+#ssl_crl_file = ''                     # (change requires restart)
+#password_encryption = on
+#db_user_namespace = off
+#row_security = on
+
+# GSSAPI using Kerberos
+#krb_server_keyfile = ''
+#krb_caseins_users = off
+
+# - TCP Keepalives -
+# see "man 7 tcp" for details
+
+#tcp_keepalives_idle = 0               # TCP_KEEPIDLE, in seconds;
+                                       # 0 selects the system default
+#tcp_keepalives_interval = 0           # TCP_KEEPINTVL, in seconds;
+                                       # 0 selects the system default
+#tcp_keepalives_count = 0              # TCP_KEEPCNT;
+                                       # 0 selects the system default
+
+
+#------------------------------------------------------------------------------
+# RESOURCE USAGE (except WAL)
+#------------------------------------------------------------------------------
+
+# - Memory -
+
+{% if ansible_memtotal_mb > 65536 %}
+shared_buffers = 16GB                  # min 128kB
+{% else %}
+shared_buffers = {{ ansible_memtotal_mb // 4 }}MB                      # min 128kB
+{% endif %}
+                                       # (change requires restart)
+#huge_pages = try                      # on, off, or try
+                                       # (change requires restart)
+temp_buffers = 24MB                    # min 800kB
+#max_prepared_transactions = 0         # zero disables the feature
+                                       # (change requires restart)
+# Note:  Increasing max_prepared_transactions costs ~600 bytes of shared memory
+# per transaction slot, plus lock space (see max_locks_per_transaction).
+# Caution: it is not advisable to set max_prepared_transactions nonzero unless
+# you actively intend to use prepared transactions.
+work_mem = 512MB                               # min 64kB
+maintenance_work_mem = 1024MB          # min 1MB
+#replacement_sort_tuples = 150000      # limits use of replacement selection sort
+#autovacuum_work_mem = -1              # min 1MB, or -1 to use maintenance_work_mem
+#max_stack_depth = 2MB                 # min 100kB
+dynamic_shared_memory_type = posix     # the default is the first option
+                                       # supported by the operating system:
+                                       #   posix
+                                       #   sysv
+                                       #   windows
+                                       #   mmap
+                                       # use none to disable dynamic shared memory
+
+# - Disk -
+
+#temp_file_limit = -1                  # limits per-process temp file space
+                                       # in kB, or -1 for no limit
+
+# - Kernel Resource Usage -
+
+#max_files_per_process = 1000          # min 25
+                                       # (change requires restart)
+#shared_preload_libraries = ''         # (change requires restart)
+
+# - Cost-Based Vacuum Delay -
+
+#vacuum_cost_delay = 0                 # 0-100 milliseconds
+#vacuum_cost_page_hit = 1              # 0-10000 credits
+#vacuum_cost_page_miss = 10            # 0-10000 credits
+#vacuum_cost_page_dirty = 20           # 0-10000 credits
+#vacuum_cost_limit = 200               # 1-10000 credits
+
+# - Background Writer -
+
+bgwriter_delay = 2000ms                        # 10-10000ms between rounds
+#bgwriter_lru_maxpages = 100           # 0-1000 max buffers written/round
+#bgwriter_lru_multiplier = 2.0         # 0-10.0 multiplier on buffers scanned/round
+#bgwriter_flush_after = 512kB          # measured in pages, 0 disables
+
+# - Asynchronous Behavior -
+
+#effective_io_concurrency = 1          # 1-1000; 0 disables prefetching
+#max_worker_processes = 8              # (change requires restart)
+#max_parallel_workers_per_gather = 0   # taken from max_worker_processes
+#old_snapshot_threshold = -1           # 1min-60d; -1 disables; 0 is immediate
+                                       # (change requires restart)
+#backend_flush_after = 0               # measured in pages, 0 disables
+
+
+#------------------------------------------------------------------------------
+# WRITE AHEAD LOG
+#------------------------------------------------------------------------------
+
+# - Settings -
+
+wal_level = logical                    # minimal, replica, or logical
+                                       # (change requires restart)
+
+{% if postgres_fsync_enabled %}
+#fsync = on                            # flush data to disk for crash safety
+#synchronous_commit = on               # synchronization level;
+                                       # off, local, remote_write, remote_apply, or on
+{% else %}
+fsync = off                            # turns forced synchronization on or off
+# (turning this off can cause
+# unrecoverable data corruption)
+synchronous_commit = off               # synchronization level;
+{% endif %}
+#wal_sync_method = fsync               # the default is the first option
+                                       # supported by the operating system:
+                                       #   open_datasync
+                                       #   fdatasync (default on Linux)
+                                       #   fsync
+                                       #   fsync_writethrough
+                                       #   open_sync
+#full_page_writes = on                 # recover from partial page writes
+#wal_compression = off                 # enable compression of full-page writes
+wal_log_hints = on                     # also do full page writes of non-critical updates
+                                       # (change requires restart)
+#wal_buffers = -1                      # min 32kB, -1 sets based on shared_buffers
+                                       # (change requires restart)
+#wal_writer_delay = 200ms              # 1-10000 milliseconds
+#wal_writer_flush_after = 1MB          # measured in pages, 0 disables
+
+#commit_delay = 0                      # range 0-100000, in microseconds
+#commit_siblings = 5                   # range 1-1000
+
+# - Checkpoints -
+
+#checkpoint_timeout = 5min             # range 30s-1d
+#max_wal_size = 1GB
+#min_wal_size = 80MB
+#checkpoint_completion_target = 0.5    # checkpoint target duration, 0.0 - 1.0
+#checkpoint_flush_after = 256kB                # measured in pages, 0 disables
+#checkpoint_warning = 30s              # 0 disables
+
+# - Archiving -
+
+{% if postgres_archive_enabled %}
+archive_mode = on
+archive_command = 'rsync -a %p barman@{{ postgres_barman_server }}:/var/lib/barman/{{ barman_directory }}/incoming/%f'
+{% else %}
+archive_mode = off
+archive_command = ''
+{% endif %}
+
+#archive_mode = off            # enables archiving; off, on, or always
+                               # (change requires restart)
+#archive_command = ''          # command to use to archive a logfile segment
+                               # placeholders: %p = path of file to archive
+                               #               %f = file name only
+                               # e.g. 'test ! -f /mnt/server/archivedir/%f && cp %p /mnt/server/archivedir/%f'
+#archive_timeout = 0           # force a logfile segment switch after this
+                               # number of seconds; 0 disables
+
+
+#------------------------------------------------------------------------------
+# REPLICATION
+#------------------------------------------------------------------------------
+
+# - Sending Server(s) -
+
+# Set these on the master and on any standby that will send replication data.
+
+max_wal_senders = 5            # max number of walsender processes
+                               # (change requires restart)
+wal_keep_segments = 16         # in logfile segments, 16MB each; 0 disables
+#wal_sender_timeout = 60s      # in milliseconds; 0 disables
+
+{% if postgres_max_replication_slots is defined %}
+max_replication_slots = {{ postgres_max_replication_slots }} # max number of replication slots
+{% else %}
+#max_replication_slots = 0     # max number of replication slots
+{% endif %}
+                               # (change requires restart)
+#track_commit_timestamp = off  # collect timestamp of transaction commit
+                               # (change requires restart)
+
+# - Master Server -
+
+# These settings are ignored on a standby server.
+
+#synchronous_standby_names = ''        # standby servers that provide sync rep
+                               # number of sync standbys and comma-separated list of application_name
+                               # from standby(s); '*' = all
+#vacuum_defer_cleanup_age = 0  # number of xacts by which cleanup is delayed
+
+# - Standby Servers -
+
+# These settings are ignored on a master server.
+
+hot_standby = on                       # "on" allows queries during recovery
+                                       # (change requires restart)
+#max_standby_archive_delay = 30s       # max delay before canceling queries
+                                       # when reading WAL from archive;
+                                       # -1 allows indefinite delay
+max_standby_streaming_delay = 600s     # max delay before canceling queries
+                                       # when reading streaming WAL;
+                                       # -1 allows indefinite delay
+#wal_receiver_status_interval = 10s    # send replies at least this often
+                                       # 0 disables
+#hot_standby_feedback = off            # send info from standby to prevent
+                                       # query conflicts
+#wal_receiver_timeout = 60s            # time that receiver waits for
+                                       # communication from master
+                                       # in milliseconds; 0 disables
+#wal_retrieve_retry_interval = 5s      # time to wait before retrying to
+                                       # retrieve WAL after a failed attempt
+
+
+#------------------------------------------------------------------------------
+# QUERY TUNING
+#------------------------------------------------------------------------------
+
+# - Planner Method Configuration -
+
+#enable_bitmapscan = on
+#enable_hashagg = on
+#enable_hashjoin = on
+#enable_indexscan = on
+#enable_indexonlyscan = on
+#enable_material = on
+#enable_mergejoin = on
+#enable_nestloop = on
+#enable_seqscan = on
+#enable_sort = on
+#enable_tidscan = on
+
+# - Planner Cost Constants -
+
+#seq_page_cost = 1.0                   # measured on an arbitrary scale
+{% if postgres_specific_random_page_cost is defined -%}
+# Random page cost is an arbitrary value relative to the seq_page_cost conf (default 1.0)
+# On SSD disk it is better to lower the default value from 4.0 to 1.0 for instance.
+random_page_cost = {{ postgres_specific_random_page_cost }}                    # same scale as above
+{% else -%}
+#random_page_cost = 4.0                        # same scale as above
+{% endif %}
+#cpu_tuple_cost = 0.01                 # same scale as above
+#cpu_index_tuple_cost = 0.005          # same scale as above
+#cpu_operator_cost = 0.0025            # same scale as above
+#parallel_tuple_cost = 0.1             # same scale as above
+#parallel_setup_cost = 1000.0  # same scale as above
+#min_parallel_relation_size = 8MB
+#effective_cache_size = 4GB
+effective_cache_size = {{ ansible_memtotal_mb // 2 }}MB
+
+# - Genetic Query Optimizer -
+
+#geqo = on
+#geqo_threshold = 12
+#geqo_effort = 5                       # range 1-10
+#geqo_pool_size = 0                    # selects default based on effort
+#geqo_generations = 0                  # selects default based on effort
+#geqo_selection_bias = 2.0             # range 1.5-2.0
+#geqo_seed = 0.0                       # range 0.0-1.0
+
+# - Other Planner Options -
+
+#default_statistics_target = 100       # range 1-10000
+#constraint_exclusion = partition      # on, off, or partition
+#cursor_tuple_fraction = 0.1           # range 0.0-1.0
+#from_collapse_limit = 8
+#join_collapse_limit = 8               # 1 disables collapsing of explicit
+                                       # JOIN clauses
+#force_parallel_mode = off
+
+
+#------------------------------------------------------------------------------
+# ERROR REPORTING AND LOGGING
+#------------------------------------------------------------------------------
+
+# - Where to Log -
+
+#log_destination = 'stderr'            # Valid values are combinations of
+                                       # stderr, csvlog, syslog, and eventlog,
+                                       # depending on platform.  csvlog
+                                       # requires logging_collector to be on.
+
+# This is used when logging to stderr:
+#logging_collector = off               # Enable capturing of stderr and csvlog
+                                       # into log files. Required to be on for
+                                       # csvlogs.
+                                       # (change requires restart)
+
+# These are only used if logging_collector is on:
+#log_directory = 'pg_log'              # directory where log files are written,
+                                       # can be absolute or relative to PGDATA
+#log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'       # log file name pattern,
+                                       # can include strftime() escapes
+#log_file_mode = 0600                  # creation mode for log files,
+                                       # begin with 0 to use octal notation
+#log_truncate_on_rotation = off                # If on, an existing log file with the
+                                       # same name as the new log file will be
+                                       # truncated rather than appended to.
+                                       # But such truncation only occurs on
+                                       # time-driven rotation, not on restarts
+                                       # or size-driven rotation.  Default is
+                                       # off, meaning append to existing files
+                                       # in all cases.
+#log_rotation_age = 1d                 # Automatic rotation of logfiles will
+                                       # happen after that time.  0 disables.
+#log_rotation_size = 10MB              # Automatic rotation of logfiles will
+                                       # happen after that much log output.
+                                       # 0 disables.
+
+# These are relevant when logging to syslog:
+#syslog_facility = 'LOCAL0'
+#syslog_ident = 'postgres'
+#syslog_sequence_numbers = on
+#syslog_split_messages = on
+
+# This is only relevant when logging to eventlog (win32):
+#event_source = 'PostgreSQL'
+
+# - When to Log -
+
+#client_min_messages = notice          # values in order of decreasing detail:
+                                       #   debug5
+                                       #   debug4
+                                       #   debug3
+                                       #   debug2
+                                       #   debug1
+                                       #   log
+                                       #   notice
+                                       #   warning
+                                       #   error
+
+#log_min_messages = warning            # values in order of decreasing detail:
+                                       #   debug5
+                                       #   debug4
+                                       #   debug3
+                                       #   debug2
+                                       #   debug1
+                                       #   info
+                                       #   notice
+                                       #   warning
+                                       #   error
+                                       #   log
+                                       #   fatal
+                                       #   panic
+
+#log_min_error_statement = error       # values in order of decreasing detail:
+                                       #   debug5
+                                       #   debug4
+                                       #   debug3
+                                       #   debug2
+                                       #   debug1
+                                       #   info
+                                       #   notice
+                                       #   warning
+                                       #   error
+                                       #   log
+                                       #   fatal
+                                       #   panic (effectively off)
+
+log_min_duration_statement = 10000     # -1 is disabled, 0 logs all statements
+                                       # and their durations, > 0 logs only
+                                       # statements running at least this number
+                                       # of milliseconds
+
+
+# - What to Log -
+
+#debug_print_parse = off
+#debug_print_rewritten = off
+#debug_print_plan = off
+#debug_pretty_print = on
+#log_checkpoints = off
+#log_connections = off
+#log_disconnections = off
+#log_duration = off
+#log_error_verbosity = default         # terse, default, or verbose messages
+#log_hostname = off
+
+log_line_prefix = '{{ postgres_log_line_prefix }}'
+#log_line_prefix = '%t '               # special values:
+                                       #   %a = application name
+                                       #   %u = user name
+                                       #   %d = database name
+                                       #   %r = remote host and port
+                                       #   %h = remote host
+                                       #   %p = process ID
+                                       #   %t = timestamp without milliseconds
+                                       #   %m = timestamp with milliseconds
+                                       #   %n = timestamp with milliseconds (as a Unix epoch)
+                                       #   %i = command tag
+                                       #   %e = SQL state
+                                       #   %c = session ID
+                                       #   %l = session line number
+                                       #   %s = session start timestamp
+                                       #   %v = virtual transaction ID
+                                       #   %x = transaction ID (0 if none)
+                                       #   %q = stop here in non-session
+                                       #        processes
+                                       #   %% = '%'
+                                       # e.g. '<%u%%%d> '
+#log_lock_waits = off                  # log lock waits >= deadlock_timeout
+#log_statement = 'none'                        # none, ddl, mod, all
+#log_replication_commands = off
+#log_temp_files = -1                   # log temporary files equal or larger
+                                       # than the specified size in kilobytes;
+                                       # -1 disables, 0 logs all temp files
+log_timezone = 'UTC'
+
+
+# - Process Title -
+
+cluster_name = '{{ postgres_version }}/{{ postgres_cluster_name }}'                    # added to process titles if nonempty
+                                       # (change requires restart)
+#update_process_title = on
+
+
+#------------------------------------------------------------------------------
+# RUNTIME STATISTICS
+#------------------------------------------------------------------------------
+
+# - Query/Index Statistics Collector -
+
+#track_activities = on
+#track_counts = on
+#track_io_timing = off
+#track_functions = none                        # none, pl, all
+#track_activity_query_size = 1024      # (change requires restart)
+stats_temp_directory = '/var/run/postgresql/{{ postgres_version }}-{{ postgres_cluster_name }}.pg_stat_tmp'
+
+
+# - Statistics Monitoring -
+
+#log_parser_stats = off
+#log_planner_stats = off
+#log_executor_stats = off
+#log_statement_stats = off
+
+
+#------------------------------------------------------------------------------
+# AUTOVACUUM PARAMETERS
+#------------------------------------------------------------------------------
+
+#autovacuum = on                       # Enable autovacuum subprocess?  'on'
+                                       # requires track_counts to also be on.
+#log_autovacuum_min_duration = -1      # -1 disables, 0 logs all actions and
+                                       # their durations, > 0 logs only
+                                       # actions running at least this number
+                                       # of milliseconds.
+#autovacuum_max_workers = 3            # max number of autovacuum subprocesses
+                                       # (change requires restart)
+#autovacuum_naptime = 1min             # time between autovacuum runs
+#autovacuum_vacuum_threshold = 50      # min number of row updates before
+                                       # vacuum
+#autovacuum_analyze_threshold = 50     # min number of row updates before
+                                       # analyze
+#autovacuum_vacuum_scale_factor = 0.2  # fraction of table size before vacuum
+#autovacuum_analyze_scale_factor = 0.1 # fraction of table size before analyze
+#autovacuum_freeze_max_age = 200000000 # maximum XID age before forced vacuum
+                                       # (change requires restart)
+#autovacuum_multixact_freeze_max_age = 400000000       # maximum multixact age
+                                       # before forced vacuum
+                                       # (change requires restart)
+#autovacuum_vacuum_cost_delay = 20ms   # default vacuum cost delay for
+                                       # autovacuum, in milliseconds;
+                                       # -1 means use vacuum_cost_delay
+#autovacuum_vacuum_cost_limit = -1     # default vacuum cost limit for
+                                       # autovacuum, -1 means use
+                                       # vacuum_cost_limit
+
+
+#------------------------------------------------------------------------------
+# CLIENT CONNECTION DEFAULTS
+#------------------------------------------------------------------------------
+
+# - Statement Behavior -
+
+#search_path = '"$user", public'       # schema names
+#default_tablespace = ''               # a tablespace name, '' uses the default
+#temp_tablespaces = ''                 # a list of tablespace names, '' uses
+                                       # only default tablespace
+#check_function_bodies = on
+#default_transaction_isolation = 'read committed'
+#default_transaction_read_only = off
+#default_transaction_deferrable = off
+#session_replication_role = 'origin'
+#statement_timeout = 0                 # in milliseconds, 0 is disabled
+#lock_timeout = 0                      # in milliseconds, 0 is disabled
+#idle_in_transaction_session_timeout = 0               # in milliseconds, 0 is disabled
+#vacuum_freeze_min_age = 50000000
+#vacuum_freeze_table_age = 150000000
+#vacuum_multixact_freeze_min_age = 5000000
+#vacuum_multixact_freeze_table_age = 150000000
+#bytea_output = 'hex'                  # hex, escape
+#xmlbinary = 'base64'
+#xmloption = 'content'
+#gin_fuzzy_search_limit = 0
+#gin_pending_list_limit = 4MB
+
+# - Locale and Formatting -
+
+datestyle = '{{ postgres_datestyle }}'
+#intervalstyle = 'postgres'
+#timezone = '(defaults to server environment setting)'
+{% if postgres_timezone is defined %}
+timezone = '{{ postgres_timezone }}'
+{% endif %}
+#timezone_abbreviations = 'Default'     # Select the set of available time zone
+                                       # abbreviations.  Currently, there are
+                                       #   Default
+                                       #   Australia (historical usage)
+                                       #   India
+                                       # You can create your own file in
+                                       # share/timezonesets/.
+#extra_float_digits = 0                        # min -15, max 3
+#client_encoding = sql_ascii           # actually, defaults to database
+                                       # encoding
+
+# These settings are initialized by initdb, but they can be changed.
+lc_messages = '{{ postgres_locale_system }}'   # locale for system error message
+                                       # strings
+lc_monetary = '{{ postgres_locale_formats }}'  # locale for monetary formatting
+lc_numeric = '{{ postgres_locale_formats }}'   # locale for number formatting
+lc_time = '{{ postgres_locale_formats }}'      # locale for time formatting
+
+# default configuration for text search
+default_text_search_config = '{{ postgres_text_search_config }}'
+
+# - Other Defaults -
+
+#dynamic_library_path = '$libdir'
+#local_preload_libraries = ''
+#session_preload_libraries = ''
+
+
+#------------------------------------------------------------------------------
+# LOCK MANAGEMENT
+#------------------------------------------------------------------------------
+
+#deadlock_timeout = 1s
+#max_locks_per_transaction = 64                # min 10
+                                       # (change requires restart)
+# Note:  Each lock table slot uses ~270 bytes of shared memory, and there are
+# max_locks_per_transaction * (max_connections + max_prepared_transactions)
+# lock table slots.
+#max_pred_locks_per_transaction = 64   # min 10
+                                       # (change requires restart)
+
+
+#------------------------------------------------------------------------------
+# VERSION/PLATFORM COMPATIBILITY
+#------------------------------------------------------------------------------
+
+# - Previous PostgreSQL Versions -
+
+#array_nulls = on
+#backslash_quote = safe_encoding       # on, off, or safe_encoding
+#default_with_oids = off
+#escape_string_warning = on
+#lo_compat_privileges = off
+#operator_precedence_warning = off
+#quote_all_identifiers = off
+#sql_inheritance = on
+#standard_conforming_strings = on
+#synchronize_seqscans = on
+
+# - Other Platforms and Clients -
+
+#transform_null_equals = off
+
+
+#------------------------------------------------------------------------------
+# ERROR HANDLING
+#------------------------------------------------------------------------------
+
+#exit_on_error = off                   # terminate session on any error?
+#restart_after_crash = on              # reinitialize after backend crash?
+
+
+#------------------------------------------------------------------------------
+# CONFIG FILE INCLUDES
+#------------------------------------------------------------------------------
+
+# These options allow settings to be loaded from files other than the
+# default postgresql.conf.
+
+#include_dir = 'conf.d'                        # include files ending in '.conf' from
+                                       # directory 'conf.d'
+#include_if_exists = 'exists.conf'     # include file only if it exists
+#include = 'special.conf'              # include file
+
+
+#------------------------------------------------------------------------------
+# CUSTOMIZED OPTIONS
+#------------------------------------------------------------------------------
+
+# Add settings for extensions here
diff --git a/templates/recovery.conf.j2 b/templates/recovery.conf.j2
new file mode 100644 (file)
index 0000000..059b234
--- /dev/null
@@ -0,0 +1,8 @@
+# This file is renamed to `recover.done` by postgres once the secondary is promoted
+# {{ ansible_managed }}
+
+standby_mode = 'on'
+restore_command = '/usr/bin/barman-wal-restore --user barman --parallel 8 {{ postgres_barman_server }} {{ postgres_primary.restore_directory }} %f %p'
+primary_conninfo = 'host={{ postgres_primary.host }} port={{ postgres_primary.port }} user={{ postgres_primary.replication_user }} password={{ postgres_primary.replication_password }} sslmode=require'
+trigger_file = '/var/lib/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/failover.trigger'
+recovery_target_timeline='latest'
diff --git a/templates/standby-clone.sh.j2 b/templates/standby-clone.sh.j2
new file mode 100755 (executable)
index 0000000..3486342
--- /dev/null
@@ -0,0 +1,44 @@
+#!/bin/bash
+# {{ ansible_managed }}
+
+BARMAN_DATABASE=$1
+BARMAN_BACKUP_VERSION=$2
+
+if [[ -z $BARMAN_DATABASE || -z $BARMAN_BACKUP_VERSION ]]
+then
+  echo "Usage : $0 BARMAN_DATABASE BARMAN_BACKUP_VERSION" >&2
+  echo "  Example: $0 25kv 20161118T002405" >&2
+  exit 1
+fi
+
+BACKUP_DATE=`date +%s`
+
+echo "accept key if necessary"
+sudo -u postgres ssh barman@{{ postgres_barman_server }} echo ""
+
+echo Stopping PostgreSQL
+pg_ctlcluster {{ postgres_version }} {{ postgres_cluster_name }} stop
+
+echo Cleaning up old cluster directory
+sudo -u postgres mv /var/lib/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}{,_$BACKUP_DATE}
+
+echo Creating new directory
+sudo -u postgres mkdir -p /var/lib/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}
+
+echo Get previous backup from backups server
+sudo -u postgres \
+  time rsync --progress -pvia --exclude='*.conf' --exclude='server.crt' --exclude='server.key' --delete \
+  --password-file=/var/lib/postgresql/.rsync_pass \
+  rsync://barman@{{ postgres_barman_server }}/backups/$BARMAN_DATABASE/base/$BARMAN_BACKUP_VERSION/data/ \
+  /var/lib/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/
+
+echo Restoring .conf and server certificate
+sudo -u postgres cp -a /var/lib/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}_$BACKUP_DATE/{*.conf,server.crt,server.key} /var/lib/postgresql/{{ postgres_version }}/{{ postgres_cluster_name }}/
+
+echo Ensure rights are correcly set
+chown -R postgres:postgres /var/lib/postgresql/{{ postgres_version }}/
+chmod 0700 /var/lib/postgresql/{{ postgres_version }}/
+chmod -R o-rwx /var/lib/postgresql/{{ postgres_version }}/
+
+echo Starting PostgreSQL
+sudo pg_ctlcluster {{ postgres_version }} {{ postgres_cluster_name }} start
diff --git a/test/hosts b/test/hosts
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/test/main.yml b/test/main.yml
new file mode 100644 (file)
index 0000000..19ff526
--- /dev/null
@@ -0,0 +1,154 @@
+---
+- name: Bring up docker containers
+  hosts: localhost
+  vars: &common_vars
+    postgres_version: 10
+    postgres_barman_directory: 'test-postgres-10'
+    postgres_barman_server: postgres_barman
+    barman_rsync_password: "secret_rsync"
+    barman_rsync_allowed_hosts: 172.17.0.0/24
+    postgres_allowed_hosts:
+      - user: all
+        range: 172.17.0.0/24
+    postgres_replication_hosts:
+      - user: replicator
+        range: 172.17.0.0/24
+    inventory:
+      - name: "{{ postgres_barman_server }}"
+        image: "python:3.7-stretch"
+      - name: postgres_one
+        image: "python:3.7-stretch"
+        links:
+          - "{{ postgres_barman_server }}"
+      - name: postgres_two
+        image: "python:3.7-stretch"
+        links:
+          - "{{ postgres_barman_server }}"
+          - postgres_one
+      - name: postgres_three
+        image: "python:3.7-stretch"
+        links:
+          - "{{ postgres_barman_server }}"
+          - postgres_one
+  roles:
+    - role: provision_docker
+      provision_docker_inventory: "{{inventory}}"
+      provision_docker_use_docker_connection: true
+  tasks:
+    - name: Group primary
+      add_host:
+        hostname: "{{item}}"
+        groups: primary
+        <<: *common_vars
+        postgres_clusters:
+          - version: "{{ postgres_version }}"
+            name: 'main'
+            port: 5432
+            fsync_enabled: True
+            checksums: False
+            archive_enabled: True
+            barman_directory: "{{ postgres_barman_directory }}"
+            users:
+              - username: barman
+                password: "secret_cocktail"
+                permissions: 'SUPERUSER'
+              - username: replicator
+                password: "secret_repli"
+                permissions: 'REPLICATION'
+
+      with_items:
+        - postgres_one
+      tags: provision_docker
+
+    - name: Group secondaries
+      add_host:
+        hostname: "{{item}}"
+        groups: secondary
+        <<: *common_vars
+        postgres_clusters:
+          - version: "{{ postgres_version }}"
+            name: 'main'
+            port: 5432
+            fsync_enabled: True
+            checksums: False
+            archive_enabled: True
+            barman_directory: "{{ postgres_barman_directory }}"
+            primary:
+              host: postgres_one
+              port: 5432
+              restore_directory: "{{ postgres_barman_directory }}"
+              replication_user: "replicator"
+              replication_password: "secret_repli"
+
+      with_items:
+        - postgres_two
+        - postgres_three
+      tags: provision_docker
+
+    - name: Group db-all
+      add_host:
+        hostname: "{{item}}"
+        groups: db-all
+      with_items:
+        - postgres_one
+        - postgres_two
+        - postgres_three
+      tags: provision_docker
+
+    - name: Group barman
+      add_host:
+        hostname: "{{item}}"
+        groups: barman
+        <<: *common_vars
+        barman_databases:
+          - name: "{{ postgres_barman_directory }}"
+            description: 'Main database'
+            primary_host: postgres_one
+            primary_barman_password: "secret_cocktail"
+            backup_method: rsync
+            ansible_group: db-all
+            retention_policy: 'RECOVERY WINDOW OF 7 DAYS'
+      with_items:
+        - postgres_barman
+      tags: provision_docker
+
+- name: Test installing Barman role
+  hosts: barman
+  connection: docker
+  vars: {}
+  pre_tasks: &pre_tasks
+     - name: "Build hosts file"
+       shell: 'echo "{{ hostvars[inventory_hostname].ansible_default_ipv4.address }} {{inventory_hostname}}" >> /etc/hosts'
+       when: hostvars[inventory_hostname].ansible_default_ipv4.address is defined
+
+     - debug: msg="Running on host {{inventory_hostname}} ({{ hostvars[inventory_hostname].ansible_default_ipv4.address }})"
+  roles:
+    - { role: barman, tags: ['barman'] }
+
+- name: Test installing Postgresql role
+  hosts: primary:secondary
+  connection: docker
+  vars:
+    postgres_listen_addresses: "{{ hostvars[inventory_hostname].ansible_default_ipv4.address }}"
+  pre_tasks: *pre_tasks
+  roles:
+    - { role: postgresql, tags: ['postgres'] }
+  tasks:
+    - name: Start postgres cluster
+      service: name=postgresql state=started
+
+    - name: Test connection to Postgres instances.
+      become: true
+      become_user: postgres
+      become_method: su
+      command: psql --port=5432 --command='select NOW()'
+
+
+- name: Test running Postgresql role when database is started
+  connection: docker
+  hosts: primary:secondary
+  vars:
+    postgres_listen_addresses: "{{ hostvars[inventory_hostname].ansible_default_ipv4.address }}"
+  pre_tasks: *pre_tasks
+  roles:
+    - { role: postgresql, tags: ['postgres'] }
diff --git a/test/requirements.txt b/test/requirements.txt
new file mode 100644 (file)
index 0000000..d2cbb1a
--- /dev/null
@@ -0,0 +1 @@
+docker-py
diff --git a/test/requirements.yml b/test/requirements.yml
new file mode 100644 (file)
index 0000000..1b1155c
--- /dev/null
@@ -0,0 +1,3 @@
+- src: chrismeyersfsu.provision_docker
+  name: provision_docker
+  version: 7a6243dfcf69f9d262877eca487bc14b62ba6960
diff --git a/test/roles/postgresql b/test/roles/postgresql
new file mode 120000 (symlink)
index 0000000..f47fac4
--- /dev/null
@@ -0,0 +1 @@
+../../../postgresql
\ No newline at end of file