πŸ’‘
Hey β€” It's Sandip Das πŸ‘‹
Today, we go beyond the basics and explore advanced EC2 concepts, real-world use cases, and optimization techniques.

⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:


πŸ’‘ Learning Points:

  • EC2 Instance Lifecycle – Launch, Stop, Hibernate, Reboot, Terminate.
  • EC2 IAM Access – IAM roles and permissions for EC2 instances.
  • EC2 Instance Metadata & User Data – Using metadata service and running boot-time scripts.
  • EC2 Image Management – AMI Creation, Backup, and Recovery.
  • EC2 Storage – EBS (Elastic Block Store) types, performance optimization, and snapshots.
  • Networking for EC2 – Elastic IPs, VPC setup, Private vs Public Subnets, Bastion Hosts.
  • Scaling EC2 – Auto Scaling Groups (ASG), Load Balancing (ALB/ELB), and Capacity Reservations.
  • EC2 Placement Groups, Dedicated Hosts, and Dedicated Instances – Strategies for performance and isolation.
  • Monitoring & Logging – CloudWatch metrics, AWS Config, and CloudTrail logs.
  • EC2 Instance Recovery and Troubleshooting – Fixing issues and debugging.
  • AWS Systems Manager – Advanced automation, patching, and fleet management.

🧠 Learn here:

EC2 Instance Lifecycle

Launch, Stop, Hibernate, Reboot, Terminate

Launch: Create and start an EC2 instance from an AMI.

aws ec2 run-instances --image-id ami-0abcdef1234567890 --instance-type t3.micro --key-name MyKeyPair --security-group-ids sg-0123456789abcdef0 --subnet-id subnet-0123456789abcdef0

Stop: Gracefully shuts down the instance and stops compute billing (attached EBS volumes are still billed).

aws ec2 stop-instances --instance-ids i-0123456789abcdef0

Hibernate: Saves the in-memory RAM state to the encrypted EBS root volume, so the instance resumes faster than a cold start. Hibernation has to be enabled at launch (--hibernation-options Configured=true).

aws ec2 stop-instances --instance-ids i-0123456789abcdef0 --hibernate

Reboot: Restarts the instance (similar to OS reboot).

aws ec2 reboot-instances --instance-ids i-0123456789abcdef0

Terminate: Deletes the instance and releases resources.

aws ec2 terminate-instances --instance-ids i-0123456789abcdef0

EC2 IAM Access

IAM Roles and Permissions

IAM Roles: Attach roles to EC2 to grant AWS resource access securely.

cat > trust-policy.json <<'EOF'
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Service": "ec2.amazonaws.com" },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF
aws iam create-role --role-name EC2S3AccessRole --assume-role-policy-document file://trust-policy.json
aws iam attach-role-policy --role-name EC2S3AccessRole --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

# EC2 picks up a role through an instance profile
aws iam create-instance-profile --instance-profile-name EC2S3AccessRole
aws iam add-role-to-instance-profile --instance-profile-name EC2S3AccessRole --role-name EC2S3AccessRole
aws ec2 associate-iam-instance-profile --instance-id i-0123456789abcdef0 --iam-instance-profile Name=EC2S3AccessRole


EC2 Instance Metadata & User Data

User Data: Scripts executed on first boot (e.g., install software).
Example script:

#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd

Attach it using:

aws ec2 run-instances --image-id ami-0abcdef1234567890 --instance-type t3.micro --user-data file://userdata.sh

Instance Metadata: Access instance-specific information like instance ID, IP, etc. New instances require IMDSv2, so request a session token first:

