Skip to content

Instantly share code, notes, and snippets.

@patte
Last active November 9, 2015 23:47
Show Gist options
  • Save patte/a899b1cb2c4e4b100873 to your computer and use it in GitHub Desktop.
Save patte/a899b1cb2c4e4b100873 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Generate a kubernetes secret for nginx
# github: patte
usage="generate a kubernetes secret for nginx
$(basename "$0") [-h] -n NAME [-c CRTPATH -k KEYPATH ] [-s] [-p HTPASSWDPATH]
where:
-h show this help text
-n NAME name of the secret and the generated file
-c CRTPATH path to TLS cert (only valid with -k).
If not set, a snakeoil crt & key will be generated.
-s enable htpasswd, if used without -p you
will be asked for a username & password
-p HTPASSWD specify htpasswd file to use"
# reset in case getopts has been used previously in the shell.
OPTIND=1
# initialize our variables
name=""
crtpath=""
keypath=""
dhparampath=""
doHtpasswd=false
htpasswdpath=""
while getopts ":hn:c:k:d:sh:" opt; do
case "$opt" in
h) echo "$usage"
exit
;;
n) name=$OPTARG
;;
c) crtpath=$OPTARG
;;
k) keypath=$OPTARG
;;
d) dhparampath=$OPTARG
;;
s) doHtpasswd=true
;;
p) doHtpasswd=true; htpasswdpath=$OPTARG
;;
\?) echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:) echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
esac
done
shift $((OPTIND-1))
[ "$1" = "--" ] && shift
if [[ -z "$name" ]]; then
echo "please provide a name for the secret"
exit 1
fi
mkdir -p tmp
# TLS key & cert
if [[ $crtpath && $keypath ]]; then
echo "using crt: $crtpath key: $keypath"
if [ ! -f $crtpath ]; then
echo "crt file does not exist at: $crtpath"
exit 1
fi
if [ ! -f $keypath ]; then
echo "key file does not exist at: $keypath"
exit 1
fi
else
echo "generating snakeoil key/cert"
crtpath=tmp/nginx.crt
keypath=tmp/nginx.key
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout $keypath -out $crtpath
fi
# diffie hellman param
if [[ $dhparampath ]]; then
echo "using dhparam: $dhparampath"
if [ ! -f $dhparampath ]; then
echo "dhparam file does not exist at: $dhparampath"
exit 1
fi
else
echo "generating dhparam"
dhparampath=tmp/dhparam.pem
openssl dhparam -out $dhparampath 2048
fi
# htpasswd
if [[ "$doHtpasswd" = true ]]; then
if [[ $htpasswdpath ]]; then
echo "using htpasswd: $htpasswdpath"
if [ ! -f $htpasswdpath ]; then
echo "htpasswd file does not exist at: $htpasswdpath"
fi
else
htpasswdpath=tmp/htpasswd
read -p 'htpasswd username: ' username
read -sp 'htpasswd password: ' password
htpasswd -nb $username $password > $htpasswdpath
fi
fi
#build secret
echo "---
apiVersion: v1
kind: Secret
metadata:
name: $name
type: Opaque
data:
proxycert: $(base64 -i $crtpath)
proxykey: $(base64 -i $keypath)
dhparam: $(base64 -i $dhparampath)" > tmp/${name}.yaml
if [[ "$doHtpasswd" = true ]]; then
echo "$secret
htpasswd: $(base64 -i $htpasswdpath)" >> tmp/${name}.yaml
fi
echo "you find the generated file in ./tmp"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment