Guide · Amazon EC2 · Bootstrap Automation

EC2 User Data and Cloud-Init for MCP Server Bootstrap

EC2 user data is a shell script (or cloud-init directive) that runs automatically on the first boot of a new EC2 instance. For MCP server operators, it eliminates manual AMI baking for most deployments: a Launch Template with the right user data script installs Node.js, downloads your application from S3, creates a systemd service unit, and starts your MCP server — all before the first request hits the instance. This guide covers the cloud-init execution model, complete bootstrap scripts with IMDSv2-safe metadata queries, systemd service definitions, run-once idempotency guards, debugging failed bootstraps, and multipart MIME for composing multiple cloud-init directives.

TL;DR

User data runs once on first boot, as root, before any user logs in. Output goes to /var/log/cloud-init-output.log — that's your first debug destination. Write your bootstrap script as a bash shebang script (#!/bin/bash), not as plain shell commands. Use an idempotency guard (if [ ! -f /opt/mcp/.bootstrapped ]) so re-runs (e.g., from AMI creation) do not re-install. Use IMDSv2 for all metadata queries. Download your application tarball from S3 using the instance role — no credentials needed.

Cloud-init execution model

cloud-init is the standard multi-distribution Linux boot automation package. It runs in four stages on first boot:

  1. init-local — reads user data from IMDS, determines boot mode
  2. init — sets hostname, configures network, applies cloud-config directives
  3. config — runs config modules (timezone, SSH keys, package installs)
  4. final — executes user data shell scripts and runs commands

Your user data shell script runs in the final stage, after the instance has full network access. The file /var/lib/cloud/instances/{instance-id}/boot-finished is written when all stages complete.

Key behaviour: user data runs exactly once on instance launch. It does not run again on instance stop/start. If you need re-run on reboot, use a systemd unit that runs at startup, not user data.

Complete MCP server bootstrap script

#!/bin/bash
set -euo pipefail

# Idempotency guard — skip if already bootstrapped
if [ -f /opt/mcp-server/.bootstrapped ]; then
  echo "Already bootstrapped, skipping"
  exit 0
fi

# --- IMDSv2 metadata (region, instance ID) ---
TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" \
  -H "X-aws-ec2-metadata-token-ttl-seconds: 300")

REGION=$(curl -s \
  -H "X-aws-ec2-metadata-token: $TOKEN" \
  "http://169.254.169.254/latest/meta-data/placement/region")

INSTANCE_ID=$(curl -s \
  -H "X-aws-ec2-metadata-token: $TOKEN" \
  "http://169.254.169.254/latest/meta-data/instance-id")

echo "Bootstrapping $INSTANCE_ID in $REGION"

# --- Install Node.js 22 (ARM / Amazon Linux 2023) ---
# NodeSource GPG-signed setup for AL2023 or Ubuntu
curl -fsSL https://rpm.nodesource.com/setup_22.x | bash -
dnf install -y nodejs
node --version

# --- Fetch application from S3 (uses instance role, no credentials needed) ---
aws s3 cp s3://my-mcp-artifacts/app.tar.gz /tmp/app.tar.gz \
  --region "$REGION"

mkdir -p /opt/mcp-server
tar -xzf /tmp/app.tar.gz -C /opt/mcp-server
rm /tmp/app.tar.gz

cd /opt/mcp-server
npm ci --omit=dev

# --- Create environment file (non-secret config only) ---
cat > /opt/mcp-server/.env <<EOF
NODE_ENV=production
PORT=3000
AWS_REGION=$REGION
LOG_LEVEL=info
EOF

# --- Fetch secrets from Secrets Manager into environment file ---
# Secrets Manager returns JSON: {"DB_PASSWORD":"...","API_KEY":"..."}
aws secretsmanager get-secret-value \
  --secret-id mcp/prod/app-secrets \
  --region "$REGION" \
  --query 'SecretString' \
  --output text | \
  python3 -c "
import json, sys
secrets = json.load(sys.stdin)
for k, v in secrets.items():
    print(f'{k}={v}')
" >> /opt/mcp-server/.env

chmod 600 /opt/mcp-server/.env
chown -R ec2-user:ec2-user /opt/mcp-server

# --- Create systemd service unit ---
cat > /etc/systemd/system/mcp-server.service <<'UNIT'
[Unit]
Description=MCP Server
After=network.target
Wants=network-online.target

[Service]
Type=simple
User=ec2-user
WorkingDirectory=/opt/mcp-server
EnvironmentFile=/opt/mcp-server/.env
ExecStart=/usr/bin/node dist/server.js
ExecStop=/bin/kill -SIGTERM $MAINPID
Restart=on-failure
RestartSec=5s
StandardOutput=journal
StandardError=journal
SyslogIdentifier=mcp-server
# Hard memory limit — OOM killer instead of swap
MemoryMax=1G
# Graceful shutdown timeout
TimeoutStopSec=30s

[Install]
WantedBy=multi-user.target
UNIT

# --- Enable and start ---
systemctl daemon-reload
systemctl enable mcp-server
systemctl start mcp-server

