Skip to content

Instantly share code, notes, and snippets.

Created April 6, 2016 15:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/51d86cb90e51683ee417317aee86f306 to your computer and use it in GitHub Desktop.
Save anonymous/51d86cb90e51683ee417317aee86f306 to your computer and use it in GitHub Desktop.
#!/bin/bash
APPLY_CHANGES=1
ARCHIVE_RETENTION=30
CONFIG_ARCHIVE="/mnt/flash/config"
TMP_DIR="/var/tmp"
NEW_CONFIG="$1"
RUNNING_CONFIG="/mnt/flash/config/.running-config"
TMP_CONFIG="/var/tmp/new-config"
function error()
{
echo "$@"
exit 0
}
function cli()
{
FastCli -p15 -c "$@"
}
function cleanup()
{
[ -f "$TMP_CONFIG" ] && rm $TMP_CONFIG
}
trap cleanup EXIT
[ -z "$NEW_CONFIG" ] && error "Configuration file must be set"
[ ! -f "$NEW_CONFIG" ] && error "Configuration file ($NEW_CONFIG) doesn't exist"
[ ! -d "$CONFIG_ARCHIVE" ] && mkdir -p $CONFIG_ARCHIVE
# Backup existing configuration to a file
[ ! -f "/mnt/flash/config/.running-config" ] && UPDATE_RUNNING_CONFIG=1
[ -n "$UPDATE_RUNNING_CONFIG" ] && cli "copy running-config file:/mnt/flash/config/.running-config"
DIFF_PRINT=$(diff -up -I 'last modified at' $RUNNING_CONFIG $NEW_CONFIG)
[ $(echo "$DIFF_PRINT" | wc -l) -le 1 ] && error "Configuration is the same, no changes made"
# Show the existing differences
echo "$DIFF_PRINT"
echo "---"
read -p "Do you want to apply the changes? [y/N]: " APPLY
[[ ! "$APPLY" == "y" ]] && error "Aborted"
diff -I 'last modified at' \
--new-line-format='%l
' \
--old-line-format='no %l
' \
--unchanged-line-format='%l
' \
$RUNNING_CONFIG $NEW_CONFIG | \
sed -E '/^no !$/d; /^$/d; s/^no\s{3}/ no/g' > $TMP_CONFIG
NEGATE_LINE=
while IFS='' read LINE; do
if [[ "$LINE" == "no"* ]]; then
NEGATE_LINE=1
elif [ -n "$NEGATE_LINE" ] && [[ "$LINE" == " "* ]]; then
continue
else
NEGATE_LINE=
fi
echo "$LINE"
done < $TMP_CONFIG > $TMP_CONFIG.tmp
mv $TMP_CONFIG{.tmp,}
if [ -n "$APPLY_CHANGES" ]; then
cli "copy file:$TMP_CONFIG running-config"
# Backup and rotate configurations
while read FILE; do
IFS='.' read -ra FILE_PARTS <<< "$FILE"
NEW_FILE="/mnt/flash/config/arista.conf.$(( ${FILE_PARTS[2]} + 1 )).gz"
mv $FILE $NEW_FILE
[ -z "$LAST_FILE" ] && LAST_FILE=$NEW_FILE
done < <(find /mnt/flash/config -type f -name "*.gz" | sort -Vr)
[ -f "$LAST_FILE" ] && rm $LAST_FILE
gzip -c /mnt/flash/config/.running-config > $CONFIG_ARCHIVE/arista.conf.0.gz
find /mnt/flash/config -type f -name "*.gz" | tail -n+${ARCHIVE_RETENTION} | xargs rm
rm /mnt/flash/config/.running-config
fi
exit
alias load "bash /mnt/flash/bin/config-replace %1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment