Skip to content

Lesson 29 of 30Putting it together

Project: A Serverless Feature Flag API

Deploy a small serverless feature flag API to your own AWS account, stage by stage: a tested Lambda handler, a CDK stack with DynamoDB, Secrets Manager and an HTTP API, least-privilege grants, logs and alarms, a keyless GitHub Actions deploy through OIDC, and a clean teardown.

12 min read0/4 questions

Deploying a Full-Stack App put a FastAPI service on Fargate behind a load balancer, with Postgres in private subnets. That is the right shape for steady traffic. This project builds the other common shape, the one you reach for when traffic is small or spiky: a serverless API with no servers, no VPC to run and almost no cost when nobody calls it.

The app is a feature flag service. Other apps ask it "is new-checkout on?" and get a yes or no. Anyone may read a flag. Only someone holding the admin token may change one. It is small enough to build in an afternoon, and it still needs everything a real service needs: infrastructure as code, a database, a secret, tight permissions, logs, alarms, a pipeline and a way to delete it all.

This is a guided build. You type the files and run the commands on your own machine, against your own AWS account. You need Node.js, uv, the AWS CLI v2 signed in to a dev account (Multiple Accounts, Organizations and SSO shows aws sso login), and a GitHub repo for stage 5. One trimmed copy of the handler runs right here in the page.

The plan

The feature flag API
Client: curl or an appClientcurl or an appHTTP API: API GatewayHTTP APIAPI GatewayFlagsFn: Python 3.13, arm64FlagsFnPython 3.13, arm64Flags table: DynamoDB, on-demandFlags tableDynamoDB, on-demandAdminToken: Secrets ManagerAdminTokenSecrets ManagerLogs and alarms: CloudWatch, SNSLogs and alarmsCloudWatch, SNSGitHub Actions: OIDC, no keysGitHub ActionsOIDC, no keysHTTPSinvokeGet, Put, ScanGetSecretValueJSON logscdk deploy

The HTTP API is the front door. It terminates TLS and routes three paths to one function.

1/5

Why there is no VPC. A Lambda function outside a VPC still reaches DynamoDB and Secrets Manager over HTTPS, and every call is signed and checked by IAM. Put the function in a VPC and it loses that path. You would then need a NAT gateway or interface endpoints, which VPC Networking and Advanced VPC Networking showed are billed by the hour and by the byte. You attach a function to a VPC when it must reach something that only lives there, like RDS. Nothing here does, so the default is the right choice, and it is one you should be able to explain.

Stage 1: the function and its tests

Start with the code, because it decides what the infrastructure must allow. Following Lambda and Serverless, the handler takes an HTTP API event and returns a status, headers and a body. Following DynamoDB Data Modeling, the access patterns come first: get one flag by name, set one flag by name, and list all flags. A partition key of name serves the first two. The list is a Scan, which is fine for a table of dozens of flags and would be the first thing to redesign at scale.

mkdir flagscd flagsgit initmkdir -p lambda/flags tests infra
pyproject.toml
[project]
name = "flags"
version = "0.1.0"
requires-python = ">=3.13"
dependencies = []
 
[dependency-groups]
dev = ["boto3", "moto[dynamodb,secretsmanager]", "pytest"]
 
[tool.pytest.ini_options]
pythonpath = ["lambda/flags"]

The handler creates its clients lazily and keeps them for the life of the execution environment. It caches the token for five minutes, the pattern from KMS, Secrets Manager and Parameter Store, so a warm function does not call Secrets Manager on every request. hmac.compare_digest compares the token in constant time, so response timing reveals nothing about it.

lambda/flags/handler.py
import hmac
import json
import logging
import os
import re
import time
from datetime import datetime, timezone
from functools import cache
 
import boto3
 
logger = logging.getLogger()
logger.setLevel(logging.INFO)
 
NAME = re.compile(r"[a-z0-9-]{1,64}")
TOKEN_TTL_SECONDS = 300
_token: tuple[float, str] | None = None
 
 
@cache
def table():
    return boto3.resource("dynamodb").Table(os.environ["TABLE_NAME"])
 
 
