Files
k3s-gitops/terraform/aws-infrastructure/scripts/user-data.sh

95 lines
2.3 KiB
Bash

#!/bin/bash
# EC2 User Data Bootstrap Script
# Runs on instance launch
set -e
exec > >(tee /var/log/user-data.log) 2>&1
echo "========================================="
echo "Starting EC2 Bootstrap"
echo "Environment: ${environment}"
echo "Region: ${region}"
echo "========================================="
# Update system
echo "[1/5] Updating system..."
yum update -y
# Install CloudWatch Agent
echo "[2/5] Installing CloudWatch Agent..."
wget https://s3.${region}.amazonaws.com/amazoncloudwatch-agent-${region}/amazon_linux/amd64/latest/amazon-cloudwatch-agent.rpm
rpm -U ./amazon-cloudwatch-agent.rpm
# Install Docker
echo "[3/5] Installing Docker..."
yum install -y docker
systemctl start docker
systemctl enable docker
usermod -a -G docker ec2-user
# Install dependencies
echo "[4/5] Installing dependencies..."
yum install -y git htop vim wget curl jq python3 python3-pip
# Setup health check endpoint
echo "[5/5] Setting up health check..."
mkdir -p /opt/app
cat > /opt/app/health.py << 'PYEOF'
#!/usr/bin/env python3
from http.server import HTTPServer, BaseHTTPRequestHandler
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/health':
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(b'healthy')
else:
self.send_response(404)
self.end_headers()
def log_message(self, format, *args):
pass # Suppress logs
if __name__ == '__main__':
server = HTTPServer(('', 80), Handler)
server.serve_forever()
PYEOF
chmod +x /opt/app/health.py
# Create systemd service
cat > /etc/systemd/system/health-server.service << 'EOF'
[Unit]
Description=Health Check Server
After=network.target
[Service]
Type=simple
User=root
WorkingDirectory=/opt/app
ExecStart=/usr/bin/python3 /opt/app/health.py
Restart=always
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable health-server
systemctl start health-server
# Tag instance
INSTANCE_ID=$(ec2-metadata --instance-id | cut -d " " -f 2)
aws ec2 create-tags \
--resources $INSTANCE_ID \
--tags Key=Bootstrap,Value=Complete \
--region ${region}
echo "========================================="
echo "Bootstrap Complete!"
echo "Instance ID: $INSTANCE_ID"
echo "========================================="