# Wait for startup (health check)
for i in $(seq 1 12); do
  HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3000/health || true)
  if [ "$HTTP_CODE" = "200" ]; then
    echo "MCP server healthy after ${i}0s"
    break
  fi
  echo "Waiting for health check (attempt $i/12)..."
  sleep 10
done

# --- Tag instance with bootstrap timestamp ---
aws ec2 create-tags \
  --resources "$INSTANCE_ID" \
  --tags "Key=BootstrappedAt,Value=$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
  --region "$REGION"

# --- Mark bootstrap complete ---
touch /opt/mcp-server/.bootstrapped
echo "Bootstrap complete"

Using user data in a Launch Template

User data must be base64-encoded when passed via the API. The AWS CLI handles this for files:

# Create Launch Template with user data
aws ec2 create-launch-template \
  --launch-template-name mcp-server-lt \
  --version-description "v1" \
  --launch-template-data '{
    "ImageId": "ami-0abcdef1234567890",
    "InstanceType": "m7g.large",
    "IamInstanceProfile": { "Name": "mcp-server-profile" },
    "MetadataOptions": {
      "HttpTokens": "required",
      "HttpEndpoint": "enabled",
      "HttpPutResponseHopLimit": 1
    },
    "BlockDeviceMappings": [{
      "DeviceName": "/dev/xvda",
      "Ebs": {
        "VolumeSize": 30,
        "VolumeType": "gp3",
        "Encrypted": true,
        "DeleteOnTermination": true
      }
    }]
  }' \
  --user-data "$(base64 -w 0 bootstrap.sh)"

# Or reference the file directly with run-instances
aws ec2 run-instances \
  --launch-template LaunchTemplateName=mcp-server-lt,Version=1 \
  --user-data file://bootstrap.sh  # AWS CLI base64-encodes automatically

Debugging bootstrap failures

When a bootstrap fails, the instance launches but your MCP server is not running. Diagnostic steps:

# 1. Connect via SSM Session Manager (no SSH needed)
aws ssm start-session --target i-0abc123def456

# 2. Read cloud-init output log (all stdout/stderr from user data script)
sudo cat /var/log/cloud-init-output.log

# 3. Check cloud-init status
sudo cloud-init status --long

# 4. View systemd service logs
sudo journalctl -u mcp-server -n 100 --no-pager

# 5. Check if bootstrap marker was written
ls -la /opt/mcp-server/.bootstrapped

# 6. Run bootstrap script manually (if idempotency guard not yet set)
sudo bash /opt/mcp-server/bootstrap.sh

If you cannot connect via SSM (instance fully broken), use the EC2 console to retrieve the last 64 KB of system log:

# Retrieve instance console output (last 64 KB of kernel + cloud-init output)
aws ec2 get-console-output \
  --instance-id i-0abc123def456 \
  --latest \
  --output text

Common bootstrap failure causes:

Multipart MIME user data

To combine a cloud-config block (for packages: installs) with a shell script, use multipart MIME. cloud-init processes each part according to its content type:

Content-Type: multipart/mixed; boundary="MIME_BOUNDARY"
MIME-Version: 1.0

--MIME_BOUNDARY
Content-Type: text/cloud-config; charset="utf-8"

#cloud-config
packages:
  - jq
  - htop
  - amazon-cloudwatch-agent
runcmd:
  - systemctl enable amazon-cloudwatch-agent

--MIME_BOUNDARY
Content-Type: text/x-shellscript; charset="utf-8"

#!/bin/bash
set -euo pipefail
# ... your bootstrap script here ...

--MIME_BOUNDARY--

Save this as a file and pass it as user data. The cloud-config part runs first (in the config phase) and installs packages; the shell script runs second (in the final phase). Do not mix the two in a single script — package installs via yum/dnf in a shell script work, but cloud-config's package manager is more robust for handling retries and lock files.

Fetching application updates without AMI rebuilds

Instead of baking new AMIs for every code deploy, structure your bootstrap to pull the application from S3 at launch time. Combined with an Auto Scaling group, new instances get the latest version automatically:

# On deploy: upload new artifact to S3 with a versioned key
VERSION="v$(date +%Y%m%d%H%M%S)"
npm run build
tar -czf app.tar.gz dist/ package.json package-lock.json

aws s3 cp app.tar.gz "s3://my-mcp-artifacts/app-${VERSION}.tar.gz"
# Update the "latest" pointer
aws s3 cp "s3://my-mcp-artifacts/app-${VERSION}.tar.gz" \
  "s3://my-mcp-artifacts/app.tar.gz"

# Trigger rolling update: start instance refresh in Auto Scaling group
aws autoscaling start-instance-refresh \
  --auto-scaling-group-name mcp-server-asg \
  --preferences '{"MinHealthyPercentage": 50, "InstanceWarmup": 120}'

The instance refresh replaces instances in the Auto Scaling group one batch at a time. New instances pull the latest app.tar.gz from S3 during bootstrap. Old instances drain connections and terminate. This achieves a code deploy with no container registry, no image build pipeline, and no downtime — suitable for small teams running Node.js MCP servers.

Related guides