@cache
def secrets():
    return boto3.client("secretsmanager")
 
 
def admin_token() -> str:
    global _token
    now = time.monotonic()
    if _token is None or now - _token[0] > TOKEN_TTL_SECONDS:
        value = secrets().get_secret_value(SecretId=os.environ["TOKEN_SECRET_ARN"])
        _token = (now, value["SecretString"])
    return _token[1]
 
 
def reply(status: int, body: dict) -> dict:
    return {
        "statusCode": status,
        "headers": {"content-type": "application/json"},
        "body": json.dumps(body),
    }
 
 
def list_flags() -> dict:
    items, kwargs = [], {}
    while True:
        page = table().scan(**kwargs)
        items += page["Items"]
        if "LastEvaluatedKey" not in page:
            break
        kwargs["ExclusiveStartKey"] = page["LastEvaluatedKey"]
    flags = [{"name": i["name"], "enabled": i["enabled"]} for i in items]
    flags.sort(key=lambda f: f["name"])
    return reply(200, {"flags": flags})
 
 
def get_flag(name: str) -> dict:
    item = table().get_item(Key={"name": name}).get("Item")
    if item is None:
        return reply(404, {"error": f"no flag called {name}"})
    return reply(200, {"name": name, "enabled": item["enabled"], "updatedAt": item["updatedAt"]})
 
 
def put_flag(name: str, event: dict) -> dict:
    sent = event.get("headers", {}).get("authorization", "")
    if not hmac.compare_digest(sent.encode(), f"Bearer {admin_token()}".encode()):
        logger.warning("rejected write", extra={"flag": name})
        return reply(401, {"error": "missing or wrong token"})
    try:
        enabled = json.loads(event.get("body") or "{}")["enabled"]
    except (ValueError, KeyError):
        enabled = None
    if not isinstance(enabled, bool):
        return reply(400, {"error": 'body must be {"enabled": true} or {"enabled": false}'})
    now = datetime.now(timezone.utc).isoformat(timespec="seconds")
    table().put_item(Item={"name": name, "enabled": enabled, "updatedAt": now})
    logger.info("flag changed", extra={"flag": name, "enabled": enabled})
    return reply(200, {"name": name, "enabled": enabled, "updatedAt": now})
 
 
def handler(event: dict, context: object) -> dict:
    route = event.get("routeKey", "")
    if route == "GET /flags":
        return list_flags()
    name = (event.get("pathParameters") or {}).get("name", "")
    if not NAME.fullmatch(name):
        return reply(400, {"error": "flag names are 1 to 64 of a-z, 0-9 and -"})
    if route == "GET /flags/{name}":
        return get_flag(name)
    if route == "PUT /flags/{name}":
        return put_flag(name, event)
    return reply(404, {"error": f"no route {route}"})

There is no requirements.txt: boto3 ships with the Lambda Python runtime. That is fine for a small project. Teams that need a pinned SDK version bundle their own.

The tests use moto, from The AWS CLI and boto3 for Developers, so they never touch a real account. The fake credentials make sure that anything that escapes the mock fails instead of reaching AWS.

tests/test_handler.py
import json
 
import boto3
import pytest
from moto import mock_aws
 
import handler
 
 
@pytest.fixture
def aws(monkeypatch):
    # fake credentials: if anything escapes the mock, it fails instead of reaching a real account
    monkeypatch.setenv("AWS_ACCESS_KEY_ID", "testing")
    monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "testing")
    monkeypatch.setenv("AWS_DEFAULT_REGION", "eu-west-2")
    with mock_aws():
        boto3.client("dynamodb").create_table(
            TableName="flags",
            KeySchema=[{"AttributeName": "name", "KeyType": "HASH"}],
            AttributeDefinitions=[{"AttributeName": "name", "AttributeType": "S"}],
            BillingMode="PAY_PER_REQUEST",
        )
        arn = boto3.client("secretsmanager").create_secret(
            Name="flags-admin", SecretString="s3cret"
        )["ARN"]
        monkeypatch.setenv("TABLE_NAME", "flags")
        monkeypatch.setenv("TOKEN_SECRET_ARN", arn)
        handler.table.cache_clear()
        handler.secrets.cache_clear()
        handler._token = None
        yield
 
 
