Why automate at all?
In Part 2 you ran eleven steps by hand. It worked, but think about doing it every time someone changes one line of code, for months, on different laptops.
Manual deployment fails in boring, predictable ways:
- Someone forgets
--platform linux/amd64and the new version crashes on AWS. - Someone builds from a folder with uncommitted experiments in it, and nobody knows what code is actually running.
- Someone's laptop has AWS keys that never expire, and that laptop gets stolen.
- The one person who knows the steps is on leave.
CI and CD in plain words
- CI, continuous integration
- Every change pushed to the shared code is automatically built and checked, so problems are caught within minutes of being introduced, not weeks later.
- CD, continuous delivery / deployment
- Every change that passes the checks is automatically packaged and (in deployment's case) shipped to the servers.
Our pipeline does the CD part fully (build, push, deploy) and a first piece of CI: a smoke test that loads the live page and fails the run if it does not answer. It does not yet run unit tests; adding them is the first exercise at the end of this page.
main walks this conveyor. If anything fails, the run stops, turns red, and prints the evidence you would otherwise collect by hand with the troubleshooting method from Part 2.GitHub Actions in five words
GitHub Actions is GitHub's built-in automation service. Its vocabulary maps neatly onto a kitchen again:
| Word | What it is | Kitchen version |
|---|---|---|
| Workflow | A YAML file in .github/workflows/ describing an automated process | A recipe card |
Trigger (on:) | The event that starts it: a push, a button click, a schedule | “Start cooking when an order arrives” |
| Runner | A fresh Ubuntu virtual machine GitHub lends you for one run, then wipes | A rented kitchen, cleaned after every meal |
| Job | A group of steps that run on one runner | One cook's station |
| Step | One command (run:) or one ready-made plugin (uses:) | “Chop onions”, or “use the dough machine” |
Two more ideas you need for this pipeline:
- Variables
- Plain settings such as the region. Visible in logs. Read as
${{ vars.AWS_REGION }}. - Secrets
- Encrypted settings such as the OpenAI key. GitHub replaces them with
***if they ever appear in a log. Read as${{ secrets.OPENAI_API_KEY }}.
The trust problem: how GitHub logs in to AWS
The runner needs to push images and deploy stacks in your AWS account. How does AWS know the request really comes from your repository, and not from someone pretending?
Option A: store AWS access keys in GitHub (avoid)
You could create an access key and save it as a GitHub secret. It works, but it is like giving a courier company a permanent copy of your house key. The key never expires, it sits outside AWS, and if it leaks through a log, a compromised plugin or a careless copy-paste, it keeps working until you notice.
Option B: OpenID Connect (what we use)
In our setup, GitHub is the courier company, AWS's Security Token Service (STS) is the guard, and the IAM role is the one door. This standard is called OpenID Connect (OIDC).
What is inside the token?
The ID token is a signed note from GitHub. Decoded, the important part looks like this (trimmed):
{
"iss": "https://token.actions.githubusercontent.com",
"aud": "sts.amazonaws.com",
"sub": "repo:your-user@6875450/inventory-agent-aws@1453653749:ref:refs/heads/main",
"repository": "your-user/inventory-agent-aws",
"ref": "refs/heads/main",
"exp": 1762678800
}iss- Issuer: who signed it. AWS checks the signature against the provider you registered.
aud- Audience: who it is meant for. A token meant for another service is rejected.
sub- Subject: exactly which repository and branch is asking. This is what the role's rule matches.
@6875450,@1453653749- New GitHub repositories add the owner's and the repository's permanent number IDs after an
@. A user name can be given up and taken by someone else; an ID never changes, so nobody can pretend to be your repository by grabbing your old name. Older repositories still send the classic formrepo:your-user/inventory-agent-aws:ref:refs/heads/main. You can see which form yours uses withgh api repos/$GITHUB_REPO/actions/oidc/customization/sub. exp- Expiry time. The token itself is only valid for minutes.
The rule on the AWS side
infra/github-oidc.yaml creates the role with this trust policy (“who may wear this badge”):
Action: sts:AssumeRoleWithWebIdentity
Condition:
StringEquals:
token.actions.githubusercontent.com:aud: sts.amazonaws.com
StringLike:
# any branch / tag / workflow_dispatch run of THIS repository only, in both
# subject formats: classic and the newer immutable one
token.actions.githubusercontent.com:sub:
- repo:your-user/inventory-agent-aws:*
- repo:your-user@*/inventory-agent-aws@*:*aud: sts.amazonaws.com- Accept only tokens GitHub made for AWS's identity desk.
- First
subpattern - The classic form, for older repositories.
- Second
subpattern - The newer form with number IDs. Each
@*means “any ID”, but the owner name and the repository name must still match exactly, so another person's repository with the same name is refused. - The final
* - Any branch, tag or manual run of your repository. For production you would tighten it to
…:ref:refs/heads/main, so a feature branch cannot deploy.
The template builds both patterns from the one GitHubRepo value you pass in piece C, so you never type them yourself.
Inside deploy.yml, part by part
Open .github/workflows/deploy.yml alongside this page. Each excerpt below is the real file, followed by what it does and which manual step it replaces.
When it runs
on:
push:
branches: [main]
paths:
- "backend/**"
- "frontend/**"
- "db/**"
- "infra/inventory-stack.yaml"
- ".github/workflows/deploy.yml"
workflow_dispatch:A push to main starts it, but only if something that affects the running app changed. Fixing a typo in the README does not redeploy. workflow_dispatch adds a Run workflow button in the Actions tab for manual runs.
Permissions, and one deployment at a time
permissions:
id-token: write # needed to request the OIDC token for AWS
contents: read
concurrency:
group: deploy-${{ vars.DEPLOY_VERSION || 'v1' }}
cancel-in-progress: falseid-token: write allows the run to ask GitHub for the ID token from the diagram above; without it, step 1 of the handshake is refused. concurrency queues runs: if you push twice in a minute, the second deployment waits for the first instead of both editing the same stack at once.
Settings with sensible defaults
env:
AWS_REGION: ${{ vars.AWS_REGION || 'us-east-1' }}
VERSION: ${{ vars.DEPLOY_VERSION || 'v1' }}
OPENAI_MODEL: ${{ vars.OPENAI_MODEL || 'gpt-4o-mini' }}|| means “if the repository variable is not set, use this default”. The same variable names as Part 2's variables block, now living in GitHub instead of your terminal.
The steps, mapped to Part 2
| Workflow step | What it does | Part 2 |
|---|---|---|
| Check repository configuration | Stops immediately with a clear message if AWS_ROLE_ARN, OPENAI_API_KEY or API_KEY is missing, rather than failing 10 minutes later with a cryptic error | Set variables |
| Checkout | Copies the repository's code at this exact commit onto the runner | Your project folder |
| Configure AWS credentials (OIDC) | The handshake above. After this, every aws command has 1-hour credentials | Step 1 |
| Login to Amazon ECR, ensure repositories exist | Docker login, then create the two repositories only if missing | Steps 2, 3 |
| Store secrets in SSM | Copies the two GitHub secrets into Parameter Store, overwriting | Step 4 |
| Build and push images | Builds both images for linux/amd64, tags them with the commit ID and the version, pushes | Step 3 |
| Deploy CloudFormation stack | Same command as Step 5, with the commit-tagged images | Step 5 |
| Smoke test the public URL | Requests the page until it answers HTTP 200, for up to 5 minutes | Steps 6, 9 |
| Write summary | Puts the URL, region, image tag and model in the run's summary box | Step 9 |
| Diagnostics (only on failure) | Runs the four-question troubleshooting method and prints the answers | Troubleshooting |
Tagging every image with the commit
TAG="${GITHUB_SHA::7}"
echo "TAG=$TAG" >> "$GITHUB_ENV"
docker build --platform linux/amd64 -f backend/Dockerfile -t "$ECR/inventory-backend:$TAG" -t "$ECR/inventory-backend:$VERSION" .GITHUB_SHA is the full ID of the commit being deployed; ::7 keeps its first seven characters, like a1b2c3d. Writing to $GITHUB_ENV makes TAG available to later steps. The stack is then deployed with inventory-backend:a1b2c3d, not :v1.
Deploying safely: first creation versus updates
case "$STATUS" in
CREATE_FAILED|ROLLBACK_COMPLETE|ROLLBACK_FAILED)
echo "Previous first deployment failed ($STATUS) - deleting it before redeploying"
aws cloudformation delete-stack --stack-name "$STACK"
aws cloudformation wait stack-delete-complete --stack-name "$STACK"
STATUS="NONE" ;;
esac
EXTRA=""
[ "$STATUS" = "NONE" ] && EXTRA="--disable-rollback"The step first asks CloudFormation what state the stack is in, then chooses a behaviour:
- No stack yet: create it with
--disable-rollback, so a failure leaves evidence for the diagnostics step (same reasoning as Part 2). - A previous first attempt failed: nothing in it is worth keeping, so delete it and start clean. You never have to clean up by hand before retrying.
- A healthy stack exists: update it with normal rollback. If the new version fails, CloudFormation and the ECS circuit breaker put the previous working version back. A bad commit cannot take the running app down.
The smoke test
for i in $(seq 1 20); do
code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "$URL/" || true)
if [ "$code" = "200" ]; then echo "UI is up (HTTP 200)"; exit 0; fi
echo "attempt $i: HTTP $code - retrying in 15s"; sleep 15
done
echo "::error::UI did not return HTTP 200 within 5 minutes"; exit 1A cook tastes the dish before it leaves the kitchen. Twenty attempts, fifteen seconds apart: the run turns green only if real users can actually load the page. ::error:: is a special message format that GitHub shows as a red annotation on the run.
Diagnostics when something fails
- name: Diagnostics (only on failure)
if: failure()
run: |
...if: failure() makes this step run only when an earlier step failed. It prints failed stack events, ECS service events, task stop reasons and the last 80 log lines of each container, each in a collapsible group. You read one log instead of running four commands.
Inside destroy.yml: a delete button with a safety catch
on:
workflow_dispatch:
inputs:
version:
description: "Deployment version to delete (e.g. v1)"
required: true
default: "v1"
delete_shared:
description: "Also delete the shared ECR repositories and SSM secrets (end of course)"
type: boolean
default: false
confirm:
description: "Type DELETE to confirm"
required: trueThis workflow has no automatic trigger: it only runs when a person clicks Run workflow and fills in a small form. Deleting infrastructure should never happen because of a push.
- Typing
DELETEis the same safety catch GitHub uses when you delete a repository (“type the repository name to confirm”). A misclick cannot destroy anything. - Retry loop: deletion is attempted up to three times, a minute apart, because AWS sometimes needs a moment to release network cards (the
DELETE_FAILEDcase from Part 2). - Verification: the last step lists stacks, repositories, parameters, disks, load balancers, networks and log groups that still exist, and writes the result to the run summary. Empty lines mean nothing is left.
One-time setup
Four short pieces, in this order, all from the terminal. Use the same terminal as Part 2: it already holds $REGION and $OPENAI_API_KEY, and ~/.inventory-api-key exists. New terminal? Paste Part 2's four session blocks first.
Log in to GitHub from the terminal
Install the GitHub CLI and give it permission to push workflow files.
gh --version || brew install gh gh auth status >/dev/null 2>&1 || gh auth login --hostname github.com --git-protocol https --web --scopes workflow gh auth status 2>&1 | grep -q "'workflow'" || gh auth refresh --hostname github.com --scopes workflow gh auth setup-git
gh- GitHub's own command-line tool. Anything you would click on github.com (create a repository, add a secret, watch a run) becomes a command you can paste and repeat. On Linux or WSL, install it from
cli.github.cominstead ofbrew. gh auth login … --web- Signs you in through the browser: the terminal shows a one-time code, you paste it on the page GitHub opens, and click Authorize. It only runs if you are not logged in yet.
--scopes workflow- An extra permission. GitHub refuses any push that adds or changes files in
.github/workflows/without it, because a workflow can run code with your secrets. grep -q "'workflow'" || gh auth refresh- Looks for
workflowin your login's permission list and adds it only if it is missing, so the block is safe to run again. gh auth setup-git- Lets
git pushuse the same login, so git never asks for a password.
Create the repository (do not push yet)
Turn the project folder into a git repository and create a private, empty copy on GitHub.
git init -b main git add -A git status --short | grep -E '[ /]\.env$' && echo "STOP: .env would be committed" || echo ".env not included - good" git commit -m "Inventory Planning Agent on AWS" gh repo create "$(gh api user --jq .login)/inventory-agent-aws" --private --source=. --remote=origin
Then, whether you just created it or already had one:
GITHUB_REPO=$(gh repo view --json nameWithOwner --jq .nameWithOwner); echo $GITHUB_REPO
git init -b main- Starts version tracking in this folder, with
mainas the first branch: the branch the workflow watches. git add -A,git commit- Takes a snapshot of every file.
.gitignorekeeps.env, virtual environments and database files out of it. - The
grepline - A safety check before anything leaves your laptop. A real key pushed to GitHub, even by mistake, is found by scanning bots within minutes.
gh api user --jq .login- Your exact GitHub user name, so there is no typo and no upper/lower-case surprise.
gh repo create … --private --source=. --remote=origin- Creates the repository on GitHub, private, from this folder, and links it under the usual name
origin. There is deliberately no--push. GITHUB_REPO=$( … )- Reads
owner/nameback from GitHub, spelt exactly as GitHub spells it. Pieces C and D use it, and the role's rule must match it character for character.
Create the role GitHub may use
Register GitHub as a trusted login service in AWS and create the one role it may wear.
if aws cloudformation describe-stacks --region $REGION --stack-name github-oidc-inventory-agent >/dev/null 2>&1; then
OIDC_PARAM=""
elif [ -n "$(aws iam list-open-id-connect-providers --query "OpenIDConnectProviderList[?contains(Arn,'token.actions.githubusercontent.com')].Arn" --output text)" ]; then
OIDC_PARAM="CreateOidcProvider=false"
else
OIDC_PARAM="CreateOidcProvider=true"
fi
echo "Provider setting: ${OIDC_PARAM:-keep the earlier value}"
aws cloudformation deploy --region $REGION --stack-name github-oidc-inventory-agent \
--template-file infra/github-oidc.yaml --capabilities CAPABILITY_NAMED_IAM \
--parameter-overrides GitHubRepo=$GITHUB_REPO $OIDC_PARAM
ROLE_ARN=$(aws cloudformation describe-stacks --region $REGION --stack-name github-oidc-inventory-agent \
--query "Stacks[0].Outputs[?OutputKey=='DeployRoleArn'].OutputValue" --output text); echo $ROLE_ARNif … describe-stacks- Does the role stack already exist? Then keep the provider setting it was created with. Passing
falseto a stack that created the provider would make CloudFormation delete it. list-open-id-connect-providers- An AWS account can register GitHub's login service only once. If another project already did, the role reuses it (
false) instead of failing withEntityAlreadyExists. Otherwise the stack creates it (true). CAPABILITY_NAMED_IAM- A stronger consent than Part 2's
CAPABILITY_IAM, needed because this template gives the role a fixed name (github-actions-inventory-agent-deploy). GitHubRepo=$GITHUB_REPO- The only repository whose runs may wear the role. The template turns it into both subject patterns shown in the rule on the AWS side.
ROLE_ARN=$( … )- Saves the role's full address for piece D, so nothing has to be copied by hand.
Add the variables and secrets in GitHub
Tell the workflow which role to use and where to deploy, and give it the two keys.
First check every value is in place. Nothing may be empty:
echo "repo: $GITHUB_REPO | region: $REGION | role: $ROLE_ARN | openai: ${#OPENAI_API_KEY} chars | api key file: $(wc -c < ~/.inventory-api-key) bytes"If openai shows 0, paste read -rs OPENAI_API_KEY on its own line, then your key. Then:
gh variable set AWS_ROLE_ARN --repo $GITHUB_REPO --body "$ROLE_ARN" gh variable set AWS_REGION --repo $GITHUB_REPO --body "$REGION" gh variable set DEPLOY_VERSION --repo $GITHUB_REPO --body "v1" gh variable set OPENAI_MODEL --repo $GITHUB_REPO --body "gpt-4o-mini" printf %s "$(cat ~/.inventory-api-key)" | gh secret set API_KEY --repo $GITHUB_REPO printf %s "$OPENAI_API_KEY" | gh secret set OPENAI_API_KEY --repo $GITHUB_REPO gh variable list --repo $GITHUB_REPO; gh secret list --repo $GITHUB_REPO
gh variable set … --body- Saves a plain setting. Variables are visible in logs, so they are only for things that are not secret.
printf %s … | gh secret set- Sends the key through a pipe, so it never appears on screen or in your shell history.
ghlocks it with the repository's public key on your laptop before upload; GitHub only ever stores the locked copy.printf %sadds no line break, which would otherwise become part of the key. $(cat ~/.inventory-api-key)- The same API key as your Part 2 stack, so a pipeline update never leaves the frontend and backend with different keys (the Backend error 403 problem).
gh … list- Shows names and dates only. A secret's value can never be read back, not even by you.
| Name | Type | Meaning |
|---|---|---|
AWS_ROLE_ARN | variable | The role from piece C. Required. |
AWS_REGION | variable | Where to deploy. Default us-east-1. |
DEPLOY_VERSION | variable | Which versioned stack the pipeline manages. Default v1. If your Part 2 stack inventory-stack-v1 still exists, the pipeline simply updates it. |
OPENAI_MODEL | variable | Default gpt-4o-mini. |
OPENAI_API_KEY | secret | Your OpenAI key. Required. Copied into SSM on every run. |
API_KEY | secret | The shared frontend/backend key, from ~/.inventory-api-key. Required. |
Prefer clicking? The same six live in the repository under Settings → Secrets and variables → Actions: the first four on the Variables tab, the last two on the Secrets tab.
Your first automated deployment
Everything is in place. The first push starts the pipeline, and you can watch it from the terminal:
git push -u origin main sleep 10 gh run watch --repo $GITHUB_REPO $(gh run list --repo $GITHUB_REPO --workflow deploy.yml --limit 1 --json databaseId --jq '.[0].databaseId')
git push -u origin main- Uploads your commit to GitHub.
-uremembers wheremaingoes, so later pushes are justgit push. sleep 10- Gives GitHub a few seconds to notice the push and create the run.
gh run list … --jq '.[0].databaseId'- The ID number of the newest run of
deploy.yml. gh run watch- A live view of that run in your terminal: each step appears with a tick or a cross, refreshed every few seconds, until the run ends.
What you will see
- Steps turn into green ticks one by one. The longest are Build and push images (a few minutes on the first run) and Deploy CloudFormation stack (6–8 minutes when the stack is new, 2–3 minutes for an update).
- When everything is green, the run's Summary page shows a box with the frontend URL, region, image tag and model.
- The same run is visible in the browser: the repository's Actions tab, a spinning yellow dot while it runs.
Total: about 10–12 minutes the first time, about 5 minutes afterwards.
Check what is running
gh run view --repo $GITHUB_REPO --web
URL=$(aws cloudformation describe-stacks --stack-name inventory-stack-v1 --region $REGION --query "Stacks[0].Outputs[?OutputKey=='FrontendURL'].OutputValue" --output text)
curl -s -o /dev/null -w "HTTP %{http_code}\n" --max-time 15 "$URL"
aws ecs describe-task-definition --task-definition inventory-v1-backend --region $REGION --query "taskDefinition.containerDefinitions[0].image" --output text
git log --oneline -1gh run view --web- Opens the latest run's page in your browser, with the summary box and its URL.
curl … "$URL"- Asks the app's address for a page without a browser.
HTTP 200means it is up. describe-task-definition … image- Which image ECS is running right now.
git log --oneline -1- Your latest commit, with its short ID first.
Now make a real change and watch it ship
sed -i '' 's/# Inventory Planning Agent/# Inventory Agent (auto-deployed)/' frontend/app.py git diff --stat git commit -am "Rename the chat page" && git push sleep 10 gh run watch --repo $GITHUB_REPO $(gh run list --repo $GITHUB_REPO --workflow deploy.yml --limit 1 --json databaseId --jq '.[0].databaseId')
sed -i '' 's/old/new/'- Find and replace inside a file: here, the page title. On a Mac the
''after-iis required; on Linux writesed -iwithout it. Editing the line by hand in your editor works just as well. git diff --stat- Shows which files changed: one line in
frontend/app.py. git commit -am- Stages every file git already tracks that has changed, and commits it in one go.
A new run starts on its own. About five minutes later, refresh the URL and the title reads Inventory Agent (auto-deployed). During the update, the old frontend kept serving until the new one passed its health check, so a user in the middle of a chat would not have noticed.
Undo it
git revert --no-edit HEAD && git push
git revert HEAD- Makes a new commit that is the exact opposite of the last one. History keeps both, so everyone can see what happened and when, and the pipeline deploys the result like any other push.
--no-edit- Accepts the ready-made commit message (Revert "Rename the chat page") instead of opening an editor.
Day-2 operations
| I want to… | Do this |
|---|---|
| Ship a code change | Commit and push to main. Rolling update, no downtime. |
| Undo a bad change | git revert --no-edit HEAD && git push (or git revert <bad-commit>). Or open an earlier green run in Actions and click Re-run all jobs: it rebuilds that exact commit. |
| Watch the latest run | gh run watch --repo $GITHUB_REPO $(gh run list --repo $GITHUB_REPO --workflow deploy.yml --limit 1 --json databaseId --jq '.[0].databaseId') |
| Read why a run failed | gh run view --repo $GITHUB_REPO --log-failed |
| Deploy without a code change | gh workflow run deploy.yml --repo $GITHUB_REPO (the Run workflow button) |
| Switch the model | Change the OPENAI_MODEL variable, then Run workflow. |
| Rotate the OpenAI key | Update the OPENAI_API_KEY secret, then Run workflow. The new value is written to SSM and the backend restarts with it. |
| Try v2 next to v1 | Set DEPLOY_VERSION to v2 and run. v1 keeps running at its own URL; destroy it when v2 is confirmed. |
| Pause overnight | Use Step 10 from Part 2. The next pipeline run sets the services back to one task each. |
| Read logs | aws logs tail /ecs/inventory-v1/backend --follow, or CloudWatch, Log groups in the console. |
Tear everything down
Up to four pieces, in this order: the deployment, the role, the repository, the shared images and keys. Each piece needs the ones after it to still exist. In a new terminal, from the project folder, set the two variables first:
REGION=us-east-1 GITHUB_REPO=$(gh repo view --json nameWithOwner --jq .nameWithOwner); echo $GITHUB_REPO
1. Delete the deployment
gh workflow run destroy.yml --repo $GITHUB_REPO -f version=v1 -f delete_shared=false -f confirm=DELETE sleep 10 gh run watch --repo $GITHUB_REPO $(gh run list --repo $GITHUB_REPO --workflow destroy.yml --limit 1 --json databaseId --jq '.[0].databaseId')
gh workflow run destroy.yml- Presses the Run workflow button of the destroy workflow from the terminal.
-f version=v1- Fills in the form: which versioned stack to delete.
-f delete_shared=false- Keep the ECR images and SSM keys, so a later deployment is quick. Use
trueat the end of the course. -f confirm=DELETE- The safety catch. Anything else and the workflow stops without deleting.
Prefer clicking? Actions → Destroy AWS deployment → Run workflow, fill in the same three boxes.
2. Delete the deploy role, from your laptop
aws cloudformation delete-stack --region $REGION --stack-name github-oidc-inventory-agent aws cloudformation wait stack-delete-complete --region $REGION --stack-name github-oidc-inventory-agent aws cloudformation list-stacks --region $REGION --query "StackSummaries[?(starts_with(StackName,'inventory-stack-') || starts_with(StackName,'github-oidc')) && StackStatus!='DELETE_COMPLETE'].[StackName,StackStatus]" --output table
The last command should print an empty table: no inventory stack, no role stack. If piece C created GitHub's provider, it is removed together with the role.
3. Delete the GitHub repository (optional)
gh auth refresh --hostname github.com --scopes delete_repo gh repo delete $GITHUB_REPO --yes gh repo view $GITHUB_REPO 2>&1 | head -1
--scopes delete_repo- Deleting a repository needs its own permission, which
ghdoes not have by default. A browser page opens to approve it. gh repo delete … --yes- Deletes the repository with its Actions history, variables and secrets.
--yesskips the “type the name to confirm” question, so check$GITHUB_REPOfirst: this cannot be undone. gh repo view- Proves it is gone:
Could not resolve to a Repository.
Then tidy your laptop. Your code and its git history stay in the folder:
git remote remove origin gh auth refresh --hostname github.com --remove-scopes delete_repo
git remote remove origin- Forgets the link to the deleted repository.
--remove-scopes delete_repo- Takes the delete permission away again, so a stray command can never delete another repository.
4. Delete the shared images and keys (end of course)
Only needed if you ran step 1 with delete_shared=false:
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 holds images. After all four pieces, the only things left are the two free service-linked roles from Part 2.
Recap: every command in plain words
One line per command, in the order you ran them. Part 2's recap covers the AWS commands this page reuses.
| When | Command | What it does | Everyday picture |
|---|---|---|---|
| A | gh auth login --scopes workflow | Signs the terminal in to GitHub, allowed to push workflow files | A staff card that also opens the kitchen door |
gh auth setup-git | Lets git push use the same login | One card for every door | |
| B | git init, git add, git commit | Takes a labelled snapshot of the project | Sealing and labelling a parcel |
gh repo create --private --source=. | Creates the repository on GitHub and links the folder | Renting a locker for the parcel | |
| C | aws iam list-open-id-connect-providers | Is GitHub already a trusted login service in this account? | Is the courier company already on the guard's list? |
aws cloudformation deploy … github-oidc.yaml | Trusts GitHub and creates the one role it may wear | Telling the guard which courier may enter, and through which door | |
| D | gh variable set | Saves plain settings in the repository | The address written on the box |
printf … | gh secret set | Saves a key, locked before it leaves your laptop | A sealed envelope only the cook may open | |
| Deploy | git push | Uploads the commit and starts the pipeline | Placing the order |
gh run watch | Live view of the run's steps | Watching the kitchen through the window | |
gh run view --web | Opens the run's summary with the URL | Reading the receipt | |
aws ecs describe-task-definition … image | Shows which image, and so which commit, is live | Checking the batch number on the strip | |
gh run rerun | Runs a failed run again after you fixed its cause | Sending the same order back to the kitchen | |
| Change | sed -i, git commit -am, git push | Edits, commits and ships a change | Updating the menu, reprinted automatically |
git revert --no-edit HEAD | Undoes the last commit with a new commit | Printing a correction, not cutting out the article | |
| Tear down | gh workflow run destroy.yml -f … | Presses the delete button, with the form filled in | Closing the shop for good |
aws cloudformation delete-stack … github-oidc-inventory-agent | Removes the role (and the provider, if piece C created it) | Taking the courier off the guard's list | |
gh repo delete --yes | Deletes the repository, its history and secrets | Giving the locker back | |
| If stuck | aws cloudtrail lookup-events | Reads AWS's own record of why a login was refused | Asking the guard why he turned the courier away |
Troubleshooting
| In the Actions log | What it means | Fix |
|---|---|---|
Missing repository configuration: AWS_ROLE_ARN(variable) … | Piece C is not done, or a name is misspelled | Add the listed variables or secrets, re-run |
Not authorized to perform sts:AssumeRoleWithWebIdentity | The role's rule does not match what GitHub sent: a different repository name, GitHub's newer subject format with an old template, a wrong AWS_ROLE_ARN, or a company-wide AWS rule | Run the check in When GitHub cannot log in to AWS below |
Credentials could not be loaded / id-token permission error | The workflow cannot request an ID token | Keep permissions: id-token: write in the workflow file |
| No run appears after a push | Pushed to another branch, or only changed files outside the trigger paths | Push to main, or use Run workflow |
| Deploy CloudFormation stack fails | Something in AWS rejected the change | Open the Diagnostics step; match the error to Part 2's troubleshooting table; push the fix. A failed first creation is cleaned up automatically on the next run |
Smoke test: HTTP 503 for 5 minutes | The frontend never became healthy | Diagnostics shows the frontend log; usually a start-up crash |
| Run is green, chat says Agent error (AuthenticationError) | The OPENAI_API_KEY secret is wrong | Update the secret, Run workflow |
| Chat says Backend error 403 | Frontend and backend hold different API_KEY values (for example Part 2's stack with a different key) | Set the secret to one value, Run workflow, then force a new deployment of both services |
Destroy run: You must type DELETE | The confirm box did not say exactly DELETE | Re-run and type it in capitals |
git push refused: … without workflow scope | Your GitHub login lacks the workflow permission | gh auth refresh --hostname github.com --scopes workflow, then push again |
| Yellow warnings about Node.js 20 or Ubuntu 26 | GitHub announcing future changes to its machines | Nothing; they are warnings, not errors |
gh: command not found | The GitHub CLI is not installed | brew install gh (Mac) or see cli.github.com |
gh repo delete refused | Your login lacks the delete permission | gh auth refresh --hostname github.com --scopes delete_repo |
Piece C prints …=false on a new account | GitHub's provider already exists, from another project | Nothing; the role reuses it |
| Running out of Actions minutes | Private repositories on the free plan have a monthly allowance | Each deploy uses about 10 minutes; public repositories are free |
When GitHub cannot log in to AWS
The run fails at Configure AWS credentials with Not authorized to perform sts:AssumeRoleWithWebIdentity. AWS deliberately does not say why, to avoid helping attackers. But it writes the reason to its own audit log, CloudTrail, and you can read it. From the project folder:
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
echo "== 1. repo: $GITHUB_REPO"
echo "== 2. GitHub variable:"; gh variable list --repo $GITHUB_REPO | grep AWS_ROLE_ARN
echo "== 3. role rule:"; aws iam get-role --role-name github-actions-inventory-agent-deploy --query "Role.AssumeRolePolicyDocument.Statement[0].Condition" --output json
echo "== 4. provider audiences:"; aws iam get-open-id-connect-provider --open-id-connect-provider-arn arn:aws:iam::$ACCOUNT_ID:oidc-provider/token.actions.githubusercontent.com --query ClientIDList --output json
echo "== 5. GitHub subject format:"; gh api repos/$GITHUB_REPO/actions/oidc/customization/sub
echo "== 6. What AWS saw (last 3 attempts):"
aws cloudtrail lookup-events --region $REGION --max-results 3 \
--lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity \
--query "Events[].CloudTrailEvent" --output json \
| python3 -c 'import sys,json
for s in json.load(sys.stdin):
e=json.loads(s); u=e.get("userIdentity",{})
print(e["eventTime"], "|", e.get("errorCode","OK"), "|", u.get("userName"), "|", e.get("errorMessage",""))'cloudtrail lookup-events- CloudTrail records every call to AWS, including refused ones, for 90 days at no cost. Events appear within about 5 to 15 minutes.
--lookup-attributes … AssumeRoleWithWebIdentity- Only GitHub's login attempts.
- The
python3part - Each event is a long JSON document; this prints just four fields per attempt: time, result, who GitHub said it was, and AWS's reason.
| Section | Correct value | If it is different |
|---|---|---|
| 1 | your-user/inventory-agent-aws | Run piece B's GITHUB_REPO line |
| 2 | The role ARN from piece C | gh variable set AWS_ROLE_ARN --repo $GITHUB_REPO --body "arn:aws:iam::$ACCOUNT_ID:role/github-actions-inventory-agent-deploy" |
| 3 | aud is sts.amazonaws.com; sub lists both patterns with your exact owner/name | Make sure infra/github-oidc.yaml has both patterns, then run piece C again |
| 4 | The list contains sts.amazonaws.com | aws iam add-client-id-to-open-id-connect-provider --open-id-connect-provider-arn arn:aws:iam::$ACCOUNT_ID:oidc-provider/token.actions.githubusercontent.com --client-id sts.amazonaws.com |
| 5 | use_default: true; use_immutable_subject: true means the form with @ IDs | Information only: it tells you which pattern in section 3 must match |
| 6, user column | Starts with repo:your-user/inventory-agent-aws: or repo:your-user@…/inventory-agent-aws@…: | Compare it with the patterns in section 3: the first difference is your bug |
| 6, last column | Not authorized to perform sts:AssumeRoleWithWebIdentity | If it mentions service control policy or explicit deny, your organisation blocks GitHub logins: ask your AWS administrator to allow sts:AssumeRoleWithWebIdentity for this role |
After a fix, re-run the failed run instead of pushing again (see Fixed a failed run? Re-run it).
Exercises: make the pipeline yours
Each of these mirrors something real teams do. They are ordered from easiest to hardest.
- Add unit tests before deploying. Write
tests/test_reorder.pythat callscalculate_reorderwith SKU002's numbers and checks the answer contains “55 units”. Add atestjob that installsbackend/requirements.txtpluspytestand runs the tests, then give the deploy jobneeds: test. Now a broken formula can never reach AWS. - Allow only main to deploy. In both of the role's
subpatterns, change the final:*to:ref:refs/heads/mainand run piece C again. Push from a branch with Run workflow and watch it be refused; section 6 of the check above shows the branch in the refused subject. - Require a human approval. Create a GitHub Environment called
productionwith yourself as a required reviewer, and addenvironment: productionto the deploy job. Every deployment now waits for a click. - Shrink the role's permissions. Replace
AdministratorAccesswith a policy that allows only the services the stack uses. Deploy, read the access-denied errors, add what is missing. This is how least privilege is done in practice. - Announce deployments. Add a final step that posts the URL and commit to a Slack or Teams channel through an incoming webhook stored as a secret.
Check your understanding
1. Why is OIDC safer than storing an AWS access key as a GitHub secret?
There is nothing permanent to leak. Even a stolen temporary credential stops working within the hour.
2. You push a change to README.md only. What happens?
The paths: filter starts the workflow only when app code, the schema, the stack template or the workflow itself changes.
3. Why tag images with the commit ID instead of only v1?
Like batch numbers on medicine: v1 gets overwritten by every push, but a1b2c3d always means one specific version of the code.
4. An update deployment fails halfway. What do users see?
Rolling updates only stop the old task after the new one is healthy, and failed updates roll back. Only the very first creation keeps failed resources around, for debugging.
5. Which do you delete first at the end of the course?
The destroy workflow needs the role to log in to AWS. Remove what the role manages first, then the role.
6. What does if: failure() on the diagnostics step do?
On a green run it is skipped; on a red run it collects the evidence for you.
7. AWS refuses GitHub's login. CloudTrail shows repo:you@6875450/inventory-agent-aws@1453653749:ref:refs/heads/main, but the role's rule only allows repo:you/inventory-agent-aws:*. What is wrong?
The two strings differ at the @ IDs. The fix is a second pattern in the rule, repo:you@*/inventory-agent-aws@*:*, which the course template now includes.