An EC2 instance's user-data Bash script sometimes fails half-way, and you cannot see why. How do you debug and harden it?
BeginnerScenarioScenarios: deployments, user management and fleet operations
Answer
Situation read → User data runs once at first boot via cloud-init, as root, with no terminal.
What I'd do →
- Read the logs:
/var/log/cloud-init-output.log(script output) and/var/log/cloud-init.log; the script itself is at/var/lib/cloud/instance/scripts/part-001. - Add
#!/bin/bash,set -Eeuxo pipefail, and anERRtrap that logs the line. - Wait for network and package locks: retry
apt-get updatewith backoff;cloud-init status --waitin dependent steps. - Make steps idempotent so
cloud-init clean && reboot(or rerunning the script) is safe. - Signal completion or failure (for example
cfn-signal, an ASG lifecycle hook, or a tag), so failures are visible.
Why → First-boot scripts fail on timing (network not ready, apt locks), and without logs and signals nobody notices.
Interview tip → Mention baking images with Packer to move most of user data out of boot time.
More on Scenarios: deployments, user management and fleet operations
Write the core of a deploy script with release directories, an atomic symlink switch and rollback.IntermediateDeploy to 10 servers behind an AWS ALB one at a time, removing each from the target group during its deploy. Outline the script.AdvancedAfter a deploy, the health check fails intermittently. Your script must roll back automatically, but only if the failure persists. How?IntermediateImplement a blue/green switch on a single nginx host with a script.AdvancedOnboard 30 engineers: create accounts and install their SSH keys from their GitHub usernames, idempotently.IntermediateAn engineer leaves the company. Write the offboarding steps for Linux servers.Intermediate