def call(route: str, name: str | None = None, body: dict | None = None, token: str | None = None) -> tuple[int, dict]:
    event = {
        "routeKey": route,
        "pathParameters": {"name": name} if name else None,
        "headers": {"authorization": f"Bearer {token}"} if token else {},
        "body": json.dumps(body) if body is not None else None,
    }
    response = handler.handler(event, None)
    return response["statusCode"], json.loads(response["body"])
 
 
def test_write_then_read(aws):
    status, body = call("PUT /flags/{name}", "new-checkout", {"enabled": True}, token="s3cret")
    assert status == 200 and body["enabled"] is True
    assert call("GET /flags/{name}", "new-checkout")[1]["enabled"] is True
    assert call("GET /flags")[1] == {"flags": [{"name": "new-checkout", "enabled": True}]}
 
 
def test_writes_need_the_token(aws):
    assert call("PUT /flags/{name}", "new-checkout", {"enabled": True})[0] == 401
    assert call("PUT /flags/{name}", "new-checkout", {"enabled": True}, token="guess")[0] == 401
    assert call("GET /flags/{name}", "new-checkout")[0] == 404
 
 
def test_rejects_bad_input(aws):
    assert call("PUT /flags/{name}", "new-checkout", {"enabled": "yes"}, token="s3cret")[0] == 400
    assert call("GET /flags/{name}", "Bad Name!")[0] == 400
uv run pytest -q

Check: the last line reads 3 passed. If you want to see the routing logic without installing anything, this trimmed copy swaps DynamoDB and Secrets Manager for a dictionary and a constant:

Pythonhandler_sim.py
import hmacimport jsonimport re # Stand-ins for DynamoDB and Secrets Manager, so the routing logic runs anywhere.TABLE: dict[str, dict] = {}ADMIN_TOKEN = "s3cret"NAME = re.compile(r"[a-z0-9-]{1,64}") def reply(status: int, body: dict) -> dict: return {"statusCode": status, "body": json.dumps(body)} def handler(event: dict) -> dict: route = event.get("routeKey", "") if route == "GET /flags": return reply(200, {"flags": sorted(TABLE)}) name = (event.get("pathParameters") or {}).get("name", "") if not NAME.fullmatch(name): return reply(400, {"error": "flag names are 1 to 64 of a-z, 0-9 and -"}) if route == "GET /flags/{name}": item = TABLE.get(name) return reply(200, item) if item else reply(404, {"error": f"no flag called {name}"}) if route == "PUT /flags/{name}": sent = event.get("headers", {}).get("authorization", "") if not hmac.compare_digest(sent.encode(), f"Bearer {ADMIN_TOKEN}".encode()): return reply(401, {"error": "missing or wrong token"}) enabled = json.loads(event.get("body") or "{}").get("enabled") if not isinstance(enabled, bool): return reply(400, {"error": "enabled must be true or false"}) TABLE[name] = {"name": name, "enabled": enabled} return reply(200, TABLE[name]) return reply(404, {"error": f"no route {route}"}) def call(route, name=None, body=None, token=None): event = { "routeKey": route, "pathParameters": {"name": name} if name else None, "headers": {"authorization": f"Bearer {token}"} if token else {}, "body": json.dumps(body) if body is not None else None, } response = handler(event) print(route.ljust(18), name or "", response["statusCode"], response["body"]) call("PUT /flags/{name}", "new-checkout", {"enabled": True})call("PUT /flags/{name}", "new-checkout", {"enabled": True}, token="s3cret")call("GET /flags/{name}", "new-checkout")call("GET /flags/{name}", "Dark Mode")call("GET /flags")
Output
Press Run (⌘ Enter) to see what happens.

Stage 2: the stack in CDK

Now describe the infrastructure. The course used CDK in TypeScript for the full-stack deploy, and Infrastructure as Code: Choosing a Tool explains when you would pick Terraform instead. Create the CDK app in infra/. --generate-only skips the extra git repo and install that cdk init would otherwise run:

