Skip to content

Use a Python script to set PSQL facts (version and dbdir) #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 0 additions & 13 deletions '

This file was deleted.

1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
.DS_Store
*.pyc
__pycache__
files/
18 changes: 3 additions & 15 deletions defaults/main.yaml
Original file line number Diff line number Diff line change
@@ -1,20 +1,8 @@
---
postgresql_version: "{{ vars.postgresql.version }}"
postgresql_version: "{{ ansible_local.postgresql.version | default(16) }}"
postgresql:
version: 13 # Is ignored on FreeBSD Proservers
prefix:
config: >-
{%- if ansible_system == 'Linux' -%}
/etc/postgresql/{{ postgresql_version }}/main/conf.d
{%- elif ansible_system == 'FreeBSD' -%}
{%- if postgresql_version == "15" -%}
/var/db/postgres/data{{ postgresql_version }}
{%- else -%}
/var/db/postgresql/data{{ postgresql_version }}
{%- endif -%}
{%- else -%}
/usr/local/etc/main/conf.d
{%- endif -%}
version: "{{ postgresql_version }}"
prefix: "{{ ansible_local.postgresql.prefix | default('') }}"
users: {}
privileges: {}
databases:
Expand Down
65 changes: 65 additions & 0 deletions files/postgresql.fact.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
#!/usr/bin/env python3
import os
import re
import json
import subprocess

class PostgresqlFacts:
def get_os_family(self) -> str:
if os.path.exists("/etc/os-release"):
os_vars = {}
with open("/etc/os-release", "r", encoding="utf-8") as os_release:
for line in os_release.readlines():
key, value = line.split("=")
os_vars.update({key: value})
if os_vars.get("ID_LIKE"):
os_family = str(os_vars.get("ID_LIKE")).lower().strip()
else:
os_family = str(os_vars.get("ID")).lower().strip()
else:
os_family = re.findall(r"debian|freebsd", os.uname().version.lower())
if len(os_family) == 0:
raise OSError(f"Unsupported OS family: {os.uname().version}")
else:
os_family = os_family[0]
if os_family == "debian" or os_family == "freebsd":
return os_family
else:
raise OSError(f"Unsupported OS family: {os_family}")

def get_postgresql_version(self) -> int:
os_family = self.get_os_family()
if os_family == "debian":
command='apt-cache search --names-only "^postgresql-[0-9]+$" | grep -Po "[0-9]+"'
else:
command='psql --version | sed "s/^.*\\([0-9][0-9]\\).*$/\\1/"'
command_output = subprocess.run(command, shell=True, capture_output=True)
if len(command_output.stdout) > 0:
return int(command_output.stdout.decode().strip())
else:
raise OSError(f"Error detecting the PostgreSQL version: {command_output.stderr.decode()}")

def get_postgresql_dbdir(self) -> str:
os_family = self.get_os_family()
version = self.get_postgresql_version()
if os_family == "debian":
dbdir = f"/etc/postgresql/{version}/main/conf.d"
else:
if version >= 15:
dbdir = f"/var/db/postgres/data{version}"
else:
dbdir = f"/var/db/postgresql/data{version}"
return dbdir

def generate_postgresql_facts(self) -> dict:
return {
'version': str(self.get_postgresql_version()),
'prefix': {"config": self.get_postgresql_dbdir()},
}

class Facts:
def __str__(self):
return json.dumps(PostgresqlFacts().generate_postgresql_facts())

if __name__ == '__main__':
print(Facts())
5 changes: 2 additions & 3 deletions tasks/main.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
---
- name: Determine the PostgreSQL version (FreeBSD Proserver)
ansible.builtin.include_tasks: postgresql_version.yaml
when: ansible_system == 'FreeBSD'
- name: Set the PostgreSQL facts
ansible.builtin.include_tasks: postgresql_fact.yaml

- name: Install PostgreSQL (Linux)
ansible.builtin.include_tasks: install.yaml
Expand Down
33 changes: 33 additions & 0 deletions tasks/postgresql_fact.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
---
- name: Update apt cache (Debian-based)
changed_when: no
check_mode: no
when: "ansible_os_family == 'Debian'"
ansible.builtin.apt:
update_cache: yes

- name: Create directory for Ansible facts
loop:
- "/etc/ansible"
- "/etc/ansible/facts.d"
check_mode: no
ansible.builtin.file:
mode: "0755"
owner: root
path: "{{ item }}"
state: directory

- name: Template PostrgreSQL facts
check_mode: no
ansible.builtin.copy:
owner: root
src: postgresql.fact.py
dest: "/etc/ansible/facts.d/postgresql.fact"
mode: a+x
register: postgresql_template_fact_result

- name: Reload facts

Check warning on line 29 in tasks/postgresql_fact.yaml

View workflow job for this annotation

GitHub Actions / lint

no-handler

Tasks that run when changed should likely be handlers.
check_mode: no
when: postgresql_template_fact_result.changed
changed_when: yes
ansible.builtin.setup: {}
17 changes: 0 additions & 17 deletions tasks/postgresql_version.yaml

This file was deleted.

Loading