Ansible create postgresql user with access to all tables? - postgresql

This should be very simple. I want to make an Ansible statement to create a Postgres user that has connection privileges to a specific database and select/insert/update/delete privileges to all tables within that specific database. I tried the following:
- name: Create postgres user for my app
become: yes
become_user: postgres
postgresql_user:
db: "mydatabase"
name: "myappuser"
password: "supersecretpassword"
priv: CONNECT/ALL:SELECT,INSERT,UPDATE,DELETE
I get relation \"ALL\" does not exist
If I remove ALL:, I get Invalid privs specified for database: INSERT UPDATE SELECT DELETE

What I had to do was first create the user and then grant the privileges separately. It's working like a charm.
- name: Create postgres user for my app
become: yes
become_user: postgres
postgresql_user:
name: "myappuser"
password: "supersecretpassword"
- name: Ensure we have access from the new user
become: yes
become_user: postgres
postgresql_privs:
db: mydatabase
role: myappuser
objs: ALL_IN_SCHEMA
privs: SELECT,INSERT,UPDATE,DELETE

Here is the playbook I use, using debian and setting up user and db, as well as giving user access to all databases:
- hosts: all
become: yes
vars:
ansible_ssh_pipelining: true
tasks:
- name: install postgresql server
apt:
pkg: postgresql
state: present
- name: change postgres network binding
lineinfile:
path: /etc/postgresql/9.6/main/postgresql.conf
regexp: '# listen_addresses'
line: "listen_addresses = '*'"
- name: change postgres pg hba access
lineinfile:
path: /etc/postgresql/9.6/main/pg_hba.conf
regexp: 'host all all 0.0.0.0/0 md5'
line: 'host all all 0.0.0.0/0 md5'
- name: start postgresql server
service:
enabled: yes
name: postgresql
state: restarted
# psycopg2 needed for user, db creation
- pip:
name: psycopg2-binary
- name: create postgresql user
postgresql_user:
user: "root"
password: "root"
role_attr_flags: "CREATEDB,NOSUPERUSER"
become: true
become_user: postgres
- name: create postgresql db
postgresql_db:
name: "your-db-name"
state: present
become: true
become_user: postgres
Your paths may vary so adjust accordingly.
And for bonus here is my Vagrantfile, using virtualbox:
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Brings up a vm with es and mongodb
Vagrant.configure("2") do |config|
config.vm.box = "geerlingguy/debian9"
config.vm.network "private_network", ip: "192.168.33.44"
config.vm.provider "virtualbox" do |vb|
vb.memory = "2048"
end
config.vm.provision "ansible_local" do |ansible|
ansible.playbook = "ansible_playbook.yml"
ansible.install = "true"
ansible.install_mode = "pip"
end
end
Cheers!

From ansible documentation postgressql module, priv should be "PostgreSQL privileges string in the format: table:priv1,priv2"
So your task should be
- name: Create postgres user for my app
become: yes
become_user: postgres
postgresql_user:
db: "mydatabase"
name: "myappuser"
password: "supersecretpassword"
priv: ALL:SELECT,INSERT,UPDATE,DELETE,CONNECT

Related