cd infranpx aws-cdk@latest init app --language typescript --generate-onlynpm installrm lib/infra-stack.ts test/infra.test.ts

The stack is the whole design in one file. Read the comments: they carry the decisions.

infra/lib/flags-stack.ts
import { CfnOutput, Duration, RemovalPolicy, Stack, StackProps } from "aws-cdk-lib";
import { Construct } from "constructs";
import * as apigw from "aws-cdk-lib/aws-apigatewayv2";
import { HttpLambdaIntegration } from "aws-cdk-lib/aws-apigatewayv2-integrations";
import * as dynamodb from "aws-cdk-lib/aws-dynamodb";
import * as lambda from "aws-cdk-lib/aws-lambda";
import * as logs from "aws-cdk-lib/aws-logs";
import * as secretsmanager from "aws-cdk-lib/aws-secretsmanager";
 
interface FlagsStackProps extends StackProps {
  alertEmail?: string;
}
 
export class FlagsStack extends Stack {
  constructor(scope: Construct, id: string, props: FlagsStackProps = {}) {
    super(scope, id, props);
 
    // A learning stack: DESTROY so teardown leaves nothing behind. Production data would be RETAIN.
    const table = new dynamodb.TableV2(this, "Flags", {
      partitionKey: { name: "name", type: dynamodb.AttributeType.STRING },
      billing: dynamodb.Billing.onDemand(),
      removalPolicy: RemovalPolicy.DESTROY,
    });
 
    const token = new secretsmanager.Secret(this, "AdminToken", {
      description: "Bearer token for writes to the flags API",
      generateSecretString: { passwordLength: 40, excludePunctuation: true },
      removalPolicy: RemovalPolicy.DESTROY,
    });
 
    const logGroup = new logs.LogGroup(this, "FnLogs", {
      retention: logs.RetentionDays.TWO_WEEKS,
      removalPolicy: RemovalPolicy.DESTROY,
    });
 
    const fn = new lambda.Function(this, "FlagsFn", {
      runtime: lambda.Runtime.PYTHON_3_13,
      architecture: lambda.Architecture.ARM_64,
      handler: "handler.handler",
      code: lambda.Code.fromAsset("../lambda/flags"),
      memorySize: 256,
      timeout: Duration.seconds(5),
      logGroup,
      loggingFormat: lambda.LoggingFormat.JSON,
      environment: {
        TABLE_NAME: table.tableName,
        TOKEN_SECRET_ARN: token.secretArn,
      },
    });
 
    // Least privilege: the three calls the code makes, on this table and this secret only.
    table.grant(fn, "dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:Scan");
    token.grantRead(fn);
 
    const api = new apigw.HttpApi(this, "Api");
    const integration = new HttpLambdaIntegration("FlagsIntegration", fn);
    api.addRoutes({ path: "/flags", methods: [apigw.HttpMethod.GET], integration });
    api.addRoutes({
      path: "/flags/{name}",
      methods: [apigw.HttpMethod.GET, apigw.HttpMethod.PUT],
      integration,
    });
 
    // Stage 4 adds the alarms here.
 
    new CfnOutput(this, "ApiUrl", { value: api.apiEndpoint });
    new CfnOutput(this, "TokenSecretArn", { value: token.secretArn });
    new CfnOutput(this, "FunctionLogGroup", { value: logGroup.logGroupName });
  }
}

Three choices come straight from the course:

  • Grants, not hand-written policies. AWS CDK in Depth showed grantReadWriteData. That would allow about a dozen actions, including DeleteItem and BatchWriteItem. table.grant(fn, ...) with the three actions the code calls is the least-privilege habit from IAM. If a bug or a stolen token runs code in this function, it still cannot delete a flag.
  • The log group exists before the function. Monitoring and Logs warned that groups Lambda creates for you never expire. Creating it in code with a retention period, and passing it in, closes that gap. LoggingFormat.JSON makes every log line a JSON object.
  • RemovalPolicy.DESTROY. AWS CDK in Depth told you to retain stateful resources. This is a learning stack you will delete in stage 6, so here you want the opposite. In production the table would be RETAIN with deletion protection on.
