Last active
September 18, 2015 10:08
-
-
Save sihil/71396b5e91c71004c34c to your computer and use it in GitHub Desktop.
Bash script for uploading certificates to IAM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Upload a certificate and chain to AWS | |
set -e | |
DOMAIN=$1 | |
if [ -n "$2" ]; then | |
PROFILE_PARAM="--profile $2" | |
fi | |
if [ -z "${DOMAIN}" ]; then | |
echo "Usage: $0 domain [aws-profile]" | |
echo " domain - the file name of the certificate and private key" | |
echo " aws-profile - the AWS credentials profile to use" | |
exit 1 | |
fi | |
CERTIFICATE="${DOMAIN}.crt" | |
PRIVATE_KEY="${DOMAIN}.pem" | |
if [ ! -f ${CERTIFICATE} ]; then | |
echo "Certificate file ${CERTIFICATE} not found!" | |
exit 2 | |
fi | |
if [ ! -f ${PRIVATE_KEY} ]; then | |
echo "Private key file ${PRIVATE_KEY} not found!" | |
exit 2 | |
fi | |
# Decrypt the private key | |
echo "Decrypting private key ${PRIVATE_KEY}" | |
PRIVATE_KEY_BODY=`openssl rsa -in ${PRIVATE_KEY}` | |
if [ $? -ne 0 ]; then | |
echo "Decryption of private key failed" | |
exit 3 | |
fi | |
# Find the issuer hash | |
ISSUER_HASH=`openssl x509 -in ${CERTIFICATE} -noout -issuer_hash` | |
# See if there is an associated chain file | |
CHAIN_FILE="${ISSUER_HASH}.chain" | |
if [ -f ${CHAIN_FILE} ]; then | |
if [ -s ${CHAIN_FILE} ]; then | |
CERTIFICATE_CHAIN_PARAM="--certificate-chain file://${CHAIN_FILE}" | |
fi | |
else | |
echo "No certificate chain found for issuer_hash ${ISSUER_HASH} (expected ${CHAIN_FILE})." | |
echo "If you don't want to upload a certificate chain for this issuer (because it" | |
echo "is the root cert) then create an empty file in this location." | |
exit 4 | |
fi | |
# Find the certificate expiration | |
FULL_DATE=$(openssl x509 -in ${CERTIFICATE} -noout -enddate | cut -d= -f2) | |
if [ `uname` == "Darwin" ]; then | |
DATE_CMD=`which gdate` | |
if [ $? -ne 0 ]; then | |
echo "No gdate available. Please brew coreutils." | |
exit 5 | |
fi | |
else | |
DATE_CMD="date" | |
fi | |
SHORT_DATE=$($DATE_CMD --date="$FULL_DATE" +%Y-%m-%d) | |
SERVER_CERTIFICATE_NAME="${DOMAIN}-exp${SHORT_DATE}" | |
if [ -n "${CERTIFICATE_CHAIN}" ]; then | |
CERTIFICATE_CHAIN_PARAM="--certificate-chain file://${CERTIFICATE_CHAIN}" | |
fi | |
# Finally, upload the certificate | |
aws iam upload-server-certificate ${PROFILE_PARAM} \ | |
--server-certificate-name ${SERVER_CERTIFICATE_NAME} \ | |
--certificate-body file://${CERTIFICATE} \ | |
--private-key "${PRIVATE_KEY_BODY}" ${CERTIFICATE_CHAIN_PARAM} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment