Hey cloud enthusiasts! π
Ever launched an EC2 instance and thought “I wish I could automate all this setup”? Well, you’re in luck! Today we’re diving deep into EC2 User Data - your secret weapon for instance automation.
EC2 User Data lets you execute scripts during instance launch, automating everything from package installation to service configuration. Let’s explore this powerful feature with practical examples!
The Ultimate User Data Script
Here’s a comprehensive MIME-multipart script that works across different Linux distributions:
Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0
--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"
#cloud-config
cloud_final_modules:
- [scripts-user, always]
--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"
#!/bin/bash
# Log all outputs
exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
# Detect Linux distribution
if [ -f /etc/os-release ]; then
. /etc/os-release
OS=$NAME
fi
# Function to create users
create_users() {
# Create admin user with sudo access
useradd -m -s /bin/bash admin
echo "admin:StrongPassword123!" | chpasswd
echo "admin ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/admin
# Create service user
useradd -m -s /bin/bash service_user
mkdir -p /home/service_user/.ssh
chmod 700 /home/service_user/.ssh
}
# Function to configure SSH
configure_ssh() {
# Backup original sshd_config
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
# Update SSH configuration
cat << EOF > /etc/ssh/sshd_config
Port 22
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
AllowUsers admin service_user
EOF
# Add your SSH public key
cat << EOF > /home/service_user/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADA... your-key-here
EOF
chmod 600 /home/service_user/.ssh/authorized_keys
chown -R service_user:service_user /home/service_user/.ssh
}
# Function to install common packages
install_packages() {
if [[ "$OS" == "Ubuntu"* ]] || [[ "$OS" == "Debian"* ]]; then
apt-get update
apt-get install -y curl wget unzip htop nginx
# Configure NGINX
cat << EOF > /var/www/html/index.html
<!DOCTYPE html>
<html>
<head>
<title>Instance Configured Successfully!</title>
</head>
<body>
<h1>Success!</h1>
<p>This instance was configured using EC2 User Data</p>
</body>
</html>
EOF
systemctl enable nginx
systemctl start nginx
elif [[ "$OS" == "Amazon Linux"* ]] || [[ "$OS" == "CentOS"* ]]; then
yum update -y
yum install -y curl wget unzip htop nginx
# Similar NGINX configuration for RHEL-based systems
systemctl enable nginx
systemctl start nginx
fi
}
# Execute functions
create_users
configure_ssh
install_packages
# Restart SSH service
systemctl restart sshd
# Emergency SSH access recovery (uncomment if needed)
#aws s3 cp s3://your-bucket/emergency-key.pub /home/admin/.ssh/authorized_keys
# Final setup verification
echo "Setup completed at $(date)"
# Optional: Install monitoring tools
if [[ "$OS" == "Ubuntu"* ]] || [[ "$OS" == "Debian"* ]]; then
apt-get install -y amazon-cloudwatch-agent
elif [[ "$OS" == "Amazon Linux"* ]] || [[ "$OS" == "CentOS"* ]]; then
yum install -y amazon-cloudwatch-agent
fi
# Start CloudWatch agent
systemctl enable amazon-cloudwatch-agent
systemctl start amazon-cloudwatch-agent
--//--
Understanding the Magic π©
This script does several amazing things:
Cross-Platform Compatibility: Works on Ubuntu, Debian, Amazon Linux, and CentOS
User Management: Creates admin and service users with proper permissions
SSH Security: Configures secure SSH access with key-based authentication
Web Server Setup: Installs and configures NGINX with a custom welcome page
Monitoring: Sets up CloudWatch agent for instance monitoring
Comprehensive Logging: All actions are logged for easy troubleshooting
Pro Tips for Success π
Testing: Always test your User Data scripts in a non-production environment first
Idempotency: Write scripts that can safely run multiple times if needed
Logging: Use the built-in logging to troubleshoot issues
Security: Store sensitive data in AWS Secrets Manager or Parameter Store
Backup: Keep recovery options ready (like the emergency SSH access script)
Emergency Recovery π
Lost SSH access? During instance launch, use this emergency recovery script:
#!/bin/bash
mkdir -p /home/ec2-user/.ssh
aws s3 cp s3://your-emergency-bucket/recovery-key.pub /home/ec2-user/.ssh/authorized_keys
chmod 600 /home/ec2-user/.ssh/authorized_keys
chown -R ec2-user:ec2-user /home/ec2-user/.ssh
systemctl restart sshd
Best Practices π
Keep scripts modular and well-commented
Implement proper error handling
Use cloud-init directives when possible
Consider security implications
Monitor script execution time
Use AWS Systems Manager for complex configurations
When to Use User Data
β
First-time instance configuration
β
Software installation
β
Service configuration
β
User setup
β
Basic security hardening
When to Consider Alternatives
β Complex application deployments
β Frequent configuration changes
β Large-scale orchestration
β Sensitive data handling
Ready to automate your EC2 deployments? Start with this script and customize it to your needs. Remember, the key to successful automation is thorough testing and proper error handling.
Happy automating! βοΈ
#AWS #EC2 #CloudComputing #DevOps #Automation