infra/bin/infra.ts
#!/usr/bin/env node
import { App, Tags } from "aws-cdk-lib";
import { FlagsStack } from "../lib/flags-stack";
 
const app = new App();
const env = { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION };
 
new FlagsStack(app, "Flags", { env, alertEmail: app.node.tryGetContext("alertEmail") });
 
Tags.of(app).add("app", "flags");

Test the template before anything exists, with the assertions from AWS CDK in Depth. The second test fails any change that slips a wildcard into a policy:

infra/test/flags.test.ts
import { App } from "aws-cdk-lib";
import { Match, Template } from "aws-cdk-lib/assertions";
import { FlagsStack } from "../lib/flags-stack";
 
const template = Template.fromStack(new FlagsStack(new App(), "Test"));
 
test("the function gets only the DynamoDB calls it makes", () => {
  template.hasResourceProperties("AWS::IAM::Policy", {
    PolicyDocument: {
      Statement: Match.arrayWith([
        Match.objectLike({
          Action: ["dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:Scan"],
          Effect: "Allow",
        }),
      ]),
    },
  });
});
 
test("no policy grants a wildcard action", () => {
  const policies = template.findResources("AWS::IAM::Policy");
  const actions = Object.values(policies).flatMap((p) =>
    p.Properties.PolicyDocument.Statement.flatMap((s: { Action: string | string[] }) => s.Action),
  );
  expect(actions).not.toContain("*");
  expect(actions.filter((a: string) => a.endsWith(":*"))).toEqual([]);
});
npx jestnpx cdk synth

Check: Jest reports 2 passed. cdk synth prints a CloudFormation template without touching your account. Find the AWS::IAM::Policy resource: it lists dynamodb:GetItem, dynamodb:PutItem and dynamodb:Scan on the table's ARN, and secretsmanager:GetSecretValue and secretsmanager:DescribeSecret on the secret. Those five actions are everything this function can do, beyond writing its own logs.

Quick check
A teammate says the function should run in private subnets of a VPC, to be safe. With no other change, what happens to calls to DynamoDB and Secrets Manager?
Need a nudge? A hint rules out a wrong answer.

Stage 3: deploy it and use it

Sign in to your dev account, then bootstrap it once per Region, as AWS CDK in Depth described. Bootstrapping creates the CDKToolkit stack, which CDK uses to upload the function's code.

aws sso login --profile devexport AWS_PROFILE=devaws sts get-caller-identitynpx cdk bootstrapnpx cdk diffnpx cdk deploy Flags -c alertEmail=you@example.com

get-caller-identity is the "who am I, and where am I?" check from The AWS CLI and boto3 for Developers. Do it before every first deploy into an account. cdk deploy lists the IAM changes and asks you to confirm them. That list is a free security review, so read it. When it finishes, it prints the outputs:

Outputs:
Flags.ApiUrl = https://a1b2c3d4e5.execute-api.eu-west-2.amazonaws.com
Flags.FunctionLogGroup = Flags-FnLogs3EE1EAE0-AbCdEf123456
Flags.TokenSecretArn = arn:aws:secretsmanager:eu-west-2:111111111111:secret:AdminToken38B307E8-...

Your IDs and Region will differ. Now use it. The token stays in your shell and never lands in a file:

API=https://a1b2c3d4e5.execute-api.eu-west-2.amazonaws.comTOKEN=$(aws secretsmanager get-secret-value --secret-id <TokenSecretArn> --query SecretString --output text)curl -s -X PUT "$API/flags/new-checkout" -H "content-type: application/json" -d '{"enabled": true}'curl -s -X PUT "$API/flags/new-checkout" -H "authorization: Bearer $TOKEN" -H "content-type: application/json" -d '{"enabled": true}'curl -s "$API/flags"
{"error": "missing or wrong token"}
{"name": "new-checkout", "enabled": true, "updatedAt": "2026-10-23T09:14:02+00:00"}
{"flags": [{"name": "new-checkout", "enabled": true}]}

