Skip to content

Instantly share code, notes, and snippets.

@selivan selivan/new-cert.sh
Last active Dec 27, 2018

Embed
What would you like to do?
#!/bin/bash
#set -x
function die {
echo "ERROR: $*";
exit 1
}
usage_info="Usage: $0 ca_dir client|server certificate_name
Creates new certificate of given type and encrypts it with ansible-vault.
Warning: unencrypted directory ca_dir.plainntext may remain if script was interrupted.
"
# Arguments
ca_dir="$1"
cert_type="$2"
cert_name="$3"
[ -n "$cert_name" ] || die "$usage_info"
[ -e "$ca_dir/vars" ] || die "Not an easy-rsa CA directory: $ca_dir"
# Check for necessary programs
type openssl > /dev/null || die "openssl is not available in PATH"
type make-cadir > /dev/null || die "easy-rsa is not available in PATH"
type ansible-vault > /dev/null || die "ansible is not available in PATH"
# Abort if something goes wrong
set -e
scriptdir="$(readlink -f "$(dirname $0)")"
cd "$scriptdir"
ca_dir="$(readlink -f "$ca_dir")"
ca_plaintext_dir="$ca_dir".plaintext
## NOTE: All *.key files are encrypted, *.crt and others are saved in plaintext
## Create unencrypted ca dir to manage keys
# make-cadir can not use existing directory, it creates a new one
test -d "$ca_plaintext_dir" && rm -fr "$ca_plaintext_dir"
make-cadir "$ca_plaintext_dir"
# remove default configs
rm -fr "$ca_plaintext_dir"/vars
rm -fr "$ca_plaintext_dir"/*.cnf
## Copy files from ca dir
cp "$ca_dir"/vars "$ca_dir"/*.cnf "$ca_plaintext_dir"
mkdir "$ca_plaintext_dir"/keys
cp "$ca_dir"/keys/* "$ca_plaintext_dir"/keys
## Decrypt encrypted files
# we need to be in directory with ansible.cfg to make ansible-vault use it
find "$ca_plaintext_dir"/keys -name '*.key' -print0 | \
xargs -0 --max-args=1 --verbose -- ansible-vault decrypt
case "$cert_type" in
client)
build_script="./build-key"
;;
server)
build_script="./build-key-server"
;;
*)
die "$usage_info"
;;
esac
cd "$ca_plaintext_dir"
source ./vars
echo "$build_script" "$cert_name"
"$build_script" "$cert_name"
## Encrypt plaintext files
cd "$scriptdir"
ansible-vault encrypt "$ca_plaintext_dir"/keys/"$cert_name".key
## Copy new certs and keys back to ca dir
cp -f "$ca_plaintext_dir"/keys/"$cert_name".* "$ca_plaintext_dir"/keys/[0-9]*.pem "$ca_plaintext_dir"/keys/*.txt "$ca_plaintext_dir"/keys/*.attr "$ca_plaintext_dir"/keys/serial "$ca_dir"/keys
# Copy easy-rsa files like
## Remove unnecessary ca plaintext dir
rm -fr "$ca_plaintext_dir"
echo
echo "NOTE: don't forget to commit new files to git"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.