forked from gregtwallace/certificate-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cw-xcp-ng.sh
71 lines (54 loc) · 2.14 KB
/
cw-xcp-ng.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/bin/sh
# This script should be securely placed with limited access
# (e.g. owned by root with permissions of 700) to avoid
# compromising the API Keys
# I placed the script in /root/certwarden and it seems fine.
# Recommended cron -- run at boot (in case system was powered off
# during a renewal, and run weekly)
# Pick any time you like. This time was arbitrarily selected.
# sudo crontab -e
# @reboot sleep 15 && /script/path/here
# 5 4 * * 2 /script/path/here
# NOTE: If Cert Warden server is running on a VM, add sleep 300-600 to wait 5-10 minutes for
# the VM to come up
## Set VARs in accord with environment
cert_apikey=<cert API key>
key_apikey=<key API key>
# server hosting key/cert
server=certdp.local:port
# name of the key/cert (as it is on server)
cert_name=unifi.example.com
# URL paths
api_cert_path=certwarden/api/v1/download/certificates/$cert_name
api_key_path=certwarden/api/v1/download/privatekeys/$cert_name
# other
xcp_cert=/etc/xensource/xapi-ssl.pem
cert_owner=root:root
# temp folder
temp_certs=/tmp/tempcerts
# path to store a timestamp to easily see when script last ran
time_stamp=/root/certwarden/timestamp.txt
####
# stop / fail on any error
set -e
mkdir -p $temp_certs
# Fetch Cert Warden
http_statuscode=$(wget https://$server/$api_cert_path --header="apiKey: $cert_apikey" -O $temp_certs/cert.pem --server-response 2>&1 | tee /dev/tty | awk '/^ HTTP/{print $2}')
if [[ $http_statuscode -ne 200 ]]; then exit 1; fi
http_statuscode=$(wget https://$server/$api_key_path --header="apiKey: $key_apikey" -O $temp_certs/key.pem --server-response 2>&1 | tee /dev/tty | awk '/^ HTTP/{print $2}')
if [[ $http_statuscode -ne 200 ]]; then exit 1; fi
# concat to expected single file
cat $temp_certs/key.pem > $temp_certs/xapi-ssl.pem
echo "" >> $temp_certs/xapi-ssl.pem
cat $temp_certs/cert.pem >> $temp_certs/xapi-ssl.pem
# use diff to check if file is different
if ! diff -s "$xcp_cert" "$temp_certs/xapi-ssl.pem" ; then
#no need to stop anything
cp -f "$temp_certs/xapi-ssl.pem" "$xcp_cert"
chown $cert_owner "$xcp_cert"
chmod 400 "$xcp_cert"
#restart api
systemctl restart xapi
fi
rm -rf $temp_certs
echo "Last Run: $(date)" > $time_stamp