Vagrant - Ansible - Install PostgreSQL and Postgis [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 19 hours ago.
Improve this question
I'm trying to install PostgreSQL and Postgis with Ansible on a Vagrant VM.
But I'm reaching some issues to install and access to PostgreSQL (didn't reach the step of Postgis yet).
My Vagrant VM is an ubuntu/jammy64.
Firstly, I installed PHP on the VM.
Then I try to install PostrgreSQL. In following, my psql task to Ansible:
---
- name: Install
apt:
update_cache: true
name:
- bash
- openssl
- libssl-dev
- libssl-doc
- postgresql
- postgresql-contrib
- libpq-dev
- python3-psycopg2
state: present
- name: Check if initialized
stat:
path: "{{ postgresql_data_dir }}/pg_hba.conf"
register: postgres_data
- name: Empty data dir
file:
path: "{{ postgresql_data_dir }}"
state: absent
when: not postgres_data.stat.exists
- name: Initialize
shell: "{{ postgresql_bin_path }}/initdb -D {{ postgresql_data_dir }}"
become: true
become_user: postgres
when: not postgres_data.stat.exists
- name: Start and enable service
service:
name: postgresql
state: started
enabled: true
- name: Update pg_ident.conf - allow user to auth with postgres
lineinfile:
dest: "/etc/postgresql/{{ postgresql_version }}/main/pg_ident.conf"
insertafter: "# MAPNAME SYSTEM-USERNAME PG-USERNAME"
line: "user_{{ user }} {{ user }} postgres"
- name: Update pg_hba.conf - disable peer for postgres user
lineinfile:
dest: "/etc/postgresql/{{ postgresql_version }}/main/pg_hba.conf"
regexp: "local all postgres peer"
line: "#local all postgres peer"
- name: Update pg_hba.conf - trust all connection
lineinfile:
dest: "/etc/postgresql/{{ postgresql_version }}/main/pg_hba.conf"
regexp: "local all all peer"
line: "local all all trust"
- name: Restart
service:
name: postgresql
state: restarted
enabled: true
- name: "Create database {{ postgresql_db }}"
become: true
become_user: "{{ postgresql_user }}"
postgresql_db:
name: "{{ postgresql_db }}"
state: present
- name: "Create user {{ user }}"
become: yes
become_user: "{{ postgresql_user }}"
postgresql_user:
name: "{{ user }}"
password: "{{ user }}"
state: present
- name: "Grant user {{ user }}"
become: yes
become_user: "{{ postgresql_user }}"
postgresql_privs:
type: database
database: "{{ postgresql_db }}"
roles: "{{ user }}"
grant_option: no
privs: all
notify: psql restart
My vars:
---
postgresql_version: 14
postgresql_bin_path: "/usr/lib/postgresql/{{ postgresql_version }}/bin"
postgresql_data_dir: "/var/lib/postgresql/{{ postgresql_version }}/main"
postgresql_host: localhost
postgresql_port: 5432
postgresql_db: "db_{{ user }}"
postgresql_user: "{{ user }}"
postgresql_password: "{{ user }}"
ansible_ssh_pipelining: true
But when I play the Ansible's playbook I'm getting the following feedback:
TASK [include_role : psql] *****************************************************
TASK [psql : Install] **********************************************************
ok: [192.168.50.50]
TASK [psql : Check if initialized] *********************************************
ok: [192.168.50.50]
TASK [psql : Empty data dir] ***************************************************
skipping: [192.168.50.50]
TASK [psql : Initialize] *******************************************************
skipping: [192.168.50.50]
TASK [psql : Start and enable service] *****************************************
ok: [192.168.50.50]
TASK [psql : Create database db_ojirai] ****************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: Is the server running locally and accepting connections on that socket?
fatal: [192.168.50.50]: FAILED! => {"changed": false, "msg": "unable to connect to database: connection to server on socket \"/var/run/postgresql/.s.PGSQL.5432\" failed: Connection refused\n\tIs the server running locally and accepting connections on that socket?\n"}
PLAY RECAP *********************************************************************
192.168.50.50 : ok=14 changed=0 unreachable=0 failed=1 skipped=2 rescued=0 ignored=0
Can you, guys, explain to me where is my mistake, please? Is it my PostgreSQL installation which is wrong?
Thanks for your feedbacks!
Edit:
I try the suggested solution by β.εηοιτ.βε but the message persist. I tried with following process:
vagrant destroy > export vars (suggested in the post) > vagrant up > ansible deploy
export vars (suggested in the post) > vagrant reload > ansible deploy
export vars (suggested in the post) > vagrant destroy > vagrant up > ansible deploy
vagrant destroy > vagrant up > export vars (suggested in the post) > ansible deploy

ansible and postgres not allowing configuration: LOG: provided user name (postgres) and authenticated user name (boop) do not match

Im trying to configure postgres with ansible. i have two vms running ubuntu 22.0.4.1 on an internal network. they are happy to use standard ansible commands. however upon using the standard ansible commands I get.
unable to connect to database: connection to server on socket \"/var/run/postgresql/.s.PGSQL.5432\" failed: fatal: peer authentication failed for user \"postgres\"
message.
the log says
LOG: provided user name (postgres) and authenticated user name (boop) do not match
i used the following playbook:
---
- name: Setup
hosts: postgres_primaries
become: true
tasks:
- name: Install dependencies for PostgreSQL
apt:
name: "{{ item.name }}"
update_cache: true
state: latest
with_items:
- { name: bash }
- { name: openssl }
- { name: libssl-dev }
- { name: libssl-doc }
- name: Install PostgreSQL
package:
name: "{{ item.name }}"
update_cache: true
state: present
with_items:
- { name: postgresql }
- { name: postgresql-contrib }
- { name: libpq-dev }
- { name: python3-psycopg2 }
- name: Ensure the PostgreSQL service is running
service: name=postgresql state=started enabled=yes
- name: Daemon-Reload for Postgres if case of config change
systemd:
state: restarted
daemon-reload: yes
name: postgresql
- name: work on database
hosts: postgres_primaries
become_user: postgres
vars_files:
- vars.yml
tasks:
- name: create database
postgresql_user:
name: test1
password: boop
i tried mapping boop to postgres the following user_name map:
postgres boop postgres
i tried editing my pg_hba.conf to a more catch all condition:
local all all peer
this should give me a user but instead the aforementioned error turns up. if i try to add a become: yes to the final task i get a error related to moving files as an unprivileged user.

