Automating Rackspace SSL Load Balancer Certificate Mappings

This one doesn’t really come up that often at work, but it was some harmless fun I had this morning, when I thought, ‘is it possible to take some cert and key files’ and then build json around it with echo >> and sed the privateKey and publicCertificate into their rightful places in an lb.json file, and then curl a request against the Rackspace Load Balancer API.

So whats the point/joy of doing this? Well, it allows you to add certificate mappings with relative ease. Just plop your .cert and your .key file in the certificates folder, and the script can do all the rest. Of course you need to provide your username and APIKEY, but you always need to do that when making requests to the API. It’s also worth noting the TOKEN is generated automatically.

Next I will write a script that generates self signed certificates and then injects them in, so literally no user action is required. Obviously this isn’t going to be that useful, but if I connected it to an API-like certificate making service that was authorised ssl reseller, it would be a pretty tight product, I would go so far to say awesome.

Here is how I achieved it:

#!/bin/bash

USERNAME='mycloudusernamehere'
APIKEY='apikeyhere'

TOKEN=`curl https://identity.api.rackspacecloud.com/v2.0/tokens -X POST -d '{ "auth":{"RAX-KSKEY:apiKeyCredentials": { "username":"'$USERNAME'", "apiKey": "'$APIKEY'" }} }' -H "Content-type: application/json" |  python -mjson.tool | grep -A5 token | grep id | cut -d '"' -f4`


echo '
{
  "certificateMapping": {
     "hostName": "my.com",
     "certificate": "' > lb.json

cat certificates/private.key | sed ':a;N;$!ba;s/\n/\\n/g' > certificates/private.short
cat certificates/public.cert | sed ':a;N;$!ba;s/\n/\\n/g' >  certificates/public.short

cat certificates/public.short >> lb.json
echo '", "privateKey": "' >> lb.json
cat certificates/private.short >> lb.json
echo '" } }' >> lb.json


curl -v -H "X-Auth-Token: $TOKEN" -d @lb.json -X POST -H "content-type: application/json"  https://lon.loadbalancers.api.rackspacecloud.com/v1.0/10011111/loadbalancers/157089/ssltermination/certificatemappings

My colleague referred this as a ‘sneaky way’ to parse Json. He is indeed correct, I am quite sneaky, but if it’s simple and it works, then booyah. This is what the lb.json file looks like after it’s created by the above shellscript.

{
  "certificateMapping": {
     "hostName": "my.com",
     "certificate": "
-----BEGIN CERTIFICATE-----\nMIIC/TCCAeWgAwIBAgIJAP5bHAHitdeo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