Automation Fundamentals
BeginnerBefore automating, learn to identify good candidates for automation and structure your scripts properly.
When to Automate?
Good candidates: Repetitive tasks, error-prone manual processes, scheduled maintenance, data collection/reporting.
Bad candidates: One-time tasks, tasks requiring human judgment, tasks that change frequently.
Rule of thumb: If you do it more than twice, automate it!
Script Structure Best Practices
#!/bin/bash
# Script: system_health.sh
# Purpose: Daily system health check
# Author: SysAdmin
# Version: 1.0
set -e # Exit on error
set -u # Error on undefined vars
# Configuration
LOG_DIR="/var/log/health"
DATE=$(date +%Y-%m-%d)
LOG_FILE="${LOG_DIR}/health_${DATE}.log"
# Functions
log_message() {
echo "[$(date '+%H:%M:%S')] $1" | tee -a "$LOG_FILE"
}
check_disk() {
log_message "Checking disk usage..."
df -h | tee -a "$LOG_FILE"
}
# Main execution
main() {
log_message "=== Health Check Started ==="
check_disk
log_message "=== Health Check Complete ==="
}
main
# Script: System-Health.ps1
# Purpose: Daily system health check
# Author: SysAdmin
# Configuration
$LogDir = "C:\Logs\Health"
$Date = Get-Date -Format "yyyy-MM-dd"
$LogFile = "$LogDir\health_$Date.log"
# Ensure log directory exists
if (-not (Test-Path $LogDir)) {
New-Item -ItemType Directory -Path $LogDir -Force
}
# Functions
function Write-Log {
param([string]$Message)
$Timestamp = Get-Date -Format "HH:mm:ss"
"[$Timestamp] $Message" | Tee-Object -FilePath $LogFile -Append
}
function Get-DiskHealth {
Write-Log "Checking disk usage..."
Get-WmiObject Win32_LogicalDisk -Filter "DriveType=3" |
Select-Object DeviceID,
@{N='Size(GB)';E={[math]::Round($_.Size/1GB,2)}},
@{N='Free(GB)';E={[math]::Round($_.FreeSpace/1GB,2)}} |
Tee-Object -FilePath $LogFile -Append
}
# Main
Write-Log "=== Health Check Started ==="
Get-DiskHealth
Write-Log "=== Health Check Complete ==="
#!/usr/bin/env python3
"""
Script: system_health.py
Purpose: Daily system health check
Author: SysAdmin
"""
import os
import shutil
from datetime import datetime
from pathlib import Path
# Configuration
LOG_DIR = Path("/var/log/health")
DATE = datetime.now().strftime("%Y-%m-%d")
LOG_FILE = LOG_DIR / f"health_{DATE}.log"
def log_message(message: str) -> None:
"""Log a message with timestamp."""
timestamp = datetime.now().strftime("%H:%M:%S")
log_line = f"[{timestamp}] {message}"
print(log_line)
with open(LOG_FILE, 'a') as f:
f.write(log_line + "\n")
def check_disk() -> None:
"""Check disk usage."""
log_message("Checking disk usage...")
total, used, free = shutil.disk_usage("/")
log_message(f"Total: {total // (2**30)} GB")
log_message(f"Used: {used // (2**30)} GB")
log_message(f"Free: {free // (2**30)} GB")
if __name__ == "__main__":
LOG_DIR.mkdir(parents=True, exist_ok=True)
log_message("=== Health Check Started ===")
check_disk()
log_message("=== Health Check Complete ===")
Tasks
- Identify 5 tasks in your environment that could be automated
- Create a script template with proper header, configuration section, and functions
- Implement logging that records timestamps and outputs to file
- Add error handling to your script template
- Document your script with comments explaining each section