Bootstrapping with User Data

User data is a startup script EC2 runs the first time an instance boots β€” perfect for installing your app.

User data is a script you attach to an instance. EC2 runs it automatically on first boot, as root, so you can install packages, pull code, and start services with zero manual SSH.

What it is good for

  • Installing runtimes (Node, Python, Docker).
  • Downloading your application artifact.
  • Writing config files and starting the service.

User data makes instances reproducible: launch ten copies and every one configures itself identically. It is the first rung on the ladder toward infrastructure as code.

Example

Example Β· bash
#!/bin/bash
# EC2 user-data: runs once on first boot as root
dnf update -y
dnf install -y nodejs git

cd /opt
git clone https://github.com/acme/myapp.git
cd myapp && npm ci --production

# Install and start the systemd service (defined in the next lesson)
cp deploy/myapp.service /etc/systemd/system/
systemctl enable --now myapp

When to use it

  • A team installs Node.js, clones the app repo, and starts the service via a user-data script so new EC2 instances are production-ready on first boot.
  • An auto-scaling group uses user data to register each new instance with a configuration management server before serving traffic.
  • A data pipeline team bootstraps a worker EC2 instance with Python dependencies and starts the job immediately via user data.

More examples

Pass user-data script at launch

Passes a local shell script as user data so EC2 executes it automatically on the very first boot.

Example Β· bash
aws ec2 run-instances \
  --image-id ami-0c55b159cbfafe1f0 \
  --instance-type t3.micro \
  --key-name my-keypair \
  --user-data file://bootstrap.sh

Bootstrap script installing Node.js app

Installs Node.js, clones the application, installs production dependencies, and starts the systemd service on first boot.

Example Β· bash
#!/bin/bash
set -e
yum update -y
curl -fsSL https://rpm.nodesource.com/setup_20.x | bash -
yum install -y nodejs git

git clone https://github.com/myorg/myapp.git /opt/myapp
cd /opt/myapp && npm ci --omit=dev

systemctl enable myapp
systemctl start myapp

View user-data logs on the instance

Streams the cloud-init output log so you can debug user-data execution without waiting for the app to be live.

Example Β· bash
# SSH into the instance and tail the cloud-init output log
ssh -i my-key.pem ec2-user@<public-ip> \
  'sudo tail -f /var/log/cloud-init-output.log'

Discussion

  • Be the first to comment on this lesson.
Bootstrapping with User Data β€” AWS Deployment | SoundsCode