In PowerShell the first call throws a 401 error instead of printing the body, which is how Invoke-RestMethod reports failures. Check: the first write is refused, the second succeeds, and the list shows the flag. If the first request is noticeably slower than the rest, you have seen a cold start.

Stage 4: logs and alarms

A service you cannot see is not finished. Monitoring and Logs gave you the three signals. The logs are already JSON. Now add alarms that reach you. Add these imports to the top of flags-stack.ts:

infra/lib/flags-stack.ts (add to the imports)
import * as cloudwatch from "aws-cdk-lib/aws-cloudwatch";
import * as actions from "aws-cdk-lib/aws-cloudwatch-actions";
import * as sns from "aws-cdk-lib/aws-sns";
import * as subs from "aws-cdk-lib/aws-sns-subscriptions";

Then replace the // Stage 4 adds the alarms here. comment with:

infra/lib/flags-stack.ts (replace the stage 4 comment)
    const alerts = new sns.Topic(this, "Alerts");
    if (props.alertEmail) alerts.addSubscription(new subs.EmailSubscription(props.alertEmail));
 
    const alarms = [
      fn.metricErrors({ period: Duration.minutes(5) }).createAlarm(this, "FnErrors", {
        threshold: 1,
        evaluationPeriods: 1,
        treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
        alarmDescription: "The flags function threw an error",
      }),
      api.metricServerError({ period: Duration.minutes(5) }).createAlarm(this, "Api5xx", {
        threshold: 5,
        evaluationPeriods: 1,
        treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
        alarmDescription: "The flags API returned 5XX responses",
      }),
      fn.metricThrottles({ period: Duration.minutes(5) }).createAlarm(this, "FnThrottles", {
        threshold: 1,
        evaluationPeriods: 1,
        treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
        alarmDescription: "The flags function was throttled",
      }),
    ];
    for (const alarm of alarms) alarm.addAlarmAction(new actions.SnsAction(alerts));

NOT_BREACHING means "no data is good news". A quiet API sends no error datapoints, and you do not want that to count as a problem. Add a test for the alarms to test/flags.test.ts:

infra/test/flags.test.ts (add at the end)
test("logs expire and every alarm notifies the topic", () => {
  template.hasResourceProperties("AWS::Logs::LogGroup", { RetentionInDays: 14 });
  template.resourceCountIs("AWS::CloudWatch::Alarm", 3);
  template.allResourcesProperties("AWS::CloudWatch::Alarm", {
    AlarmActions: [Match.objectLike({ Ref: Match.stringLikeRegexp("Alerts") })],
  });
});

Run npx jest (3 passed), then npx cdk deploy Flags -c alertEmail=you@example.com. AWS emails you a subscription link; click it, or the alarms have no one to tell. Then prove the path works without breaking anything:

aws cloudwatch describe-alarms --alarm-name-prefix Flags --query "MetricAlarms[].AlarmName" --output textaws cloudwatch set-alarm-state --alarm-name <one of those names> --state-value ALARM --state-reason "Testing the alert path"

Check: an alarm email arrives within a minute or two, and the alarm returns to OK at its next evaluation. Now open CloudWatch Logs Insights, choose the log group from the outputs, and run:

CloudWatch Logs Insights
fields @timestamp, level, message, flag, enabled
| filter message = "flag changed" or message = "rejected write"
| sort @timestamp desc

You should see your rejected write as a WARNING and your successful one as INFO, with flag as its own field. That is why the handler passes extra: a field you can filter on beats a sentence you have to search.

Stage 5: deploy from GitHub with OIDC

So far you deployed from your laptop. CI/CD to AWS with GitHub Actions showed the better way: no stored keys, and a role that trusts one repo and one environment. Define that role in CDK too, in its own stack, because you deploy it once by hand and rarely change it.

infra/lib/github-deploy-stack.ts
import { CfnOutput, Stack, StackProps } from "aws-cdk-lib";
import { Construct } from "constructs";
import * as iam from "aws-cdk-lib/aws-iam";
 
