Essential Automation Scripts Every DevOps Engineer Needs

(1) Ensuring regular backups of system states and configurations through automation
#!/bin/bash
SOURCE=”path/to/source”
DEST=”path/to/dest”
DATE=$(date +%Y%m%d%H%M%S)
ARCHIVE_NAME=”backup_$DATE.tar.gz”
mkdir -p “$DEST”
tar -czvf “$DEST/$ARCHIVE_NAME” “$SOURCE”
if [ $? -eq 0 ]; then
echo “backup sucess: $DEST/$ARCHIVE_NAME”
else
echo “backup failed”
exit 1
fi
(2) Incremental Backup Script
#!/bin/bash
SOURCE=” path/to/source”
DEST=” path/to/dest”
DATE=$(date +%Y%m%d%H%M%S)
LATEST=”$DEST/latest”
NEW=”$DEST/$DATE”
mkdir -p “$NEW”
if [ -e “$LATEST” ] ; then
rsync -a --dest-link=”$LATEST” “$SOURCE” “$NEW”
else
rync -a “$SOURCE” “NEW”
fi
(3) Automated service health checks to verify if critical services are running, and restarted them automatically if they were found inactive or failed
#!/bin/bash
service=”$service”
if ! systemctl is-active --quiet $service; then
echo “$service is not running ..restarting”
systemctl restart $service
else
echo “$service is running fine”
fi
(4) Website Health Check Script
#!/bin/bash
URL=” https://www.example.com”
if curl -s --head --request GET $URL | grep “200 OK” > /dev/null ; then
echo “$URL is up”
else
echo “$URL is down”
fi
(5) Basic Network Connectivity Check Script
#!/bin/bash
host=” www.example.com”
if ping -c 1 “$host” > /dev/null; then
echo “$host is reachable”
else
echo “$host is not reachable”
fi
(6) Software Installation Script
#!/bin/bash
software_list=( “git” “curl” “tree” )
for Sofware in “${software_list[@]}” ; do
echo “Installing software …”
sudo apt install $software -y
done
echo “Installation complete”
(7) Script to Check File Existence
#!/bin/bash
file=filename
if [ -e “$file” ]; then
echo “$file exists”
else
echo “$file doesn’t exists”
fi
(8) Monitoring system health and triggering alerts for anomalies
(a) CPU usage and alert if it exceeds 90%
[ $(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}' | xargs printf "%.0f\n") -gt 90 ] && echo "CPU usage above 90%" | mail -s "CPU Alert" user@example.com
(b) Memory usage and alert if it exceeds 90%
[ $(free -m | awk 'NR==2{print $3*100/$2}' | xargs printf "%.0f\n") -gt 90 ] && echo "High memory usage!" | mail -s "Memory Alert" user@example.com
(b) Disks Space usage and alert if it exceeds 90%
[ $(df / | awk 'NR==2 {print $5}' | tr -d '%' | xargs printf "%.0f\n") -gt 90 ] && echo "diskspace usage above 90%" | mail -s "diskspace Alert" user@example.com
Subscribe to my newsletter
Read articles from Harish kumar Cheemela directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
