Hi all,
I want to init postgresql in k8s, try use the code as below to do:
-
name: Get the password for postgresql
kubernetes.core.k8s_info:
kind: secret
name: postgresql-ha-postgresql
namespace: pgdb
register: pgsql_info -
name:
set_fact:
pg_pwd: “{{ pgsql_info |json_query(item) | b64decode }}”
with_items: ‘resources[*].data.“postgresql-password”’ -
name:
debug: msg={{ pg_pwd }} -
name: Install psycopg2 for ansible to be able to create postgresql users
pip:
name: psycopg2-binary -
name: start k8s port forward
shell: nohup kubectl port-forward $(kubectl get pod -l app.kubernetes.io/component=pgpool -n pgdb -o name|cut -d/ -f2) 5432 -n pgdb & -
name: Check if database is available
community.postgresql.postgresql_ping:
db: postgres
login_host: 127.0.0.1
login_port: 5432
login_user: postgres
login_password: “{{ pg_pwd }}”
register: ping_database
failed_when: ping_database.warnings is defined -
name: Check the DB of ioccx
community.postgresql.postgresql_query:
db: postgres
login_host: 127.0.0.1
port: 5432
login_user: postgres
login_password: “{{ pg_pwd }}”
query: |
SELECT datname FROM pg_database where datname = ‘ioccx’
encoding: UTF-8
positional_args: 1
register: db_ioccx
when: ping_database.is_available
- name: restore dump to DB of ioccx
postgresql_db:
login_host: 127.0.0.1
login_user: postgres
login_password: “{{ pg_pwd }}”
name: ioccx
state: restore
target: 20180626.dump.tar.gz
target_opts: “–create --clean”
when: db_ioccx.query_result | length == 0
-
name: “CREATE ROLE ioccadmin”
register: result
retries: 100
until: result is success
when: db_ioccx.query_result | length == 0
postgresql_user:
login_host: 127.0.0.1
login_user: postgres
login_password: “{{ pg_pwd }}”
port: 5432
state: present
name: ioccadmin
password: “zaq12wsx”
encrypted: true
role_attr_flags: SUPERUSER -
name: “CREATE DATABASE ioccx”
when: db_ioccx.query_result | length == 0
register: create_database
postgresql_db:
login_host: 127.0.0.1
login_user: postgres
login_password: “{{ pg_pwd }}”
port: 5432
state: present
name: ioccx
owner: ioccadmin
encoding: “UTF-8”
lc_collate: “en_EN.UTF-8”
lc_ctype: “en_EN.UTF-8”
template: “template0” -
name: “GRANT ALL PRIVILEGES ON ioccx TO ioccadmin”
when: db_ioccx.query_result | length == 0
postgresql_privs:
login_host: 127.0.0.1
login_user: postgres
login_password: “{{ pg_pwd }}”
port: 5432
state: present
db: ioccx
privs: “ALL”
type: “database”
obj: ioccx
role: ioccadmin
but can’t connect the postgresql, presumably the problem is that for-forward is not running continuously in the background
Do you have any more elegant way to initialize PostgreSQL in k8s?By the way, would you pls tell me how to keep shell commands running in the background?