interface GithubDeployStackProps extends StackProps {
  repo: string; // "owner/name"
}
 
export class GithubDeployStack extends Stack {
  constructor(scope: Construct, id: string, props: GithubDeployStackProps) {
    super(scope, id, props);
 
    // One per account. If your account already has this provider, import it with
    // iam.OidcProviderNative.fromOidcProviderArn instead of creating a second one.
    const github = new iam.OidcProviderNative(this, "GitHub", {
      url: "https://token.actions.githubusercontent.com",
      clientIds: ["sts.amazonaws.com"],
    });
 
    const role = new iam.Role(this, "DeployRole", {
      roleName: "flags-deploy-prod",
      assumedBy: new iam.WebIdentityPrincipal(github.oidcProviderArn, {
        StringEquals: {
          "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
          "token.actions.githubusercontent.com:sub": `repo:${props.repo}:environment:prod`,
        },
      }),
    });
 
    // The pipeline may only assume the roles cdk bootstrap created in this account and Region.
    role.addToPolicy(
      new iam.PolicyStatement({
        actions: ["sts:AssumeRole"],
        resources: [`arn:aws:iam::${this.account}:role/cdk-hnb659fds-*-${this.account}-${this.region}`],
      }),
    );
 
    new CfnOutput(this, "DeployRoleArn", { value: role.roleArn });
  }
}

The deploy role does not get permissions on DynamoDB or Lambda. It may only assume the roles cdk bootstrap created, and those do the work. The bootstrap stack's CloudFormation execution role is broad by default. The CDK docs show how to narrow it with --cloudformation-execution-policies when you bootstrap. Update bin/infra.ts so the stack only exists when you pass a repo:

infra/bin/infra.ts
#!/usr/bin/env node
import { App, Tags } from "aws-cdk-lib";
import { FlagsStack } from "../lib/flags-stack";
import { GithubDeployStack } from "../lib/github-deploy-stack";
 
const app = new App();
const env = { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION };
 
new FlagsStack(app, "Flags", { env, alertEmail: app.node.tryGetContext("alertEmail") });
 
const repo = app.node.tryGetContext("githubRepo");
if (repo) new GithubDeployStack(app, "FlagsGithubDeploy", { env, repo });
 
Tags.of(app).add("app", "flags");
npx cdk deploy FlagsGithubDeploy -c githubRepo=<you>/flags

Copy the DeployRoleArn output. In the GitHub repo settings, create an environment called prod and add yourself as a required reviewer. Then add three repository variables: DEPLOY_ROLE_ARN, AWS_REGION and ALERT_EMAIL. These are variables, not secrets, because none of them is sensitive.

.github/workflows/deploy.yml
name: deploy
on:
  push:
    branches: [main]
  pull_request:
 
permissions:
  contents: read
 
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: astral-sh/setup-uv@v10
      - run: uv run pytest -q
      - uses: actions/setup-node@v7
        with:
          node-version: 24
          cache: npm
          cache-dependency-path: infra/package-lock.json
      - run: npm ci
        working-directory: infra
      - run: npx jest
        working-directory: infra
      - run: npx cdk synth --quiet
        working-directory: infra
 
  deploy:
    needs: test
    if: github.event_name == 'push'
    runs-on: ubuntu-latest
    environment: prod
    permissions:
      contents: read
      id-token: write
    steps:
      - uses: actions/checkout@v7
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: ${{ vars.DEPLOY_ROLE_ARN }}
          role-session-name: flags-${{ github.run_id }}
          aws-region: ${{ vars.AWS_REGION }}
      - uses: actions/setup-node@v7
        with:
          node-version: 24
          cache: npm
          cache-dependency-path: infra/package-lock.json
      - run: npm ci
        working-directory: infra
      - name: Deploy
        working-directory: infra
        run: >-
          npx cdk deploy Flags --require-approval never
          -c alertEmail=${{ vars.ALERT_EMAIL }}
          --outputs-file outputs.json
      - name: Smoke test
        working-directory: infra
        run: curl -fsS "$(jq -r .Flags.ApiUrl outputs.json)/flags"

