1.
Start/Stop EC2 Instances
Question: Write a shell script to start or stop an EC2 instance based on the instance ID and action
provided as input.
#!/bin/bash
INSTANCE_ID=$1
ACTION=$2 # start or stop
if [ "$ACTION" != "start" ] && [ "$ACTION" != "stop" ]; then
echo "Invalid action. Use 'start' or 'stop'."
exit 1
fi
aws ec2 "$ACTION"-instances --instance-ids "$INSTANCE_ID"
if [ $? -eq 0 ]; then
echo "Instance $INSTANCE_ID has been $ACTIONed successfully."
else
echo "Failed to $ACTION instance $INSTANCE_ID."
fi
Usage: ./ec2_manage.sh i-1234567890abcdef start
2. Automate Backup of Files to S3
Question: Create a script to upload a backup file to an S3 bucket.
#!/bin/bash
BACKUP_FILE="/path/to/backup.tar.gz"
BUCKET_NAME="my-backup-bucket"
echo "Uploading $BACKUP_FILE to S3 bucket $BUCKET_NAME..."
aws s3 cp "$BACKUP_FILE" s3://"$BUCKET_NAME"/backup-$(date +
%F).tar.gz
if [ $? -eq 0 ]; then
echo "Backup uploaded successfully."
else
echo "Backup upload failed."
fi
3. Create and Attach IAM Policy to User
Question: Write a shell script to create a new IAM policy and attach it to a user.
#!/bin/bash
USER_NAME=$1
POLICY_NAME=$2
cat > policy.json << EOL
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::example-bucket"
}
]
}
EOL
echo "Creating IAM policy $POLICY_NAME..."
aws iam create-policy --policy-name "$POLICY_NAME" --policy-
document file://policy.json
POLICY_ARN=$(aws iam list-policies --query 'Policies[?
PolicyName==`'"$POLICY_NAME"'`].Arn' --output text)
echo "Attaching policy $POLICY_NAME to user $USER_NAME..."
aws iam attach-user-policy --user-name "$USER_NAME" --policy-arn
"$POLICY_ARN"
Usage: ./iam_policy.sh john_doe MyCustomPolicy
4. EBS Volume Snapshot Creation
Question: Provide a script to automate EBS volume snapshot creation.
#!/bin/bash
VOLUME_ID=$1
echo "Creating snapshot for volume: $VOLUME_ID"
SNAPSHOT_ID=$(aws ec2 create-snapshot --volume-id "$VOLUME_ID" --
description "Automated Snapshot $(date +%F)" --query 'SnapshotId'
--output text)
if [ $? -eq 0 ]; then
echo "Snapshot $SNAPSHOT_ID created successfully."
else
echo "Failed to create snapshot."
fi
Usage: ./create_snapshot.sh vol-1234567890abcdef
5. Terminate Old EC2 Instances
Question: Write a script to terminate EC2 instances that are older than 7 days.
#!/bin/bash
echo "Terminating EC2 instances older than 7 days..."
OLD_INSTANCE_IDS=$(aws ec2 describe-instances --query
'Reservations[*].Instances[?LaunchTime<=`date -d "7 days ago" +%Y-
%m-%d`].InstanceId' --output text)
for INSTANCE_ID in $OLD_INSTANCE_IDS; do
echo "Terminating instance: $INSTANCE_ID"
aws ec2 terminate-instances --instance-ids "$INSTANCE_ID"
done
6. Rotate AWS Access Keys
Question: Create a shell script to rotate AWS access keys for a user.
#!/bin/bash
USER_NAME=$1
echo "Creating a new access key for user: $USER_NAME"
NEW_ACCESS_KEY=$(aws iam create-access-key --user-name
"$USER_NAME" --query 'AccessKey.
{AccessKeyId:AccessKeyId,SecretAccessKey:SecretAccessKey}' --
output text)
OLD_ACCESS_KEY=$(aws iam list-access-keys --user-name "$USER_NAME"
--query 'AccessKeyMetadata[0].AccessKeyId' --output text)
echo "Deleting the old access key: $OLD_ACCESS_KEY"
aws iam delete-access-key --user-name "$USER_NAME" --access-key-id
"$OLD_ACCESS_KEY"
echo "New access key created: $NEW_ACCESS_KEY"
Usage: ./rotate_keys.sh username
These scripts demonstrate practical solutions to common AWS tasks and showcase your scripting
skills. Modify them as needed to handle specific requirements or error-handling mechanisms.
1. Automate Git Operations
Question: Write a shell script to automate the process of committing changes to a Git repository.
#!/bin/bash
REPO_PATH="/path/to/your/repo"
COMMIT_MESSAGE=$1
if [ -z "$COMMIT_MESSAGE" ]; then
echo "Please provide a commit message."
exit 1
fi
cd "$REPO_PATH" || exit
echo "Adding changes..."
git add .
echo "Committing changes..."
git commit -m "$COMMIT_MESSAGE"
echo "Pushing changes to the remote repository..."
git push origin main
Usage: ./git_automation.sh "Updated README file"
2. Deploy Docker Container
Question: Create a script to build and run a Docker container from a Dockerfile.
#!/bin/bash
IMAGE_NAME="my-app-image"
CONTAINER_NAME="my-app-container"
echo "Building Docker image..."
docker build -t "$IMAGE_NAME" .
if [ $? -eq 0 ]; then
echo "Docker image built successfully."
else
echo "Failed to build Docker image."
exit 1
fi
echo "Running Docker container..."
docker run -d --name "$CONTAINER_NAME" -p 8080:80 "$IMAGE_NAME"
if [ $? -eq 0 ]; then
echo "Container is up and running."
else
echo "Failed to start container."
fi
3. Check Disk Usage and Alert if Above Threshold
Question: Write a script to monitor disk usage and send an alert if it exceeds a certain threshold.
#!/bin/bash
THRESHOLD=80
USAGE=$(df -h / | grep '/' | awk '{print $5}' | sed 's/%//g')
if [ "$USAGE" -gt "$THRESHOLD" ]; then
echo "Disk usage is above $THRESHOLD%. Current usage: $USAGE%"
# You can add an alerting mechanism here (e.g., send an email
or a Slack notification)
else
echo "Disk usage is within safe limits. Current usage: $USAGE
%"
fi
4. Automate Backup and Cleanup
Question: Create a shell script to back up a directory and remove backups older than 7 days.
#!/bin/bash
SOURCE_DIR="/path/to/source"
BACKUP_DIR="/path/to/backup"
DATE=$(date +%F)
echo "Creating backup..."
tar -czvf "$BACKUP_DIR/backup-$DATE.tar.gz" "$SOURCE_DIR"
echo "Removing backups older than 7 days..."
find "$BACKUP_DIR" -type f -name "*.tar.gz" -mtime +7 -exec rm
{} \;
echo "Backup and cleanup completed."
5. Monitor CPU Usage
Question: Write a script to monitor CPU usage and log high-usage processes.
#!/bin/bash
THRESHOLD=80
LOG_FILE="/var/log/high_cpu_usage.log"
echo "Checking CPU usage..."
TOP_PROCESSES=$(ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu | head -n 10)
CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 -
$1"%"}')
echo "CPU Usage: $CPU_USAGE"
if [ $(echo "$CPU_USAGE > $THRESHOLD" | bc -l) -eq 1 ]; then
echo "High CPU usage detected. Logging details to $LOG_FILE."
echo "$(date) - High CPU Usage: $CPU_USAGE" >> "$LOG_FILE"
echo "$TOP_PROCESSES" >> "$LOG_FILE"
fi
6. Automate Kubernetes Pod Deployment
Question: Write a shell script to deploy a Kubernetes pod using a YAML configuration file.
#!/bin/bash
POD_NAME="my-app-pod"
CONFIG_FILE="pod.yaml"
echo "Applying Kubernetes configuration..."
kubectl apply -f "$CONFIG_FILE"
if [ $? -eq 0 ]; then
echo "Pod $POD_NAME has been deployed successfully."
else
echo "Failed to deploy pod."
fi
Example pod.yaml:
apiVersion: v1
kind: Pod
metadata:
name: my-app-pod
spec:
containers:
- name: my-app-container
image: nginx:latest
ports:
- containerPort: 80
7. Build and Deploy a Java Application
Question: Create a script to build a Java application using Maven and deploy it to a Tomcat server.
#!/bin/bash
PROJECT_DIR="/path/to/java/project"
TOMCAT_DIR="/path/to/tomcat/webapps"
WAR_FILE="target/myapp.war"
echo "Building Java project with Maven..."
cd "$PROJECT_DIR" || exit
mvn clean package
if [ $? -eq 0 ]; then
echo "Build successful. Deploying to Tomcat..."
cp "$WAR_FILE" "$TOMCAT_DIR"
else
echo "Build failed."
fi