|
| 1 | +#!/bin/sh |
| 2 | + |
| 3 | +usage () { |
| 4 | + echo "Usage:" |
| 5 | + echo "$0" |
| 6 | + exit 1 |
| 7 | +} |
| 8 | + |
| 9 | +# check parameters |
| 10 | +([[ -z "${REGION}" ]] || \ |
| 11 | + [[ -z "${SEED}" ]] || \ |
| 12 | + [[ -z "${PROJECT_NAME}" ]] || \ |
| 13 | + [[ -z "${ENVIRONMENT}" ]] || \ |
| 14 | + [[ -z "${DATABASE}" ]] ) && \ |
| 15 | +echo "Environment variables (REGION/REGION/PROJECT_NAME/ENVIRONMENT/DATABASE) are not set properly. Please have a check." && usage |
| 16 | + |
| 17 | +# docker image with postgres.mysql client |
| 18 | +DOCKER_IMAGE_TAG=commitdev/zero-k8s-utilities:0.0.3 |
| 19 | + |
| 20 | +# database info preparation |
| 21 | +DB_ENDPOINT=database.$PROJECT_NAME |
| 22 | +DB_NAME=$(aws rds describe-db-instances --region=$REGION --query "DBInstances[?DBInstanceIdentifier=='$PROJECT_NAME-$ENVIRONMENT'].DBName" | jq -r '.[0]') |
| 23 | +## get rds master |
| 24 | +SECRET_ID=$(aws secretsmanager list-secrets --region $REGION --query "SecretList[?Name=='$PROJECT_NAME-$ENVIRONMENT-rds-$SEED'].Name" | jq -r ".[0]") |
| 25 | +MASTER_RDS_USERNAME=master_user |
| 26 | +MASTER_RDS_PASSWORD=$(aws secretsmanager get-secret-value --region=$REGION --secret-id=$SECRET_ID | jq -r ".SecretString") |
| 27 | +## get application user/pass |
| 28 | +DB_APP_USERNAME=$PROJECT_NAME |
| 29 | +DB_APP_PASSWORD=$(LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | base64 | head -c 16) |
| 30 | + |
| 31 | +# fill in env-vars to db user creation manifest |
| 32 | +JOB_ID=$(LC_ALL=C tr -dc 'a-z0-9' < /dev/urandom | head -c 8) |
| 33 | +eval "echo \"$(cat ./db-ops/job-create-db-$DATABASE.yml.tpl)\"" > ./k8s-job-create-db.yml |
| 34 | +# the manifest creates 4 things |
| 35 | +# 1. Namespace: db-ops |
| 36 | +# 2. Secret in db-ops: db-create-users (with master password, and a .sql file |
| 37 | +# 3. Job in db-ops: db-create-users (runs the .sql file against the RDS given master_password from env) |
| 38 | +# 4. Secret in Application namespace with DB_USERNAME / DB_PASSWORD |
| 39 | + |
| 40 | +# execution |
| 41 | +kubectl apply -f ./k8s-job-create-db.yml |
| 42 | +rm -f ./k8s-job-create-db.yml |
| 43 | + |
| 44 | +# clean up |
| 45 | +## Deleting the entire db-ops namespace, leaving ONLY application-namespace's secret behind |
| 46 | +kubectl -n db-ops wait --for=condition=complete --timeout=10s job db-create-users-${JOB_ID} |
| 47 | +if [ $? -eq 0 ] |
| 48 | +then |
| 49 | + kubectl delete namespace db-ops |
| 50 | +else |
| 51 | + echo "Failed to create application database user, please see 'kubectl logs -n db-ops -l job-name=db-create-users-${JOB_ID}'" |
| 52 | +fi |
0 commit comments