TOKEN=$(curl -sX PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-id

EC2 Image Management

AMI Creation, Backup, and Recovery

Create AMI:

aws ec2 create-image --instance-id i-0123456789abcdef0 --name "MyServerBackup"

Backup:

aws ec2 create-snapshot --volume-id vol-12345678 --description "Backup snapshot"

Recovery:

aws ec2 run-instances --image-id ami-0abcdef1234567890 --instance-type t3.micro

EC2 Storage

EBS Types and Optimization

Create Volume:

aws ec2 create-volume --availability-zone us-east-1a --size 20 --volume-type gp3

Attach Volume:

aws ec2 attach-volume --volume-id vol-12345678 --instance-id i-0123456789abcdef0 --device /dev/sdf

Snapshots:

aws ec2 create-snapshot --volume-id vol-12345678 --description "EBS backup"

Networking for EC2

Elastic IPs: A static public IPv4 address. AWS bills every public IPv4 address, attached or idle, so release the ones you don't use:

aws ec2 allocate-address
aws ec2 associate-address --instance-id i-0123456789abcdef0 --allocation-id eipalloc-12345678

# when you no longer need it
aws ec2 disassociate-address --association-id eipassoc-12345678
aws ec2 release-address --allocation-id eipalloc-12345678

VPC Setup:

aws ec2 create-vpc --cidr-block 10.0.0.0/16

Private vs Public Subnets:

# Public subnet: its route table sends 0.0.0.0/0 to an internet gateway
aws ec2 create-subnet --vpc-id vpc-abc123 --cidr-block 10.0.1.0/24 --availability-zone us-east-1a
aws ec2 create-internet-gateway
aws ec2 attach-internet-gateway --vpc-id vpc-abc123 --internet-gateway-id igw-abc123
aws ec2 create-route-table --vpc-id vpc-abc123
aws ec2 create-route --route-table-id rtb-abc123 --destination-cidr-block 0.0.0.0/0 --gateway-id igw-abc123
aws ec2 associate-route-table --route-table-id rtb-abc123 --subnet-id subnet-pub123

# Private subnet: no route to the internet gateway (add a NAT gateway for outbound access)
aws ec2 create-subnet --vpc-id vpc-abc123 --cidr-block 10.0.2.0/24 --availability-zone us-east-1a

Bastion Hosts: A small instance in a public subnet that accepts SSH only from your IP and is used to reach instances in private subnets. Session Manager (covered below) removes the need for one.

Scaling EC2

Auto Scaling Groups (ASG):

# Launch configurations are deprecated; Auto Scaling groups use launch templates
aws autoscaling create-auto-scaling-group --auto-scaling-group-name my-asg \
  --launch-template LaunchTemplateName=my-launch-template,Version='$Latest' \
  --min-size 1 --max-size 3 --vpc-zone-identifier "subnet-abc123,subnet-def456"

Load Balancing (ALB):

aws elbv2 create-load-balancer --name my-alb --type application --subnets subnet-123 subnet-456 --security-groups sg-0123456789abcdef0

Capacity Reservations:

aws ec2 create-capacity-reservation --instance-type t3.micro --instance-platform Linux/UNIX --availability-zone us-east-1a --instance-count 2

EC2 Placement Groups, Dedicated Hosts, and Dedicated Instances

Placement Group:

aws ec2 create-placement-group --group-name my-placement-group --strategy cluster

Dedicated Hosts:

aws ec2 allocate-hosts --instance-type c5.large --availability-zone us-east-1a --quantity 1

Dedicated Instances: Run on hardware dedicated to your account. Set the tenancy at launch with --placement Tenancy=dedicated:

aws ec2 run-instances --image-id ami-0abcdef1234567890 --instance-type c5.large --placement Tenancy=dedicated

Monitoring & Logging

CloudWatch metrics:

aws cloudwatch get-metric-statistics --namespace AWS/EC2 --metric-name CPUUtilization --dimensions Name=InstanceId,Value=i-0123456789abcdef0 --start-time 2023-01-01T00:00:00Z --end-time 2023-01-01T01:00:00Z --period 300 --statistics Average

AWS Config:

aws configservice describe-config-rules

CloudTrail logs:

aws cloudtrail lookup-events --lookup-attributes AttributeKey=ResourceName,AttributeValue=i-0123456789abcdef0

EC2 Instance Recovery and Troubleshooting

Fixing issues and debugging:

aws ec2 get-console-output --instance-id i-0123456789abcdef0
aws ec2 describe-instance-status --instance-ids i-0123456789abcdef0

AWS Systems Manager

Run command on EC2:

aws ssm send-command --document-name "AWS-RunShellScript" --targets "Key=instanceIds,Values=i-0123456789abcdef0" --parameters 'commands=["uptime"]' --comment "Check uptime"

Patch Manager Example:

aws ssm create-patch-baseline --name "MyBaseline" --operating-system AMAZON_LINUX_2023 --approval-rules file://rules.json

πŸ“š Resources:




πŸ›  Initial Tasks

βœ… Task 1: Read about AWS EC2 Instance Types (AWS Docs) and list at least three instance types with their use cases.
βœ… Task 2: Explore EBS Volume Types (AWS Docs) and understand the difference between gp3, io1, and st1 volumes.

πŸ”₯ Challenges & Solutions

πŸ”Ή Challenge 1: Set up an IAM Role to allow EC2 to upload logs to S3

Answer:

Step 1: Create an S3 Bucket

  • Go to AWS Console β†’ S3 β†’ Click Create Bucket.
  • Name the bucket: my-ec2-logs-bucket
  • Enable versioning (optional).
  • Block all public access.
  • Click Create Bucket.

Step 2: Create an IAM Role for EC2

  • Go to AWS Console β†’ IAM β†’ Roles β†’ Click Create Role.
  • Select Trusted Entity:
    • Choose AWS Service β†’ EC2.
  • Attach Policies:
    • Click Create Policy.
    • Name it: EC2-S3-Logging-Policy
    • Click Create Policy.
    • Attach the EC2-S3-Logging-Policy to the role.
    • Name the role: EC2-S3-Logs-Role
    • Click Create Role.

Under Permissions, select JSON and paste:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:PutObject",
        "s3:GetObject",
        "s3:ListBucket"
      ],
      "Resource": [
        "arn:aws:s3:::my-ec2-logs-bucket",
        "arn:aws:s3:::my-ec2-logs-bucket/*"
      ]
    }
  ]
}

Step 3: Attach IAM Role to EC2

  • Go to AWS Console β†’ EC2 β†’ Instances.
  • Select your instance.
  • Click Actions β†’ Security β†’ Modify IAM Role.
  • Choose EC2-S3-Logs-Role and update.

Step 4: Verify IAM Role Access on EC2

Check which identity the CLI is using:

aws sts get-caller-identity

Expected:

{
    "UserId": "AROAEXAMPLEID:i-0123456789abcdef0",
    "Account": "123456789012",
    "Arn": "arn:aws:sts::123456789012:assumed-role/EC2-S3-Logs-Role/i-0123456789abcdef0"
}

Run:

TOKEN=$(curl -sX PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/

Expected Output:

EC2-S3-Logs-Role

Step 5: Configure Log Upload to S3

Log Upload Script (save it as /home/ec2-user/upload-logs.sh; it assumes nginx is installed and writing access logs):

#!/bin/bash
LOG_FILE="/var/log/nginx/access.log"
S3_BUCKET="s3://my-ec2-logs-bucket"
DATE=$(date +"%Y-%m-%d-%H%M")
aws s3 cp "$LOG_FILE" "$S3_BUCKET/nginx-logs-$DATE.log"

Make executable:

chmod +x upload-logs.sh
sudo ./upload-logs.sh

Output:

upload: ./access.log to s3://my-ec2-logs-bucket/nginx-logs-2024-03-10-1200.log

Step 6: Automate with Cron

Edit crontab:

# Amazon Linux 2023 does not ship cron by default
sudo dnf install -y cronie
sudo systemctl enable --now crond
sudo crontab -e

Add:

0 * * * * /home/ec2-user/upload-logs.sh >> /home/ec2-user/log-upload.log 2>&1

Confirm the entry:

sudo crontab -l

Step 7: Verify Logs in S3

aws s3 ls s3://my-ec2-logs-bucket/

Expected:

2024-03-10 12:00:00    12345 nginx-logs-2024-03-10-1200.log

πŸ”Ή Challenge 2: Modify an EBS Volume size and verify that it expands without rebooting the instance

Answer:

Step 1: Identify Attached Volume

  • AWS Console β†’ EC2 β†’ Instances β†’ Storage tab.

Or run:

lsblk

Example:

NAME    MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
xvda    202:0    0    8G  0 disk
└─xvda1 202:1    0    8G  0 part /

On Nitro-based instances (t3, m5, c6i and newer) the root disk shows up as nvme0n1 with partition nvme0n1p1. Use those names in the commands below, for example sudo growpart /dev/nvme0n1 1.

Step 2: Modify EBS Volume

  • Console:
    • Go to EC2 β†’ Volumes β†’ Select Volume β†’ Modify Volume β†’ Change to 16GB β†’ Confirm.

CLI:

aws ec2 modify-volume --volume-id vol-0abcdef1234567890 --size 16
# wait until the state is "optimizing" or "completed" before growing the partition
aws ec2 describe-volumes-modifications --volume-ids vol-0abcdef1234567890 --query "VolumesModifications[0].ModificationState"
aws ec2 describe-volumes --volume-ids vol-0abcdef1234567890 --query "Volumes[*].{Size:Size}"

Expected:

[ { "Size": 16 } ]

Step 3: Check New Size

lsblk

Expected:

xvda    202:0    0   16G  0 disk
└─xvda1 202:1    0    8G  0 part /

Step 4: Expand Partition (No Reboot)

sudo growpart /dev/xvda 1
lsblk

Expected:

xvda    202:0    0   16G  0 disk
└─xvda1 202:1    0   16G  0 part /

Step 5: Resize Filesystem

xfs:

sudo xfs_growfs -d /

ext4:

sudo resize2fs /dev/xvda1

Step 6: Final Check

lsblk
df -h

Expected:

Filesystem      Size  Used Avail Use% Mounted on
/dev/xvda1       16G    2G   14G   10% /

βœ… EBS volume expanded from 8GB to 16GB without rebooting!

πŸ”Ή Challenge 3: Manually attach an Elastic IP (EIP) to your running EC2 instance

Answer:

Step 1: Allocate an Elastic IP

  • Go to AWS Console β†’ EC2 β†’ Elastic IPs.
  • Click Allocate Elastic IP address.
  • Choose Amazon’s pool of IPv4 addresses.
  • Click Allocate.
  • Copy the allocated Elastic IP.

Step 2: Attach the Elastic IP to the EC2 Instance

  • Go to AWS Console β†’ EC2 β†’ Elastic IPs.
  • Select the allocated EIP.
  • Click Actions β†’ Associate Elastic IP address.
  • Choose Instance and select your running EC2.
  • Click Associate.

Step 3: Verify the Elastic IP on the EC2 Instance

SSH into your EC2 and run:

curl ifconfig.me

Expected Output:

3.120.45.67

This confirms that the Elastic IP is successfully attached.


πŸ”Ή Challenge 4: Enable CloudWatch Monitoring on your EC2 instance and view its CPU utilization logs

Answer:

Step 1: Attach an IAM Role for CloudWatch Monitoring

  • Go to AWS Console β†’ IAM β†’ Roles.
  • Click Create Role.
  • Trusted Entity: AWS Service β†’ EC2
  • Attach Policies:
    • Search for and attach CloudWatchAgentServerPolicy
  • Name the Role: EC2-CloudWatch-Role
  • Click Create Role
  • Attach role to EC2:
    • Go to EC2 β†’ Instances β†’ Select your instance
    • Click Actions β†’ Security β†’ Modify IAM Role
    • Choose EC2-CloudWatch-Role

Step 2: Install & Configure CloudWatch Agent on EC2

1️⃣ Connect to EC2 via SSH

ssh -i your-key.pem ec2-user@your-ec2-public-ip

2️⃣ Install CloudWatch Agent

  • Amazon Linux:
sudo yum install -y amazon-cloudwatch-agent
  • Ubuntu:
# The agent is not in the Ubuntu archive; install the .deb from AWS
wget https://amazoncloudwatch-agent.s3.amazonaws.com/ubuntu/amd64/latest/amazon-cloudwatch-agent.deb
sudo dpkg -i -E ./amazon-cloudwatch-agent.deb

3️⃣ Create CloudWatch Agent Configuration

sudo nano /opt/aws/amazon-cloudwatch-agent/etc/cloudwatch-config.json

Paste:

{
  "metrics": {
    "append_dimensions": {
      "InstanceId": "${aws:InstanceId}"
    },
    "metrics_collected": {
      "cpu": {
        "measurement": ["cpu_usage_active"],
        "metrics_collection_interval": 60,
        "totalcpu": true
      }
    }
  }
}

4️⃣ Start the CloudWatch Agent

sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config \
  -m ec2 \
  -c file:/opt/aws/amazon-cloudwatch-agent/etc/cloudwatch-config.json \
  -s

5️⃣ Verify the Agent is Running

sudo systemctl status amazon-cloudwatch-agent

Expected Output:

● amazon-cloudwatch-agent.service - Amazon CloudWatch Agent
   Active: active (running)

Optional: turn on detailed monitoring to get 1-minute EC2 metrics instead of the default 5-minute ones:

aws ec2 monitor-instances --instance-ids i-0123456789abcdef0

Step 3: View CPU Utilization in CloudWatch

  • Go to AWS Console β†’ CloudWatch β†’ Metrics
  • Click All Metrics β†’ EC2 β†’ Per-Instance Metrics
  • Select CPUUtilization
  • View the CPU usage graph.

The agent's own metric (cpu_usage_active) is published under All metrics β†’ CWAgent β†’ InstanceId.

πŸ”Ή Challenge 5: Set up an Auto Scaling Group (ASG) that automatically adds or removes instances based on traffic

Answer:

Step 1: Create a Launch Template for EC2 Instances

  • Go to AWS Console β†’ EC2 β†’ Launch Templates β†’ Click Create Launch Template.
  • Template Name: my-asg-template
  • AMI: Amazon Linux 2023
  • Instance Type: t3.micro (or a suitable type)
  • Key Pair: Select an existing key
  • IAM Role: Attach EC2-CloudWatch-Role (optional for monitoring)
  • Security Group:
    • Allow HTTP (port 80)
    • Allow SSH (port 22)
  • Click Create Launch Template

Step 2: Create an Auto Scaling Group

  • Go to EC2 β†’ Auto Scaling Groups β†’ Click Create Auto Scaling Group
  • Name: my-asg
  • Launch Template: my-asg-template
  • Set Instances:
    • Min: 1
    • Desired: 2
    • Max: 5
  • (Optional) Attach ALB (Application Load Balancer)
  • Scaling Policy:
    • Choose Target Tracking Scaling
    • Metric: CPU Utilization
    • Target: 50%
  • Click Create Auto Scaling Group

Step 3: Configure Auto Scaling Policies

  • Go to EC2 β†’ Auto Scaling Groups β†’ Select my-asg
  • Scaling Policies β†’ Add Policy:
    • Type: Target Tracking Scaling
    • Metric: CPU Utilization
    • Target Value: 50%

Step 4: Verify Auto Scaling Group

Check Scaling Activities:

aws autoscaling describe-scaling-activities --auto-scaling-group-name my-asg

Stress Test to Trigger Scaling:

ssh -i my-key.pem ec2-user@<instance-ip>
sudo dnf install -y stress-ng
stress-ng --cpu 2 --timeout 300s

List Instances in ASG:

aws autoscaling describe-auto-scaling-groups --auto-scaling-group-name my-asg \
--query "AutoScalingGroups[*].Instances[*].InstanceId"

πŸ”Ή Challenge 6: Use AWS Systems Manager (SSM) Session Manager to connect to an EC2 instance without SSH keys

Answer:

Step 1: Attach an IAM Role to EC2 for SSM Access

  • Go to AWS Console β†’ IAM β†’ Roles β†’ Click Create Role
  • Trusted Entity: AWS Service β†’ EC2
  • Attach Policy: AmazonSSMManagedInstanceCore
  • Role Name: EC2-SSM-Role
  • Click Create Role
  • Attach role to EC2:
    • Go to EC2 β†’ Instances β†’ Select instance
    • Click Actions β†’ Security β†’ Modify IAM Role
    • Choose EC2-SSM-Role

Using CLI:

# CLI alternative to the console steps (trust-policy.json is the EC2 trust policy shown earlier)
aws iam create-role --role-name EC2-SSM-Role --assume-role-policy-document file://trust-policy.json
aws iam attach-role-policy --role-name EC2-SSM-Role --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
aws iam create-instance-profile --instance-profile-name EC2-SSM-Role
aws iam add-role-to-instance-profile --role-name EC2-SSM-Role --instance-profile-name EC2-SSM-Role
aws ec2 associate-iam-instance-profile --instance-id i-0abcdef1234567890 --iam-instance-profile Name=EC2-SSM-Role

Step 2: Enable SSM Agent on EC2

  • If it is missing (it comes preinstalled on Amazon Linux 2023 and Ubuntu AMIs):

Amazon Linux:

sudo yum install -y amazon-ssm-agent

Ubuntu:

# Ubuntu ships the agent as a snap
sudo snap install amazon-ssm-agent --classic
sudo systemctl enable --now snap.amazon-ssm-agent.amazon-ssm-agent.service

Start and Enable:

sudo systemctl start amazon-ssm-agent
sudo systemctl enable amazon-ssm-agent

Check Agent:

sudo systemctl status amazon-ssm-agent

Step 3: Connect Using SSM Session Manager

  • Console:
    • AWS Console β†’ Systems Manager β†’ Session Manager
    • Click Start Session β†’ Select EC2 instance β†’ Start Session

CLI (needs the Session Manager plugin for the AWS CLI on your machine):

aws ssm start-session --target i-0abcdef1234567890

βœ… You now have a secure shell access without SSH keys

Step 4: Disable SSH Access for Security (Optional)

# Simplest option: remove the port 22 rule from the security group.
# To turn the daemon off as well:
sudo systemctl stop sshd
sudo systemctl disable sshd

πŸ”Ή Challenge 7: Install Apache and Deploy a WordPress Site on one EC2 instance and install MySQL on another instance

Answer:

Step 1: Launch Two EC2 Instances

WordPress EC2 Instance:

  • AMI: Amazon Linux 2023 (the commands below are for Amazon Linux)
  • Instance Type: t3.micro
  • Security Group:
    • Allow HTTP (80)
    • Allow SSH (22)
    • Allow outbound to MySQL EC2 on port 3306

MySQL EC2 Instance:

  • AMI: Amazon Linux 2023 (the commands below are for Amazon Linux)
  • Instance Type: t3.micro
  • Security Group:
    • Allow MySQL (3306) only from the WordPress EC2 private IP
    • Allow SSH (22)

Find WordPress EC2 Private IP:

TOKEN=$(curl -sX PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/local-ipv4

Step 2: Install Apache & WordPress on WordPress EC2

ssh -i my-key.pem ec2-user@<wordpress-public-ip>

1️⃣ Install Apache, PHP, Extensions:

sudo yum update -y
sudo yum install -y httpd php php-mysqlnd php-fpm php-json php-mbstring php-xml php-gd wget unzip

2️⃣ Start Apache:

sudo systemctl start httpd
sudo systemctl enable httpd

3️⃣ Install WordPress:

cd /var/www/html
sudo wget https://wordpress.org/latest.zip
sudo unzip latest.zip
sudo mv wordpress/* .
sudo rm -rf wordpress latest.zip

4️⃣ Configure Database Connection:

sudo cp wp-config-sample.php wp-config.php
sudo nano wp-config.php

Modify:

define('DB_NAME', 'wordpress_db');
define('DB_USER', 'admin');
define('DB_PASSWORD', 'your-secure-password');
define('DB_HOST', '<mysql-private-ip>');

5️⃣ Permissions & Restart Apache:

sudo chown -R apache:apache /var/www/html
sudo chmod -R 755 /var/www/html
sudo systemctl restart httpd

6️⃣ Verify: Open: http://<wordpress-public-ip>

Step 3: Install MySQL on MySQL EC2

ssh -i my-key.pem ec2-user@<mysql-public-ip>

1️⃣ Install MySQL:

sudo yum update -y
sudo yum install -y mariadb105-server

2️⃣ Start MySQL:

sudo systemctl start mariadb
sudo systemctl enable mariadb

3️⃣ Secure Installation:

sudo mysql_secure_installation

4️⃣ Create DB & User (open the MariaDB shell with sudo mysql):

CREATE DATABASE wordpress_db;
CREATE USER 'admin'@'<wordpress-private-ip>' IDENTIFIED BY 'your-secure-password';
GRANT ALL PRIVILEGES ON wordpress_db.* TO 'admin'@'<wordpress-private-ip>';
FLUSH PRIVILEGES;

5️⃣ Update MySQL Bind Address (on Amazon Linux 2023 the MariaDB server config lives in /etc/my.cnf.d/):

sudo nano /etc/my.cnf.d/mariadb-server.cnf

Update:

[mysqld]
bind-address = 0.0.0.0

Restart:

sudo systemctl restart mariadb

Step 4: Configure Security Groups

  • WordPress EC2:
    • HTTP (80): Anywhere
    • SSH (22): Admin IP
    • Outbound MySQL (3306): to MySQL private IP
  • MySQL EC2:
    • Inbound MySQL (3306): from WordPress private IP
    • SSH (22): Admin IP

Step 5: Store Apache Logs to S3

1️⃣ Create S3 Bucket:

aws s3 mb s3://my-apache-logs-bucket

2️⃣ Attach IAM Role:

  • IAM β†’ Roles β†’ Create Role
  • Service: EC2
  • Policy: AmazonS3FullAccess (or custom)
  • Name: EC2-S3-Logging
  • Attach to WordPress EC2

3️⃣ Upload Script:

sudo nano /usr/local/bin/upload-logs.sh

Paste:

#!/bin/bash
LOG_FILE="/var/log/httpd/access_log"
S3_BUCKET="s3://my-apache-logs-bucket"
DATE=$(date +"%Y-%m-%d-%H%M")
aws s3 cp "$LOG_FILE" "$S3_BUCKET/apache-logs-$DATE.log"

4️⃣ Make Executable:

sudo chmod +x /usr/local/bin/upload-logs.sh

5️⃣ Add to Cron:

# Amazon Linux 2023 does not ship cron by default
sudo dnf install -y cronie
sudo systemctl enable --now crond
sudo crontab -e

Add:

0 * * * * /usr/local/bin/upload-logs.sh >> /var/log/upload-logs.log 2>&1

Step 6: Verification

1️⃣ WordPress: Visit http://<wordpress-public-ip>

2️⃣ MySQL from WordPress (install the client first with sudo dnf install -y mariadb105):

mysql -u admin -p -h <mysql-private-ip> -D wordpress_db

3️⃣ Check S3:

aws s3 ls s3://my-apache-logs-bucket/

Expected:

2024-03-12 12:00:00    12345 apache-logs-2024-03-12-1200.log

πŸ”Ή Challenge 8: Create AMI from WordPress Instance and Snapshot from MySQL Volume as a backup

Answer:

Step 1: Create AMI from WordPress EC2

  • Go to EC2 β†’ Instances β†’ Select WordPress Instance
  • Click Actions β†’ Image and Templates β†’ Create Image
  • Set:
    • Name: WordPress-AMI-Backup
    • Description: Backup of WordPress EC2
    • No Reboot: βœ…
  • Click Create Image
  • Go to EC2 β†’ AMIs to verify

Step 2: Create Snapshot of MySQL Volume

  • Go to EC2 β†’ Volumes
  • Select MySQL EBS volume
  • Click Actions β†’ Create Snapshot
  • Set:
    • Name: MySQL-DB-Snapshot
    • Description: Backup of MySQL EBS Volume
  • Click Create Snapshot
  • Go to EC2 β†’ Snapshots to verify
Scenario Based:

πŸ”Ή Challenge 9:
Your company found AWS account bills getting too high, and asked you to install an open-source FinOps Tool called
OpenOps in an EC2 instance and find out different ways to save cloud bills.

Follow these instructions from this article and do the below:

  1. Launch an EC2 instance and configure security groups.
  2. Install Docker and Docker Compose on the EC2 instance.
  3. Install and Configure OpenOps
  4. Set up AWS Workflows.

How to Participate?

βœ… Complete the tasks and challenges.
βœ… Document your progress and key takeaways on GitHub ReadMe, Medium, or Hashnode.
βœ… Share the above in a LinkedIn post tagging me (Sandip Das) and use #60DaysDevOps to engage with the community!

Explore past #60DaysOfDevOps challenges and their solutions here:

AWS Global Infrastructure & EC2 Basics (60 Days DevOps Challenge Day 13)
Docker Mini Projects (60 Days DevOps Challenge Day 12)
Making Docker Containers Production-Ready (60 Days DevOps Challenge Day 11)
Building & Running Multi-Arch Docker Containers (60 Days DevOps Challenge Day 10)
Docker Networking, Volumes & Compose (60 Days DevOps Challenge Day 9)
Docker Basics (60 Days DevOps Challenge Day 8)
AWS Cloud Automation with Python & Boto3 (60 Days DevOps Challenge Day 7)
Advanced Python For DevOps (60 Days of DevOps Challenge Day 6 )
Python Basics for DevOps (60 Days of DevOps Challenge Day 5 )
Git Advanced - Rebase, Cherry-pick, Conflict Resolution (60 Days of DevOps Challenge: Day 4)
Git & GitHub - Basics, Branching, Merging, PRs (60 Days DevOps Challenge: Day 3)
Linux Shell Scripting & Automation (60 Days DevOps Challenge: Day 2)
Linux Basics - Commands, File System, Users & Permissions (60 Days DevOps Challenge: Day 1)
You may also like:

⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:

Share this post