Using "Kubegres" Postgres Operator for Kubernetes, how can database name be set?

Using the Postgres operator for Kubernetes "Kubegres" (https://www.kubegres.io),
how can the name of the database be set? By default the operator creates a database with name "postgres".
I am referring to the Postgres database name here passed by flag -d, a.k.a. dbname:
psql -h 127.0.0.1 -p 5432 -d postgres -U postgres -W
not the name of the Kubernetes service "mypostgres", shown in this sample manifest from https://www.kubegres.io/doc/getting-started.html:
apiVersion: kubegres.reactive-tech.io/v1
kind: Kubegres
metadata:
name: mypostgres
namespace: default
spec:
replicas: 2
image: postgres:14.1
database:
size: 200Mi
env:
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: mypostgres-secret
key: superUserPassword
- name: POSTGRES_REPLICATION_PASSWORD
valueFrom:
secretKeyRef:
name: mypostgres-secret
key: replicationUserPassword
It does not appear to be in these properties
https://www.kubegres.io/doc/properties-explained.html
I do not think this works:
env:
- name: POSTGRES_DB
value: keycloak
It does not change the dbname:
$ psql -h 127.0.0.1 -p 5432 -d keycloak -U postgres -W
Password:
psql: error: FATAL: database "keycloak" does not exist
Thank you
You can use Override primary_init_script.sh
https://www.kubegres.io/doc/override-default-configs.html

Ansible and postgresql error with psycopg2

I'm trying to configure postgresql by ansible in a VPS.
Look for a solution, I tried to change peer for md5 and trust too in the postgre conf.
My role:
- name: Install o Postgresql
become: yes
apt:
name: ['libpq-dev', 'python3-dev', 'postgresql', 'postgresql-contrib']
- name: Install o psycopg2
become: yes
pip:
name: psycopg2-binary
executable: pip3
- name: ensure postgresql is running
service:
name: postgresql
state: started
enabled: yes
- name: ensure database is created
become: true
become_user: postgres
postgresql_db:
name: "{{ db_name }}"
The tasks 1,2,3 is ok. But the task 4 "ensure database is created" I receive this error:
psycopg2.OperationalError: FATAL: role "postgresql" does not exist
My playbook
- hosts: dev
remote_user: develop
roles:
- update_apt
- nginx
- webapp
- postgresql
- git

Postgresql - unable to connect to database: could not connect to server: No such file or directory

So I'm trying to create a Postgres Database on my remote server with Ansible, unfortunately I'm getting this error message
TASK [postgresql : Create database with name sola] *****************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
fatal: [some-remote-server]: FAILED! => {
"changed": false
}
MSG:
unable to connect to database: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
This would be my playbook
- name: enable the PostgreSQL package repository
copy:
src: pgdg-96-redhat.repo
dest: /etc/yum.repos.d/pgdg-96-redhat.repo
- name: install additional packages
yum:
name: "{{ item }}"
state: present
with_items:
- "{{ packages }}"
- name: Ensure bash and OpenSSL are the latest version
yum:
name: "{{ item }}"
update_cache: true
state: latest
with_items:
- bash
- openssl
tags: packages
- name: install system packages
yum:
name: "{{ item }}"
state: installed
with_items:
- "{{ packages }}"
become: yes
- name: Install PostgreSQL
yum:
name: "{{ item }}"
update_cache: true
state: installed
with_items:
- postgresql
- postgresql-contrib
- python-psycopg2
tags: packages
become: yes
- name: enabling postgresql services
service:
name: postgresql
state: started
enabled: yes
- name: Create database with name sola
postgresql_db:
name: sola
encoding: 'UTF-8'
lc_collate: 'en_US.UTF-8'
lc_ctype: 'en_US.UTF-8'
template: 'template0'
- name: Ensure database is created
sudo_user: postgres
postgresql_db:
name: dbname
encoding: 'UTF-8'
lc_collate: 'en_US.UTF-8'
lc_ctype: 'en_US.UTF-8'
template: 'template0'
state: present
My suspicions are, that either something went wrong witht the installation process, so that postgres hasn't even been properly installed on the remote server or that I'm not properly enabling and starting the postgres services. Any help is appreciated!