Skip to content

Instantly share code, notes, and snippets.

@h0tw1r3
Last active August 29, 2023 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h0tw1r3/2c92630f9d87d953392d473700268f40 to your computer and use it in GitHub Desktop.
Save h0tw1r3/2c92630f9d87d953392d473700268f40 to your computer and use it in GitHub Desktop.
Puppet Enterprise auto-rotate puppet-backup wrapper
#!/bin/bash
#
# Puppet Enterprise backup script
#
# Limits retained backup archives
# Optionally creates a backup of the PE service secure keys
#
# All arguments supplied via environment variables.
#
# License: MIT
# https://opensource.org/licenses/MIT
# Copyright: 2022 Jeffrey Clark
# https://github.com/h0tw1r3
set -o pipefail
ENVIRONMENT="${ENVIRONMENT:-production}"
BACKUP_DIR="${BACKUP_DIR:-/var/puppetlabs/backups}/${ENVIRONMENT}"
SCOPE="${SCOPE:-all}"
KEYS="${KEYS:-1}"
RETAIN="${RETAIN:-4}"
UMASK="${UMASK:-027}"
last_backup() {
find "${BACKUP_DIR}" -name "pe_backup*tgz" -printf "%T@\t%p\0" | sort -zrn | awk 'BEGIN{RS=ORS="\x00";FS="\t"} NR==1 { print $2 }' | tr -d '\0'
}
check_brc() {
if [ $BRC -ne 0 ] ; then
echo >&2 "error ${BRC} creating puppet backup"
exit $BRC
fi
}
tidy_all() {
tidy_match "pe_backup*tgz"
tidy_match "keys-pe_backup*tgz"
}
tidy_match() {
find "${BACKUP_DIR}" -name "$1" -printf "%T@\t%p\0" | \
sort -zrn | awk 'BEGIN{RS=ORS="\x00";FS="\t"} NR>'$RETAIN' { print $2 }' | \
xargs -0 -n1 --no-run-if-empty rm -v
}
check_permissions() {
if [ ! -d "${BACKUP_DIR}" ] ; then
echo >&2 "${BACKUP_DIR} is not a directory" && exit 2
fi
if [ ! -w "${BACKUP_DIR}" ] ; then
echo >&2 "${BACKUP_DIR} is not writable by ${USER}" && exit 1
fi
if find "${BACKUP_DIR}" -perm -o+r -type d | grep -q '.*' ; then
echo >&2 "WARNING! ${BACKUP_DIR} is readable by all users"
echo >&2 "recommend: chgrp pe-postgres ${BACKUP_DIR} && chmod 770 ${BACKUP_DIR}"
fi
}
# send output to system logger if non-interactive (cron)
if [ ! -t 0 ] ; then
coproc { stdbuf -oL logger -i -e -t pe-backup -p local7.info; }
exec 1>&${COPROC[1]}
exec 2>&${COPROC[2]}
fi
check_permissions
umask $UMASK
/opt/puppetlabs/bin/puppet-backup create --pe-environment=${ENVIRONMENT} --scope=${SCOPE} --dir=${BACKUP_DIR} | sed '/^$/d' && BRC=$? || BRC=$?
check_brc
if [ "${KEYS}x" != "x" ] && [ "${KEYS}x" != "0x" ] ; then
NEW_BACKUP=$(last_backup)
echo "backing up pe service encryption keys"
tar czf ${BACKUP_DIR}/keys-$(basename $NEW_BACKUP) -C / etc/puppetlabs/orchestration-services/conf.d/secrets/ etc/puppetlabs/console-services/conf.d/secrets/ && BRC=$? || BRC=$?
check_brc
fi
echo "tidy backups, retaining the last $RETAIN"
tidy_all
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment