Skip to content

Instantly share code, notes, and snippets.

@miyanaga
Last active August 7, 2020 03:10
Show Gist options
  • Save miyanaga/ec98fc28ab28b9302429f195d2c1ff99 to your computer and use it in GitHub Desktop.
Save miyanaga/ec98fc28ab28b9302429f195d2c1ff99 to your computer and use it in GitHub Desktop.
Kubernetes interactive secret resource tool
#!/bin/bash
# Config
SECRET="my-secret" # Secret name
SECRETS="SECRET_KEY_BASE DATABASE_URL" # Data names
CACHE=".k8s-secret-env" # Cache
# YAML Template
YAML=$(cat - <<EOY
apiVersion: v1
kind: Secret
metadata:
name: $SECRET
type: Opaque
data:
EOY
)
_secret() {
cd $(dirname $0)
# Read saved cache
if [ -e "$CACHE" ]; then
source "$CACHE"
fi
DOTENV="# k8s secrets cache"
# Loop data names
for S in $SECRETS; do
# Build prompt
PROMPT="$S"
SAVED="${!S}"
if [ "$SAVED" != "" ]; then
PROMPT="${PROMPT} [${SAVED}]"
fi
echo -n "$PROMPT: "
read VALUE
# Use cache if blank input
if [ "$VALUE" = "" ]; then
VALUE="${!S}"
fi
# Add lines to YAML
BASE64=$(echo -n "$VALUE" | base64)
YAML=$(cat - <<EOY
$YAML
# $S: "$SAVED" -> "$VALUE"
$S: "$BASE64"
EOY
)
# Add lines to cache content
DOTENV=$(cat - <<EOD
$DOTENV
export $S="$VALUE"
EOD
)
done
# Confirm to apply
echo
echo "$YAML"
echo
echo -n "Apply with kubectl? (y/N): "
read YN
if [ "$YN" != "y" ]; then
return 1
fi
# Save cache and apply
echo "$DOTENV" > "$CACHE"
echo "$YAML" | kubectl apply -f -
# Ensure cache file line in .gitignore
IGNORED=""
if [ -e ".gitignore" ]; then
IGNORED=$(grep "$CACHE" .gitignore)
fi
if [ "$IGNORED" = "" ]; then
echo >> .gitignore
echo "$CACHE" >> .gitignore
fi
}
_secret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment