π What is User Data in AWS EC2?
User Data is a set of commands or a script that you can provide when launching an EC2 instance.
This script runs automatically the first time the instance starts.
Itβs commonly used for automating instance configuration like installing packages, updating software, or running initialization tasks.
π οΈ Key Points
- User Data executes as root user.
- By default, it runs only once at the first boot (though you can configure it to run at every restart).
- Supported script types:
- Linux instances β Shell script (bash)
- Windows instances β PowerShell or Batch script
- Common uses:
- Install Apache/Nginx, Docker, or other software.
- Update packages (
apt update,yum update). - Write files (config files, HTML pages).
- Create users or run custom commands.
π Example 1: Linux User Data (Shell Script)
#!/bin/bash
# Update packages
sudo yum update -y
# Install Apache
sudo yum install -y httpd
# Start Apache
sudo systemctl start httpd
sudo systemctl enable httpd
# Add simple webpage
echo "<h1>Hello from EC2 User Data!</h1>" > /var/www/html/index.html
π οΈ Sample User Data Script (Linux β RHEL / Amazon Linux / CentOS)
#!/bin/bash
# Update the system
yum update -y
# Install Apache (httpd)
yum install httpd -y
# Enable and start Apache service
systemctl enable --now httpd
# Create a simple homepage
echo "Hello Apache" > /var/www/html/index.html
# Overwrite with a custom HTML page
echo "<html><h1>Apache Server provisioned by Sumit Bera using User Data</h1></html>" > /var/www/html/index.html
β What this script does
- Updates system packages (
yum update -y) - Installs Apache web server (
yum install httpd -y) - Starts Apache and enables auto-start on reboot (
systemctl enable --now httpd) - Writes content into
/var/www/html/index.htmlso that when you hit the EC2 Public IP in a browser, you see the message: βApache Server provisioned by Sumit Bera using User Dataβ
π To use it:
- While launching EC2 β go to Advanced Details β User Data β paste this script.
- Once the instance boots, Apache will already be running and serving the custom page.
Total Page Visits: 3135 - Today Page Visits: 26
