Shell Scripts for DevOps & Cloud
Shell Scripts for DevOps & Cloud
if [ -f "$last_backup" ]; then
find $src_dir -type f -newer $last_backup > changed_files.txt
else
find $src_dir -type f > changed_files.txt
fi
Rotating Logs:
#!/bin/bash
log_dir="/path/to/logs"
max_size=1000000 # 1 MB
Explanation: This script checks if a package is already installed before attempting installation.
Modify the software_list array for your requirements.
for partition in $(df -h | grep "^/dev" | awk '{print $5 " " $1}'); do
usage=$(echo $partition | awk '{print $1}' | sed 's/%//')
mount=$(echo $partition | awk '{print $2}')
if [ $usage -ge $threshold ]; then
echo "Warning: $mount is $usage% full."
fi
done
Here’s a collection of cloud automation and DevOps-oriented shell scripts that are highly
practical in real-world scenarios. These scripts cover areas like cloud resource management,
configuration, CI/CD tasks, monitoring, and troubleshooting.
if [ -n "$instances" ]; then
aws ec2 stop-instances --instance-ids $instances
echo "Stopped instances: $instances"
else
echo "No running instances found."
fi
2. Kubernetes (k8s) Automation Scripts
2.1 List All Pods in a Namespace
bash
Copy code
#!/bin/bash
namespace="default"
kubectl get pods -n $namespace
9. Miscellaneous
9.1 Clean Up Old Files
bash
Copy code
#!/bin/bash
find /path/to/directory -type f -mtime +30 -exec rm {} \;
echo "Old files cleaned up."
Scripts
1.1 Provision an AWS EC2 Instance with a Specific Configuration
bash
Copy code
#!/bin/bash
instance_type="t2.micro"
key_name="my-key"
security_group="sg-12345678"
subnet_id="subnet-12345678"
ami_id="ami-12345678"
# Recreate namespace
kubectl create namespace $namespace
echo "Namespace $namespace recreated."
docker images --format '{{.Repository}} {{.Tag}} {{.CreatedSince}}' | while read repo tag created; do
if [[ $created == *"$threshold_days days ago"* ]]; then
echo "Deleting image: $repo:$tag"
docker rmi "$repo:$tag"
fi
done
Restore Script:
bash
Copy code
#!/bin/bash
backup_file="/backups/backup_latest.tar.gz"
restore_dir="/restore"
# Verify integrity
if md5sum -c "$backup_file.md5"; then
tar -xzf $backup_file -C $restore_dir
echo "Restore successful to $restore_dir."
else
echo "Backup integrity verification failed!"
exit 1
fi
aws ce get-cost-and-usage \
--time-period Start=$start_date,End=$end_date \
--granularity MONTHLY \
--metrics "UnblendedCost" \
--output text > $output_file