Pull requests run the tests and cdk synth with no AWS credentials at all. A push to main waits for your approval, then the deploy job gets temporary credentials, deploys, and smoke-tests the live URL. Pass the same alertEmail here as on your laptop. A deploy without it removes the email subscription.

Commit, push to main, approve the deploy, and watch the run.

Check: both jobs are green, and the smoke test step prints the flag list from stage 3. In CloudTrail, the AssumeRoleWithWebIdentity event for flags-deploy-prod shows the session name flags- followed by the run ID.

Predict the outputPython

The deploy role trusts only the prod environment. Which jobs get credentials?

TRUSTED_SUB = "repo:you/flags:environment:prod"
jobs = {
  "deploy job, environment: prod": "repo:you/flags:environment:prod",
  "test job on main": "repo:you/flags:ref:refs/heads/main",
  "pull request": "repo:you/flags:pull_request",
}
for job, sub in jobs.items():
  print(job, "->", "credentials" if sub == TRUSTED_SUB else "AccessDenied")
Need a nudge? Hints walk you through it.

Stage 6: tear it down

Finish the way Cost and the Well-Architected Framework taught you to think: anything you are not using is a cost, and anything you cannot delete cleanly is a risk.

npx cdk destroy Flagsnpx cdk destroy FlagsGithubDeploy -c githubRepo=<you>/flagsaws cloudformation list-stacks --stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE --query "StackSummaries[].StackName"aws secretsmanager list-secrets --query "SecretList[].Name"

cdk destroy asks you to confirm each stack. Because the table, log group and secret were marked DESTROY, they go with it.

Check: the stack list shows only CDKToolkit and anything you had before. The secret is gone or marked for deletion. CDKToolkit stays on purpose. Other CDK apps in this account and Region need it, and its asset bucket holds a few small files. Delete it only if nothing else uses CDK here, and empty its bucket first. Finally, if you activated app as a cost allocation tag, look at Cost Explorer in a day or two and confirm that app: flags shows nothing new.

Put it in order6 steps

Put the steps of a first keyless deploy in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/6 matched

Match each requirement to the line in this project that meets it.

Choose an item, then its match on the other side.

Make it yours

The service works. These make it worth showing:

  • Replace the shared token with real users. Add a Cognito user pool and a JWT authorizer on the PUT route, as API Gateway and Load Balancing described, so the function never sees an unauthenticated write.
  • Stop lost updates. Add a version attribute and a condition expression, the pattern from DynamoDB Data Modeling, and return 409 when two admins change a flag at once.
  • Use Powertools. Swap the hand-written logging for Powertools Logger, Metrics and Tracer from Lambda and Serverless, and add an X-Ray trace to the README.
  • Rotate the token. Add a rotation schedule for the secret and confirm the five-minute cache picks up the new value, using KMS, Secrets Manager and Parameter Store.
  • Add a dev environment. Deploy a second copy to a separate account with its own OIDC role trusting environment:dev, as CI/CD to AWS with GitHub Actions recommends.

When you write it up, the Interview Prep lesson Writing Project Case Studies shows how to turn a project like this into a short case study.

Key terms
HTTP API
The lighter, cheaper type of API Gateway, with routes, JWT authorizers and throttling, often used in front of Lambda.
execution environment
The sandbox a Lambda function runs in, reused across warm invocations, which is why module-level caches work.
grant
A CDK method that adds the IAM permissions one resource needs on another, written as policy statements in the template.
removal policy
What CloudFormation does with a resource when it leaves the stack: delete it, or retain it for you to handle.
OIDC deploy role
An IAM role whose trust policy accepts GitHub's signed token for one repo and environment, so CI needs no stored keys.
bootstrap stack
The CDKToolkit stack with the asset bucket and roles that every CDK deploy in an account and Region uses.
teardown
Deleting everything a project created and checking what remains, so nothing keeps costing money or holding data.

You have now shipped and removed a whole service on your own account. The wrap-up next walks a bigger launch through every unit of the track, from an empty account to a monitored release.