Before you start
By the end of this page you will have the inventory agent running on AWS at a public web address, you will have proved that its database survives a restart, and you will have deleted all of it with nothing left behind on your bill.
If you have not read Part 1, you can still follow along. Each step links the AWS idea back to its explanation there.
What you need on your laptop
| Tool | Check it with | Good answer looks like |
|---|---|---|
| AWS CLI v2 | aws --version | aws-cli/2.x.x … (version 1 will not work for SSO or Step 8). Missing on a Mac? brew install awscli |
| Docker Desktop, running | docker info | A page of details, no “Cannot connect to the Docker daemon” |
| A bash shell | echo $SHELL | /bin/bash or /bin/zsh (the Mac default: do “Prepare your terminal” below first). On Windows use WSL or Git Bash, not PowerShell |
| The code | ls in the project folder | backend db docker-compose.yaml frontend infra … |
| Session Manager plugin (only for Step 8) | session-manager-plugin | A message saying it installed successfully |
And two accounts:
- AWS. One of two kinds of login. Either an SSO login: you sign in through an AWS access portal page that lists your accounts and roles, and your role has administrator rights. Or an IAM user with the
AdministratorAccesspolicy and an access key for the CLI. Do not use the root login (the email you signed up with) for daily work: it can close the whole account, so it should stay locked away. - OpenAI. An API key from platform.openai.com/api-keys, on a project with billing enabled. A few dollars of credit is plenty; this whole guide uses a few cents.
The plan at a glance
The eleven steps fall into five phases. Opening a new shop is a fair picture of it.
Step 5 does the heavy lifting and takes about seven minutes. Everything else is quick.
One-time setup
Do this section once per laptop. Everything here is saved in files, so it survives closing the terminal and restarting the Mac.
0. Check what is already set up
On a laptop you have used before (or in a VS Code terminal), much of this section may already be done. Open a terminal in the project folder (in VS Code: Terminal → New Terminal) and paste this. It contains no # notes, so it works even in a fresh zsh:
echo "== tools"; aws --version; docker --version echo "== shell"; echo "profile=[$AWS_PROFILE] pager=[$AWS_PAGER]"; setopt 2>/dev/null | grep -q interactivecomments && echo "comments ok" || echo "comments OFF" echo "== profiles"; aws configure list-profiles echo "== aws login"; aws sts get-caller-identity --query Arn --output text echo "== docker"; docker info >/dev/null 2>&1 && echo "running" || echo "NOT running" echo "== stacks"; aws cloudformation list-stacks --region us-east-1 --query "StackSummaries[?starts_with(StackName,'inventory-stack-') && StackStatus!='DELETE_COMPLETE'].[StackName,StackStatus]" --output table
aws --version,docker --version- Are the two tools installed? You need
aws-cli/2.x. profile=[…] pager=[…]- Prints the two settings this section saves in
~/.zshrc. Empty brackets mean the setting is missing. setopt | grep interactivecomments- Has zsh been told that
#starts a comment? aws configure list-profiles- The AWS logins saved on this laptop, by name.
sts get-caller-identity --query Arn- Is the current login working, and as whom?
docker info- Is Docker Desktop actually running, not just installed?
list-stacks- Is a deployment from earlier still running (and costing money)?
| You see | Do this |
|---|---|
comments OFF or pager=[] | 1. Prepare your terminal, below |
profile=[], but scaler (your profile) is in the list | echo 'export AWS_PROFILE=scaler' >> ~/.zshrc; export AWS_PROFILE=scaler |
No profile in the list, or Unable to locate credentials | 2. Connect the AWS CLI, below |
Token has expired | aws sso login |
Docker NOT running | Open Docker Desktop and wait until it says it is running |
A stack such as inventory-stack-v1 is listed | An earlier deployment still exists. Step 5 simply updates it; or delete it first with Step 11 |
| Everything fine | Skip to Set your variables. 3. Service-linked roles only ever needs doing once per AWS account |
1. Prepare your terminal
echo 'setopt interactivecomments' >> ~/.zshrc echo 'export AWS_PAGER=""' >> ~/.zshrc setopt interactivecomments export AWS_PAGER=""
setopt interactivecomments- Makes zsh (the Mac's default shell) treat
#as the start of a comment, as bash does. Without it, pasting any block that has a# notein it fails with odd errors such aszsh: unknown sort specifierorcommand not found: #. AWS_PAGER=""- Prints AWS output straight to the screen. Otherwise long JSON opens in a viewer that waits until you press
q. >> ~/.zshrc- Adds the line to the file every new terminal reads at start-up, so you never type it again. The last two lines apply it to the terminal you have open now.
2. Connect the AWS CLI to your account
Pick the option that matches the login you have. Option A if you sign in through an AWS access portal (a page listing your AWS accounts, each with a role such as AdministratorAccess and an Access keys link). Option B if you have an IAM user and an access key.
Option A: SSO login (access portal)
First collect two values. In the access portal, click Access keys next to your role, and copy the SSO start URL and SSO region from the AWS IAM Identity Center credentials section. Then run:
aws configure sso
Answer its questions like this:
- SSO session name
scaler(any short name works)- SSO start URL
- Paste it from the portal. It looks like
https://d-xxxxxxxxxx.awsapps.com/start. - SSO region
- Paste it from the portal, for example
us-west-2. This is only where your login lives. It does not decide where you deploy. - SSO registration scopes
- Press Enter to accept the default.
- A browser opens
- Sign in if asked, then click Allow. Come back to the terminal.
- Account and role
- Picked automatically if you have only one. Otherwise choose the account and role meant for this lab.
- CLI default client Region
us-east-1. It must matchREGIONin the variables below.- CLI default output format
json- CLI profile name
scaler. This is the name the next block uses.
Make that profile the default for every terminal, then check it:
echo 'export AWS_PROFILE=scaler' >> ~/.zshrc export AWS_PROFILE=scaler aws sts get-caller-identity
An SSO login lasts a few hours. When a command says Token has expired or The SSO session associated with this profile has expired, run aws sso login. The first block in Set your variables does this for you when it is needed.
Option B: IAM access key
aws configure
It asks four questions:
- Access Key ID
- The username half of your CLI login. From IAM, your user, Security credentials, Create access key.
- Secret Access Key
- The password half. Shown only once when you create it. Treat it like a bank PIN: never paste it into chat, code or screenshots.
- Default region
us-east-1. Mumbai (ap-south-1) also works and is closer to India; prices differ slightly.- Default output format
json
3. Create the two service-linked roles
aws iam create-service-linked-role --aws-service-name ecs.amazonaws.com aws iam create-service-linked-role --aws-service-name elasticloadbalancing.amazonaws.com
A service-linked role is a permission that an AWS service needs to act inside your account; ECS uses it to attach network cards to your tasks, the load balancer uses it to register targets. Brand-new accounts sometimes do not have them yet, and the first deployment fails in a confusing way.
If you get AccessDenied instead, your role may not be allowed to create IAM roles. Check whether they already exist:
aws iam get-role --role-name AWSServiceRoleForECS --query Role.RoleName aws iam get-role --role-name AWSServiceRoleForElasticLoadBalancing --query Role.RoleName
Two role names printed means you are fine. NoSuchEntity means you need to ask your AWS administrator to create that role.
Set your variables
Every command below uses a few shell variables. A variable is a sticky note the terminal remembers: you write REGION=us-east-1 once, and every later $REGION is replaced with us-east-1. The notes disappear when you close the terminal, so run these four blocks at the start of every new terminal session, from the project folder. Paste each block on its own, in order.
Block 1. Log in again if your SSO login has expired. Does nothing when you are still logged in.
aws sts get-caller-identity >/dev/null 2>&1 || aws sso login
Block 2. The variables.
VERSION=v1 REGION=us-east-1 OPENAI_MODEL=gpt-4o-mini [ -f ~/.inventory-api-key ] || (umask 077; openssl rand -hex 24 > ~/.inventory-api-key) API_KEY=$(cat ~/.inventory-api-key) ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text) ECR=$ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com STACK=inventory-stack-$VERSION CLUSTER=inventory-$VERSION
Block 3. Your OpenAI key. Paste this line alone and press Enter, then paste the key and press Enter. Nothing shows on screen.
read -rs OPENAI_API_KEY
Block 4. Check everything is filled in.
echo "openai: ${#OPENAI_API_KEY} chars | api: ${#API_KEY} chars | $OPENAI_MODEL | $ECR | $STACK | $CLUSTER"VERSION- Goes into every resource name, so v1 and v2 can live side by side. Lowercase letters, digits and dashes, at most 12 characters. Increase it for each new deployment.
REGION- Where everything is built.
us-east-1here; Mumbai (ap-south-1) also works. Keep it the same as the CLI default region you chose above. OPENAI_MODELgpt-4o-miniis the cheapest model with tool calling;gpt-4.1-minigives better answers.API_KEY- The shared password between frontend and backend. The
[ -f … ] ||line creates a random one in~/.inventory-api-keythe first time only, readable by you alone. Every later session reads the same file, so the key never changes. ACCOUNT_ID- Your 12-digit account number, fetched automatically.
$( … )means “run this command and use its output here”. ECR- The address of your private image store, built from your account and region.
read -rs- Asks for the key without showing it (
-s), so it never lands on screen or in your shell history. It must be pasted alone: in a multi-line paste,readtakes the next pasted line as the key.
The eleven steps
Check who you are logged in as
Make sure the CLI is talking to the account you think it is.
aws sts get-caller-identity echo "Account: $ACCOUNT_ID Region: $REGION Registry: $ECR"
sts get-caller-identity- STS is AWS's identity desk. This call asks “who am I?” and works with any login, even one with no other permissions, so it is the safest first check.
"Account"- The 12-digit number of the account every following command will change.
"Arn"- Your full AWS name. For an SSO login, read it in three parts:
assumed-rolemeans you are temporarily wearing a role;AWSReservedSSO_InstructorsAdministratorAccess_…is the role SSO made for your access (here, administrator); the last part is who is wearing it, usually your email. echo "…$ACCOUNT_ID…"- Prints the variables back to you, so you can see they are filled in before anything is built with them.
Create the image repositories
Rent two shelves in ECR, your private image store (ECR in Part 1). First time only.
aws ecr describe-repositories --repository-names inventory-backend --region $REGION >/dev/null 2>&1 \ || aws ecr create-repository --repository-name inventory-backend --region $REGION aws ecr describe-repositories --repository-names inventory-frontend --region $REGION >/dev/null 2>&1 \ || aws ecr create-repository --repository-name inventory-frontend --region $REGION
describe-repositories- Asks “does this repository exist?”
create-repository- Creates an empty, private folder for one image. Every tag you push later (
v1,v2…) is one more version inside it. Only your account can read it. --region $REGION- Says which AWS location to work in. Every command on this page passes it, so nothing lands in a different region by accident.
>/dev/null 2>&1- Throws away that command's output and errors; we only care whether it succeeded.
||- “Or else”: run the create command only if the check failed.
\at line end- The command continues on the next line.
Together this makes the step idempotent: safe to run any number of times. Like pressing a lift button twice, the second press changes nothing.
Build the images and push them to ECR
Pack the frontend and backend into container images, then ship them to your private store.
aws ecr get-login-password --region $REGION | docker login --username AWS --password-stdin $ECR # Build from the project root: the backend Dockerfile copies db/schema.sql docker build --platform linux/amd64 -f backend/Dockerfile -t $ECR/inventory-backend:$VERSION . docker build --platform linux/amd64 -f frontend/Dockerfile -t $ECR/inventory-frontend:$VERSION . docker push $ECR/inventory-backend:$VERSION docker push $ECR/inventory-frontend:$VERSION
get-login-password | docker login- AWS prints a temporary password (valid 12 hours) and the pipe
|hands it straight to Docker, so it never appears on screen. --username AWS --password-stdin $ECR- For ECR the user name is always the literal word
AWS.--password-stdinreads the password from the pipe instead of the command line, so it is not saved in your history.$ECRsays which registry this pass is for. docker build- Follows the Dockerfile line by line: start from Python 3.11, copy the code,
pip installthe libraries. Each line becomes a layer; the build log shows them as[1/6]to[6/6]. Unchanged layers are reused next time, which is why rebuilds are fast. --platform linux/amd64- Build for x86 processors, which our Fargate tasks use. Essential on Apple Silicon Macs (why).
-f backend/Dockerfile- Which recipe to follow.
-t …:v1- The name and tag to stick on the image.
.(the final dot)- The build context: the folder Docker may copy files from. It must be the project root, because the backend needs
db/schema.sqlfrom outside thebackendfolder. docker push- Uploads the image to ECR one layer at a time. Each
Pushedline is one layer; a layer ECR already has showsLayer already existsand is skipped. The finaldigest: sha256:…is the image's fingerprint: the same digest always means exactly the same image.
Reading an image name, piece by piece
123456789012.dkr.ecr.us-east-1.amazonaws.com/inventory-backend:v1 is like a full postal address:
123456789012: your account (the building)dkr.ecr.us-east-1.amazonaws.com: ECR in your region (the city's post office)inventory-backend: the repository (the flat)v1: the tag (which parcel in that flat)
Store the two secrets in Parameter Store
Put the OpenAI key and the internal API key in AWS's safe, so containers can receive them without the keys ever being written into code or configuration (SSM in Part 1).
First, confirm the API key you are about to store is the one saved in ~/.inventory-api-key:
[ "$(cat ~/.inventory-api-key)" = "$API_KEY" ] && echo "API key saved and matches"
If it does not print API key saved and matches, run Block 2 of Set your variables again. Then store both secrets:
aws ssm put-parameter --name /inventory/openai-api-key --type SecureString --value "$OPENAI_API_KEY" --overwrite --region $REGION aws ssm put-parameter --name /inventory/api-key --type SecureString --value "$API_KEY" --overwrite --region $REGION
ssm put-parameter- Saves one value in Parameter Store, part of AWS Systems Manager (SSM). The value goes from your terminal straight to AWS; nothing is written into the project files or the images.
--name /inventory/…- Names look like folder paths, so related secrets group together and permissions can cover a whole folder.
--type SecureString- Encrypt the value with KMS. A plain
Stringwould be readable by anyone who can view parameters. "$OPENAI_API_KEY"- The quotes protect values containing special characters.
--overwrite- Replace the value if it already exists. This is how you rotate a key later: run the same command with the new value.
Deploy the stack: network, disk, servers and front door
Hand the blueprint (infra/inventory-stack.yaml) to CloudFormation and let it build the about 35 resources in the right order.
aws cloudformation deploy \
--region $REGION \
--stack-name $STACK \
--template-file infra/inventory-stack.yaml \
--capabilities CAPABILITY_IAM \
--disable-rollback \
--no-fail-on-empty-changeset \
--parameter-overrides \
Version=$VERSION \
BackendImage=$ECR/inventory-backend:$VERSION \
FrontendImage=$ECR/inventory-frontend:$VERSION \
OpenAIModel=$OPENAI_MODEL \
OpenAIKeyParameterName=/inventory/openai-api-key \
ApiKeyParameterName=/inventory/api-keycloudformation deploy- Creates the stack the first time and updates it on later runs. You never decide between “create” and “update”: CloudFormation compares the blueprint with what exists and does only the difference.
--stack-name- The name for this whole bundle of resources:
inventory-stack-v1. --template-file- The blueprint to build from.
--capabilities CAPABILITY_IAM- An “I agree” checkbox. The template creates IAM roles, and AWS wants your explicit consent before any stack creates permissions.
--disable-rollback- Normally a failed build is torn down automatically. We keep the half-built resources so you can read the error and the logs instead of watching the evidence disappear.
--no-fail-on-empty-changeset- Running the command again with nothing changed is treated as success, not an error.
--parameter-overrides- Fills in the blanks of the template: which version, which images, which model, where the secrets live.
The six blanks, one by one
Version- Added to every resource name, so
v1andv2never clash. BackendImage,FrontendImage- The full ECR addresses from Step 3. ECS pulls exactly these images when it starts a container.
OpenAIModel- Passed to the backend as a setting, so you can switch models by redeploying, without rebuilding the image.
OpenAIKeyParameterName,ApiKeyParameterName- Only the names of the secrets from Step 4, never the values. ECS fetches the values from Parameter Store when a container starts, so the keys never appear in CloudFormation, the console or the logs.
What CloudFormation does during those minutes
deploy first creates a change set, a list of everything it is about to do (like a builder's quote), then executes it. Resources that depend on each other are built in order; independent ones are built in parallel. Roughly:
- Network (under a minute): VPC, two subnets, internet gateway, route table, four security groups.
- Disk (1–2 minutes): EFS file system, a mount target in each subnet, the access point.
- Plumbing (1–2 minutes, in parallel): IAM roles, log groups, the ECS cluster, the private DNS namespace.
- Front door (2–3 minutes): the load balancer, its target group and listener.
- Backend service (about 2 minutes): ECS starts the task, mounts EFS, injects secrets, runs
init_db.py, and waits for the health check to pass. - Frontend service (about 2 minutes): starts after the backend, then registers with the load balancer.
Watch it being built, from a second terminal
Run the variables block in the new terminal first, then repeat this command every half minute:
aws cloudformation describe-stack-events --stack-name $STACK --region $REGION --max-items 12 \ --query "StackEvents[].[Timestamp,LogicalResourceId,ResourceStatus]" --output table
Or open the AWS console, CloudFormation, Stacks, inventory-stack-v1, Events tab. The newest events are at the top.
Check that both services are running
Confirm ECS is keeping one healthy copy of each, and read the backend's start-up log.
aws ecs describe-services --cluster $CLUSTER --services inventory-backend inventory-frontend --region $REGION \
--query "services[].{name:serviceName,desired:desiredCount,running:runningCount,status:status}" --output table
# Backend start-up log
aws logs tail /ecs/inventory-$VERSION/backend --region $REGION --since 15mThe --query option is a filter (in a language called JMESPath) that picks just the fields you care about out of a very large JSON answer. Without it, describe-services prints hundreds of lines.
desiredvsrunningdesiredis how many copies you asked ECS to keep alive;runningis how many are up right now. When they match, ECS is happy. Ifrunningstays at 0, a container keeps crashing: read the log.--output table- Prints the result as a small table instead of JSON, easier to read at a glance.
logs tail … --since 15m- Shows what the backend printed in the last 15 minutes, the same lines you would see in your terminal when running it locally. Add
--followto keep watching live; pressCtrl+Cto stop.
Get the backend's internal address
Read the backend URL from the stack's outputs, and understand why you cannot open it.
aws cloudformation describe-stacks --stack-name $STACK --region $REGION \ --query "Stacks[0].Outputs[?OutputKey=='BackendInternalURL'].OutputValue" --output text
Stack outputs are the builder's handover sheet: the useful addresses and names CloudFormation created, so you do not have to hunt for them in the console.
Test the backend from inside (optional)
Open a shell inside the running frontend container and call the backend the way the frontend does.
ECS Exec is like SSH into a container, but without opening any port: the connection is relayed through AWS Systems Manager, and permission comes from the task role. It needs the Session Manager plugin on your laptop.
TASK_ARN=$(aws ecs list-tasks --cluster $CLUSTER --service-name inventory-frontend --region $REGION --query "taskArns[0]" --output text) aws ecs execute-command --cluster $CLUSTER --task $TASK_ARN --container frontend --interactive --command "/bin/sh" --region $REGION
You are now inside the container. BACKEND_URL and API_KEY are already set there as environment variables:
# 1. Is the backend alive?
python -c "import os,urllib.request; print(urllib.request.urlopen(os.environ['BACKEND_URL']+'/health').read())"
# 2. Ask the agent a question, exactly like the chat page does
python -c "import os,requests; r=requests.post(os.environ['BACKEND_URL']+'/chat', json={'query':'Should I reorder SKU001?','sku_id':'SKU001'}, headers={'X-API-Key':os.environ['API_KEY']}, timeout=90); print(r.status_code, r.text)"
exitOpen the app in your browser
Get the public URL and use the agent.
URL=$(aws cloudformation describe-stacks --stack-name $STACK --region $REGION \ --query "Stacks[0].Outputs[?OutputKey=='FrontendURL'].OutputValue" --output text) echo $URL
It prints something like http://inventory-v1-alb-123456789.us-east-1.elb.amazonaws.com. Open it, and note it is http, not https.
Outputs[?OutputKey=='FrontendURL']- From the stack's handover sheet, pick the one line called
FrontendURL. --output text- Plain text without quotes, so it can be saved straight into the
URLvariable.
A five-minute test script
- Type
SKU001in the SKU box and click Lookup SKU. You should see 100 units, 10 a day, 7 days, 20 safety stock. This proves frontend → backend → database works without OpenAI. - Ask Should I reorder SKU001? Expect “not yet, about 1 day”. This proves the OpenAI key and both tools.
- Ask How much should I order for SKU002? Expect 55 units.
- Ask Inventory is 50, demand is 8 a day, lead time is 5 days. What do I do? The agent should skip the database and use only the calculator.
Experiment: prove the database survives a restart
This is the classroom moment that makes EFS click. Change a product, kill the backend, and check the change is still there.
# a) Change SKU001's stock to 50, from inside the frontend container
TASK_ARN=$(aws ecs list-tasks --cluster $CLUSTER --service-name inventory-frontend --region $REGION --query "taskArns[0]" --output text)
aws ecs execute-command --cluster $CLUSTER --task $TASK_ARN --container frontend --interactive --command "/bin/sh" --region $REGION
python -c "import os,requests; print(requests.post(os.environ['BACKEND_URL']+'/inventory', json={'sku_id':'SKU001','name':'Widget A','current_inventory':50,'avg_demand':10,'lead_time':7,'safety_stock':20}, headers={'X-API-Key':os.environ['API_KEY']}).json())"
exit
# b) Replace the backend task with a brand-new one, and wait until it is healthy
aws ecs update-service --cluster $CLUSTER --service inventory-backend --force-new-deployment --region $REGION
aws ecs wait services-stable --cluster $CLUSTER --services inventory-backend --region $REGIONNow click Lookup SKU for SKU001 again. It shows 50, not 100: the old container is gone, the new one mounted the same EFS drive, and init_db.py left your edit alone because the sample data is only inserted when missing. Ask Should I reorder SKU001? and the answer changes to “yes, reorder 110 units” (reorder point 90 + one more lead time of 70 − the 50 on hand).
Pause the containers to save money (optional)
Stop paying for the containers while nobody is using the app, without deleting anything.
# Pause: zero running copies aws ecs update-service --cluster $CLUSTER --service inventory-frontend --desired-count 0 --region $REGION aws ecs update-service --cluster $CLUSTER --service inventory-backend --desired-count 0 --region $REGION # Resume: backend first, then frontend (1-2 minutes; the database on EFS is kept) aws ecs update-service --cluster $CLUSTER --service inventory-backend --desired-count 1 --region $REGION aws ecs update-service --cluster $CLUSTER --service inventory-frontend --desired-count 1 --region $REGION aws ecs wait services-stable --cluster $CLUSTER --services inventory-backend inventory-frontend --region $REGION
--desired-count tells the service how many copies to keep running (the shift manager's rule from Part 1). Zero means none.
Delete this deployment
Remove every resource the stack created, with one command.
aws cloudformation delete-stack --stack-name $STACK --region $REGION aws cloudformation wait stack-delete-complete --stack-name $STACK --region $REGION # 5-8 minutes echo "Deleted $STACK"
The wait command simply blocks until AWS reports the deletion finished, so you know when it is safe to walk away. CloudFormation deletes in the reverse order it built: services first, then the load balancer, disk, roles and finally the network.
Recap: every command in plain words
One line per command, in the order you ran them. Use it to revise after the lab, or to explain the whole flow to someone in five minutes.
| When | Command | What it does | Everyday picture |
|---|---|---|---|
| One-time setup | setopt interactivecomments | Lets zsh treat # as a comment, so pasted blocks with notes work | Teaching the terminal to skip the margin notes |
export AWS_PAGER="" | Prints AWS output straight to the screen | Taking the result out of the envelope for you | |
aws configure sso | Saves your SSO login details as a named profile | Registering your office ID card | |
export AWS_PROFILE=scaler | Tells every aws command which login to use | Choosing which ID card to show at the door | |
aws sso login | Renews the SSO login, which lasts a few hours | Swiping your card again in the morning | |
aws iam create-service-linked-role | Lets ECS and the load balancer act inside your account | Giving the building staff their own keys | |
| Every session | VERSION=…, REGION=…, … | Short names the terminal remembers for later commands | Sticky notes on the monitor |
read -rs OPENAI_API_KEY | Takes the key without showing or saving it | Typing a PIN on a covered keypad | |
echo "${#OPENAI_API_KEY} chars …" | Checks every variable is filled in | Checking your pockets before leaving home | |
| Step 1 | aws sts get-caller-identity | Shows which account and role you are using | Reading the name on your badge |
| Step 2 | aws ecr create-repository | Creates two private image folders | Renting two shelves in a warehouse |
| Step 3 | aws ecr get-login-password | docker login | Gives Docker a 12-hour pass to upload | A gate pass for the warehouse |
docker build --platform linux/amd64 | Packs code, Python and libraries into one image for AWS's processors | Packing a sealed box | |
docker push | Uploads the image to ECR, layer by layer | Shipping the box to the warehouse | |
| Step 4 | aws ssm put-parameter --type SecureString | Stores the two keys encrypted in Parameter Store | Locking the keys in a safe |
| Step 5 | aws cloudformation deploy | Builds the network, disk, containers and load balancer from the blueprint | Handing the plans to a builder |
| Step 6 | aws ecs describe-services | Shows how many copies of each service are running | A head count of staff on shift |
aws logs tail | Shows what the app printed | Reading the shop's diary | |
| Step 9 | aws cloudformation describe-stacks … Outputs | Reads the addresses the stack created | The builder's handover sheet |
curl -w "%{http_code}" | Tests the address without a browser | Knocking on the door directly | |
| Step 10 | aws ecs update-service --desired-count 0 | Stops the containers, keeps everything else | Switching off the lights for the night |
| Step 11 | aws cloudformation delete-stack | Removes everything the stack built | Demolishing the shop, keeping the warehouse |
Updating a running deployment
You will change code far more often than you build new infrastructure. Pick the smallest update that does the job.
Changed only the frontend code
docker build --platform linux/amd64 -f frontend/Dockerfile -t $ECR/inventory-frontend:$VERSION . docker push $ECR/inventory-frontend:$VERSION aws ecs update-service --cluster $CLUSTER --service inventory-frontend --force-new-deployment --region $REGION
Changed only the backend code (the database is kept)
docker build --platform linux/amd64 -f backend/Dockerfile -t $ECR/inventory-backend:$VERSION . docker push $ECR/inventory-backend:$VERSION aws ecs update-service --cluster $CLUSTER --service inventory-backend --force-new-deployment --region $REGION
--force-new-deployment tells ECS to start fresh tasks, which pull the image again. It is a rolling update: the new task starts, passes its health check, and only then is the old one stopped. Users see no downtime. Watch it with:
aws ecs describe-services --cluster $CLUSTER --services inventory-backend --region $REGION \ --query "services[0].events[:5].message" --output table
Changed a setting (model, CPU, memory)
Re-run Step 5 with the new value, for example OpenAIModel=gpt-4.1-mini. CloudFormation compares the new blueprint with what exists and changes only the difference: here, a new task definition revision for the backend and a rolling update. Nothing else is touched.
A whole new version alongside the old one
Set VERSION=v2, re-run the variables block, then Steps 3, 5, 6 and 9. Version 1 keeps serving at its own URL while you test version 2. When you are happy, delete v1:
aws cloudformation delete-stack --stack-name inventory-stack-v1 --region $REGION
Full cleanup: remove everything
Use this at the end of a course, or whenever you want your AWS bill for this project to be zero.
A. Delete every version's stack
STACKS=$(aws cloudformation list-stacks --region $REGION \ --query "StackSummaries[?starts_with(StackName,'inventory-stack-') && StackStatus!='DELETE_COMPLETE'].StackName" --output text) echo "Deleting: $STACKS" for S in $STACKS; do aws cloudformation delete-stack --stack-name $S --region $REGION; done for S in $STACKS; do aws cloudformation wait stack-delete-complete --stack-name $S --region $REGION; done
The first command collects the names of every stack starting with inventory-stack- that is not already deleted. The two loops delete them all, then wait for each.
B. Delete the shared images and secrets
aws ecr delete-repository --repository-name inventory-backend --force --region $REGION aws ecr delete-repository --repository-name inventory-frontend --force --region $REGION aws ssm delete-parameter --name /inventory/openai-api-key --region $REGION aws ssm delete-parameter --name /inventory/api-key --region $REGION
--force deletes a repository even though it still contains images.
C. Prove nothing is left
Every one of these should print an empty list ([]) or an empty table.
aws cloudformation list-stacks --region $REGION --query "StackSummaries[?starts_with(StackName,'inventory-stack-') && StackStatus!='DELETE_COMPLETE'].[StackName,StackStatus]" --output table aws ecr describe-repositories --region $REGION --query "repositories[?starts_with(repositoryName,'inventory-')].repositoryName" aws ssm get-parameters-by-path --path /inventory --region $REGION --query "Parameters[].Name" aws efs describe-file-systems --region $REGION --query "FileSystems[?Name && starts_with(Name,'inventory-')].FileSystemId" aws elbv2 describe-load-balancers --region $REGION --query "LoadBalancers[?starts_with(LoadBalancerName,'inventory-')].LoadBalancerName" aws ec2 describe-vpcs --region $REGION --filters "Name=tag:Name,Values=inventory-*" --query "Vpcs[].VpcId" aws logs describe-log-groups --region $REGION --log-group-name-prefix /ecs/inventory --query "logGroups[].logGroupName" aws ecs list-clusters --region $REGION --query "clusterArns[?contains(@,'inventory-')]"
Troubleshooting
A method that works for any failure
Investigate from the outside in, like a doctor going from symptoms to test results. Ask four questions in order and stop when you find the answer:
- Did CloudFormation fail to build something? Look at the failed stack events.
- Is the ECS service unhappy? Read the service's recent events.
- Did a task start and then stop? Read its stop reason.
- Did my code crash? Read the container's log.
# 1. Which resource failed, and why
aws cloudformation describe-stack-events --stack-name $STACK --region $REGION \
--query "StackEvents[?contains(ResourceStatus,'FAILED')].[LogicalResourceId,ResourceStatusReason]" --output table
# 2. What the service has been doing
aws ecs describe-services --cluster $CLUSTER --services inventory-backend --region $REGION \
--query "services[0].events[:10].message" --output table
# 3. Why tasks stopped (ECS remembers stopped tasks for about an hour)
T=$(aws ecs list-tasks --cluster $CLUSTER --desired-status STOPPED --region $REGION --query "taskArns" --output text)
[ -n "$T" ] && aws ecs describe-tasks --cluster $CLUSTER --region $REGION --tasks $T \
--query "tasks[].{stopped:stoppedReason,container:containers[0].reason}" --output table || echo "no stopped tasks"
# 4. What the code printed
aws logs tail /ecs/inventory-$VERSION/backend --region $REGION --since 30m
aws logs tail /ecs/inventory-$VERSION/frontend --region $REGION --since 30mSymptoms, causes and fixes
| You see | What it means | Fix |
|---|---|---|
Unable to locate credentials | The CLI has no login | SSO: check echo $AWS_PROFILE prints your profile name, then aws sso login. Access key: run aws configure |
Token has expired or The SSO session associated with this profile has expired | Your SSO login timed out (it lasts a few hours) | Run aws sso login, then paste Block 2 of the variables again |
zsh: unknown sort specifier, zsh: command not found: # or bad pattern | zsh is reading a # note as part of the command | setopt interactivecomments (One-time setup, part 1), then paste the block again |
| Some variables are empty after pasting a block | One line failed, and zsh skipped the rest of the paste | Fix that line's error, paste the whole block again, check with Block 4 |
Output stops with (END) or : and waits | The AWS CLI opened its pager | Press q. Set export AWS_PAGER="" (One-time setup, part 1) to stop it |
Cannot connect to the Docker daemon | Docker Desktop is not running | Start it and wait for the whale icon to settle |
no basic auth credentials when pushing | The 12-hour ECR login expired | Re-run the docker login line from Step 3 |
Requires capabilities : [CAPABILITY_IAM] | You left out the consent flag | Add --capabilities CAPABILITY_IAM |
Parameter Version failed to satisfy constraint | VERSION has capitals, spaces or is too long | Use something like v1, v2, demo-3 |
CannotPullContainerError … not found | The image tag in the stack was never pushed, or was pushed to another region | Redo Step 3 with the same $VERSION and $REGION |
ResourceInitializationError: unable to pull secrets | A secret is missing in this region | Redo Step 4, then Step 5 |
exec format error in the log, task keeps restarting | Image built for ARM (Apple Silicon) | Rebuild with --platform linux/amd64, push, force a new deployment |
… reached the limit on the number of vCPUs … | New AWS accounts start with a low Fargate quota | Request an increase in the Service Quotas console, or pass BackendCpu=512 BackendMemory=1024 in Step 5 |
| Step 5 says the service deployment failed (circuit breaker) | The backend crashes at start-up, so ECS gave up | Questions 3 and 4 of the method above show the actual error |
Browser shows ERR_CONNECTION_TIMED_OUT / “This site can't be reached” | The browser switched to https, or your network blocks the address | Run the curl check in Step 9. HTTP 200: use http:// in Incognito or Safari. Timeout: try another network |
Page shows 503 Service Unavailable | The load balancer has no healthy frontend yet | Wait one or two minutes; if it persists, check Step 6 |
| Chat shows Cannot reach the backend | The backend is down or still starting | Check Step 6; wait a minute |
| Chat shows Backend error 403: Invalid API key | Frontend and backend started with different API_KEY values | Re-run Step 4 with your one key, then force a new deployment of both services |
| Chat shows Backend error 502: Agent error (AuthenticationError…) | The OpenAI key is wrong or revoked | Fix OPENAI_API_KEY, re-run Step 4, force a new backend deployment |
| Chat shows … RateLimitError / insufficient_quota | Your OpenAI project has no credit | Add billing at platform.openai.com. No redeploy needed |
Stack is ROLLBACK_COMPLETE and will not update | A first creation failed and was rolled back | Delete the stack (Step 11), then redeploy |
DELETE_FAILED | Network cards or a DNS record were still being released | Wait two minutes, run delete-stack again |
SessionManagerPlugin is not found | Plugin missing on your laptop | Install it (only needed for Step 8) |
AccessDenied / not authorized to perform | Your IAM user or SSO role lacks permissions | IAM user: attach AdministratorAccess for this lab. SSO: ask your AWS administrator for an admin role |
Quick reference
Run the four blocks in Set your variables first.
| I want to… | Command |
|---|---|
| See all my stacks | aws cloudformation list-stacks --region $REGION --query "StackSummaries[?starts_with(StackName,'inventory-stack-') && StackStatus!='DELETE_COMPLETE'].[StackName,StackStatus]" --output table |
| See this stack's URLs and names | aws cloudformation describe-stacks --stack-name $STACK --region $REGION --query "Stacks[0].Outputs" --output table |
| Follow the frontend log live | aws logs tail /ecs/inventory-$VERSION/frontend --follow --region $REGION |
| Follow the backend log live | aws logs tail /ecs/inventory-$VERSION/backend --follow --region $REGION |
| Check what is running | aws ecs describe-services --cluster $CLUSTER --services inventory-backend inventory-frontend --region $REGION --query "services[].{name:serviceName,desired:desiredCount,running:runningCount}" --output table |
| Pause / resume | aws ecs update-service --cluster $CLUSTER --service inventory-backend --desired-count 0 --region $REGION (1 to resume; same for the frontend) |
| Test the app address without a browser | curl -s -o /dev/null -w "HTTP %{http_code}\n" --max-time 15 "$URL" (set URL as in Step 9) |
| Log in again after the SSO login expires | aws sso login, then paste Block 2 of the variables again |
| Redeploy after a code change | aws ecs update-service --cluster $CLUSTER --service inventory-backend --force-new-deployment --region $REGION |
| Delete this version | aws cloudformation delete-stack --stack-name $STACK --region $REGION |
Running this as a two-hour class
The day before
- Deploy and delete the whole thing once yourself, in the same region your learners will use.
- Check every learner has: an AWS account with a budget alert, a working CLI login (
aws sts get-caller-identitysucceeds), AWS CLI v2, Docker Desktop running, an OpenAI key with a spend limit set. - Mac learners: run “Prepare your terminal” from the One-time setup, or pasted blocks with
#notes will fail in zsh. - Windows learners: confirm WSL or Git Bash works. PowerShell does not understand the
\line continuations. - Learners on office networks: Docker image downloads are sometimes blocked. Ask them to run
docker pull python:3.11-slimat home first. - Keep your own stack deployed during class, so you can demo the finished product in the first five minutes.
A session plan
| Time | Activity |
|---|---|
| 0:00 – 0:10 | Show the finished app. Ask: what has to exist for this URL to work? |
| 0:10 – 0:30 | Variables, Steps 1–4 together. While the images build, explain images, tags and ECR. |
| 0:30 – 0:40 | Start Step 5. While it builds, step through “one request, end to end” from Part 1. |
| 0:40 – 1:00 | Steps 6–9 and the test script. Everyone posts their URL in the class chat. |
| 1:00 – 1:15 | The persistence experiment. Break, and help anyone who is stuck using the troubleshooting method. |
| 1:15 – 1:35 | Make a visible change (for example the page title in frontend/app.py), frontend-only update, watch the rolling deployment. |
| 1:35 – 1:45 | Step 10 and the cost calculator from Part 1: what would a forgotten stack cost in a month? |
| 1:45 – 2:00 | Step 11 and full cleanup together. Everyone shows the empty verification output before leaving. |
Next: Part 3 turns Steps 1 to 9 into a pipeline that runs every time you push code.