Bash Scripts in DevOps Engineering
Bash Scripts in DevOps Engineering
Real-World Bash Scripts in DevOps Engineering Purpose: Filter and monitor system logs for critical events,
Bash scripting is an integral part of a DevOps engineer's toolkit, sending alerts when specific conditions are met.
enabling seamless automation for repetitive, resource-intensive Example: Monitoring Failed Login Attempts
tasks. Below are real-world scenarios, their benefits, actual #!/bin/bash
script examples, and a summary.
LOG_FILE="/var/log/auth.log"
1. Automated Deployments ALERT_EMAIL="[email protected]"
Purpose: Streamline the application deployment process to
ensure consistency and reduce manual effort. # Check for failed logins
Example: Deploying a Web Application grep "Failed password" $LOG_FILE > /tmp/failed_logins.txt
#!/bin/bash
if [ -s /tmp/failed_logins.txt ]; then
# Variables echo "Alert: Failed login attempts detected." | mail -s
REPO_URL="https://github.com/your-org/your-repo.git" "Login Alert" $ALERT_EMAIL
DEPLOY_DIR="/var/www/html" else
BRANCH="main" echo "No failed login attempts found."
fi
# Deployment Steps Use Case: Schedule this script via cron to run every hour.
echo "Starting deployment..."
cd $DEPLOY_DIR || exit 3. Backup Management
git fetch origin $BRANCH Purpose: Automate the backup of important databases and
git reset --hard origin/$BRANCH files to prevent data loss.
npm install --production Example: Backing Up MySQL Database
systemctl restart nginx #!/bin/bash
echo "Deployment completed successfully."
Use Case: Automate this script to run after a code push by DB_NAME="my_database"
integrating it into CI/CD pipelines like Jenkins or GitHub Actions. BACKUP_DIR="/backups"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
2. Log Monitoring
1
2
echo "Starting backup for database: $DB_NAME" echo "Environment setup complete."
mysqldump -u root -p"$MYSQL_PASSWORD" $DB_NAME > Use Case: Run this script on new servers to standardize setup.
$BACKUP_FILE
5. Health Checks
if [ $? -eq 0 ]; then Purpose: Regularly monitor server health and utilization.
echo "Backup completed: $BACKUP_FILE" Example: Checking CPU and Memory Usage
else #!/bin/bash
echo "Backup failed."
fi THRESHOLD_CPU=80
Use Case: Schedule the script using a cron job to run daily: THRESHOLD_MEM=90
bash
Copy code CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}')
0 2 * * * /path/to/backup_script.sh MEM_USAGE=$(free | awk '/Mem:/ {printf("%.0f"), $3/$2 *
100.0}')
4. Environment Setup
Purpose: Automate server provisioning and dependency if (( $(echo "$CPU_USAGE > $THRESHOLD_CPU" | bc -l) ));
installation for consistent environments. then
Example: Setting Up a Development Environment echo "Warning: CPU usage is at $CPU_USAGE%"
#!/bin/bash fi