Let’s spend 2 minutes at The Bash Script Corner

A while ago, I was tasked with writing a bash script that would do the following:

  • Read the username, password and host values from Kubernetic config map
  • Reads the Postgres username, password, host and database values
  • Replace variables with corresponding values in the application.yml file
#! /usr/bin/env sh

echo "Mapping the env variables to the values from Kubernetis "

STAGING_ENV="$1"

#Sanity check
if [ $# -eq 0 ]; then
    echo "No argument was provided, however the script requires 1 argument to successfully run"
    exit 1
fi

POSTGRES_CORE="postgres-core"

#Postgres Env Variables
export DB_USERNAME=$(kubectl get configmap "$STAGING_ENV"-$POSTGRES_CORE -o jsonpath="{.data.username}")
export DB_PASSWORD=$(kubectl get secret "$STAGING_ENV"-$POSTGRES_CORE -o jsonpath="{.data.password}" | base64 -D)
export DB_HOSTNAME=$(kubectl get configmap "$STAGING_ENV"-$POSTGRES_CORE -o jsonpath="{.data.host}")
export DB_NAME=$(kubectl get configmap "$STAGING_ENV"-$POSTGRES_CORE -o jsonpath="{.data.name}")

export APPLICATION_YML_LOCATION=src/main/resources/application.yml

echo "Start replacing postgres env variables values with sed"
sed -i '' "s/DB_USERNAME:postgres/DB_USERNAME:$DB_USERNAME/g" $APPLICATION_YML_LOCATION
sed -i '' "s/DB_PASSWORD:password/DB_PASSWORD:$DB_PASSWORD/g" $APPLICATION_YML_LOCATION
sed -i '' "s/DB_HOSTNAME:localhost/DB_HOSTNAME:$DB_HOSTNAME/g" $APPLICATION_YML_LOCATION
sed -i '' "s/DB_NAME:core-db/$DB_NAME:$DB_NAME/g" $APPLICATION_YML_LOCATION
echo "End replacing postgres env variables values with sed"



Posted on May 23, 2020, in Uncategorized. Bookmark the permalink. Leave a comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.