How to Use User Data in EC2 Instances
Use
user data in EC2 to run scripts or commands automatically when an instance starts. You provide the script in the User data field during instance launch, and it executes on the first boot to configure the instance.Syntax
User data is a script or set of commands provided as plain text or base64-encoded text when launching an EC2 instance. It runs automatically as the root user on the first boot.
Key parts:
- Script content: Shell script (Linux) or PowerShell (Windows).
- User data field: Input area in the EC2 launch wizard or API.
- Execution: Runs only once at instance start.
bash
#!/bin/bash
# Example user data script for Linux EC2
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpdExample
This example shows a user data script that installs and starts a web server (Apache) on a Linux EC2 instance automatically when it launches.
bash
#!/bin/bash yum update -y yum install -y httpd systemctl start httpd systemctl enable httpd echo "<html><h1>Welcome to EC2</h1></html>" > /var/www/html/index.html
Output
On instance launch, Apache web server is installed, started, and enabled to run on boot. The default web page shows 'Welcome to EC2'.
Common Pitfalls
- Script format: User data must start with a proper shebang (e.g.,
#!/bin/bash) for Linux or#!powershellfor Windows. - One-time execution: User data runs only on the first boot; changes after launch won't rerun it.
- Permissions: Commands run as root, so no need for
sudobut including it is safe. - Encoding: If using the API, user data must be base64-encoded.
- Debugging: Check
/var/log/cloud-init-output.logon Linux for errors.
bash
# Wrong way (missing shebang): yum update -y # Right way: #!/bin/bash yum update -y
Quick Reference
| Concept | Description |
|---|---|
| User data script | Shell or PowerShell script run at first boot |
| Shebang line | Required at script start (e.g., #!/bin/bash) |
| Execution time | Runs only once when instance launches |
| Permissions | Runs as root user |
| Debug logs | Check /var/log/cloud-init-output.log on Linux |
| Encoding | Base64 encode when using API calls |
Key Takeaways
User data scripts automate instance setup by running commands at first boot.
Always start Linux user data scripts with #!/bin/bash for proper execution.
User data runs only once; changes require instance restart or manual execution.
Check cloud-init logs to troubleshoot user data script issues.
When using APIs, base64-encode user data before sending.