What is a User Data Script?
A User Data Script automates tasks when an EC2 instance first launches, setting up software, applying updates, or configuring the system. It runs once on first boot and can be written in shell, PowerShell, or cloud-init.
Common Use Cases
- Software Installation: Automatically installs packages like web servers or databases.
- System Updates: Ensures the instance starts with the latest updates.
- Configuration: Applies environment-specific settings for immediate readiness.
Example: Setting Up Apache on Amazon Linux 2
To automatically set up a basic web server on launch:
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "<html><h1>Welcome!</h1></html>" > /var/www/html/index.html
How It Works
- Installs Apache and updates the instance.
- Starts Apache immediately and enables it to auto-start on reboot.
- Creates a Simple Web Page for instant access.
Benefits
- Saves Time: Automates setup steps, no manual SSH needed.
- Consistency: Ensures identical setup across instances.
- Scalability: Useful with Auto Scaling, enabling automatic configuration as new instances launch.