DEV Community

Sagar R Ravkhande for AWS Community Builders

Posted on Edited on

Deploy a Flask API on AWS ECS Fargate with DynamoDB and Terraform (End-to-End)

Updated October 2026. The first version of this post ran the app on ECS with EC2 instances, deployed with long-lived AWS access keys, and had a few bugs I only found when I revisited it. This rewrite covers the refactored project: ECS Fargate, keyless GitHub Actions deployments with OIDC, a fixed birthday calculation and a test suite that runs without AWS. At the end there's a section on what was wrong with v1 and why.

In this post we'll build and deploy a small Flask API end to end on AWS:

  • Flask + gunicorn in a hardened container
  • Amazon ECS on Fargate behind an Application Load Balancer
  • Amazon DynamoDB for storage
  • Terraform for all infrastructure, with tests
  • GitHub Actions for CI/CD, authenticating to AWS with OIDC (no stored keys)

GitHub logo sagary2j / python-flask-hello-world

Python Flask hello-world application deployment into AWS ECS

Hello World Flask Application Deployment using AWS ECS and AWS DynamoDB

This is a simple "Hello World" application that exposes two HTTP-based APIs:

  • PUT /hello/<username>: Saves or updates the given user's name and date of birth in the database.
  • GET /hello/<username>: Returns a hello message for the given user, including their birthday message if it's today or in the next N days.

Architecture

Architecture

Requirements

  • Docker(local)
  • Terraform
  • Python 3.8+
  • Flask 2.0+
  • SQLite3(local)
  • AWS account for deployment
  • AWS DynamoDB

Deployment Architecture

  • Cloud Platform: AWS (Amazon Web Services)
  • Github Action: CI/CD Deployment.
  • AWS ECS: To run the application as a containers in EC2.
  • AWS DynamoDB: Amazon DynamoDB is a fully managed proprietary NoSQL database.
  • AWS S3: For storing terraform state file.
  • AWS CloudWatch: For logging and monitoring.

1. Contents

  • ./applocal.py
    • contains a Python Flask application, which is integrated with SQLite3
  • ./app.py
    • contains a Python Flask application, which is integrated with DynamoDB…

What we're building

A "Hello Birthday" API with three endpoints:

Method Path Body Success Errors
PUT /hello/<username> {"dateOfBirth": "YYYY-MM-DD"} 204 No Content 400 invalid input, 503 storage unavailable
GET /hello/<username> none 200 {"message": "..."} 400 invalid username, 404 unknown user
GET /health none 200 {"status": "ok"} none

The rules:

  • username must contain letters only.
  • dateOfBirth must be a valid date before today.
  • People born on 29 February celebrate on 28 February in non-leap years.
$ curl -X PUT localhost:8000/hello/alice \
    -H 'Content-Type: application/json' -d '{"dateOfBirth": "1990-07-05"}'
$ curl localhost:8000/hello/alice
{"message": "Hello, alice! Your birthday is in 5 day(s)"}
# ...and on 5 July:
{"message": "Hello, alice! Happy birthday!"}
Enter fullscreen mode Exit fullscreen mode

Architecture

Architecture: Flask on ECS Fargate with DynamoDB, deployed by GitHub Actions via OIDC

  • The ALB sits in two public subnets. It is the only thing that can reach the tasks; the service security group accepts traffic from the ALB security group only.
  • Fargate tasks run in private subnets with no public IP. They reach DynamoDB through a free gateway VPC endpoint, and reach ECR and CloudWatch Logs through a NAT gateway.
  • Application Auto Scaling keeps average CPU at 60%, between 2 and 5 tasks.
  • GitHub Actions assumes an IAM role via OIDC, pushes an image tagged with the commit SHA, then runs terraform apply.

The diagram itself is code: docs/architecture.py uses the diagrams library, so it is versioned with the infrastructure it describes.

Repository layout

app/                 Flask app: factory, routes, birthday logic, storage backends
tests/               pytest suite (no AWS needed; DynamoDB is mocked with moto)
wsgi.py              WSGI entry point (gunicorn wsgi:app)
gunicorn.conf.py     Production server settings
Dockerfile           Multi-stage, non-root image with a health check
terraform/           Main stack: VPC, ALB, ECS Fargate, DynamoDB, IAM, autoscaling
terraform/tests/     terraform test suite with a mocked AWS provider
terraform/bootstrap/ One-time stack: GitHub OIDC provider, deploy role, ECR repository
.github/workflows/   CI/CD pipeline
Enter fullscreen mode Exit fullscreen mode

1. The application

One app, pluggable storage

v1 had two near-identical files: app.py for DynamoDB and applocal.py for SQLite. Now there's one app built by a factory, and storage sits behind a tiny interface:

class UserRepository(Protocol):
    def save(self, username: str, date_of_birth: date) -> None: ...

    def get(self, username: str) -> date | None: ...
Enter fullscreen mode Exit fullscreen mode

DynamoDBUserRepository and SQLiteUserRepository both implement it, and an environment variable picks one:

STORAGE_BACKEND=sqlite python wsgi.py     # local development, no AWS
STORAGE_BACKEND=dynamodb TABLE_NAME=users # what ECS runs
Enter fullscreen mode Exit fullscreen mode

The factory also accepts the repository and a today function as parameters. That's what makes the tests fast and deterministic (more on that below):

def create_app(
    settings: Settings | None = None,
    repository: UserRepository | None = None,
    today: Callable[[], date] = date.today,
) -> Flask:
Enter fullscreen mode Exit fullscreen mode

Getting the birthday maths right

This is the whole calculation. It works on plain date objects, so there are no time-of-day surprises:

from datetime import date


def _birthday_in(year: int, date_of_birth: date) -> date:
    try:
        return date_of_birth.replace(year=year)
    except ValueError:
        # 29 February in a non-leap year: celebrate on 28 February.
        return date(year, 2, 28)


def days_until_birthday(date_of_birth: date, today: date) -> int:
    next_birthday = _birthday_in(today.year, date_of_birth)
    if next_birthday < today:
        next_birthday = _birthday_in(today.year + 1, date_of_birth)
    return (next_birthday - today).days


def greeting(username: str, date_of_birth: date, today: date) -> str:
    days = days_until_birthday(date_of_birth, today)
    if days == 0:
        return f"Hello, {username}! Happy birthday!"
    return f"Hello, {username}! Your birthday is in {days} day(s)"
Enter fullscreen mode Exit fullscreen mode

Validating input properly

A missing or non-JSON body used to raise a KeyError and return a 500. Now every input is checked before anything touches the database:

@bp.put("/hello/<username>")
def save_user(username: str):
    if not username.isalpha():
        return _error("Username must contain only letters.", 400)

    payload = request.get_json(silent=True)
    raw_date = payload.get("dateOfBirth") if isinstance(payload, dict) else None
    if not isinstance(raw_date, str):
        return _error('Request body must be JSON like {"dateOfBirth": "YYYY-MM-DD"}.', 400)

    try:
        date_of_birth = datetime.strptime(raw_date, "%Y-%m-%d").date()
    except ValueError:
        return _error("Invalid date format. Use YYYY-MM-DD.", 400)

    if date_of_birth >= _today():
        return _error("Date of birth must be in the past.", 400)

    try:
        _repository().save(username, date_of_birth)
    except RepositoryError:
        current_app.logger.exception("Could not save user %s", username)
        return _error("Storage is temporarily unavailable.", 503)
    return "", 204
Enter fullscreen mode Exit fullscreen mode

All errors are JSON, and AWS error details are logged, never returned to the client.

2. Tests that don't need AWS or a lucky date

The old tests called a real DynamoDB table and asserted things like "the birthday is in 1 day" for a hardcoded date, so they only passed on certain days of the year. The new suite injects an in-memory repository and a fixed clock:

TODAY = date(2026, 6, 30)


@pytest.fixture
def client(repository):
    app = create_app(settings=Settings(), repository=repository, today=lambda: TODAY)
    return app.test_client()
Enter fullscreen mode Exit fullscreen mode

The birthday logic gets table-driven tests, including the leap-year edge cases:

@pytest.mark.parametrize(
    ("date_of_birth", "today", "expected"),
    [
        (date(1990, 6, 30), date(2026, 6, 30), 0),
        (date(1990, 7, 1), date(2026, 6, 30), 1),
        # The next birthday falls after 29 Feb 2028, so the gap is 366 days.
        (date(1990, 3, 4), date(2027, 3, 5), 365),
        # Leap-day birthdays are celebrated on 28 Feb in non-leap years.
        (date(2000, 2, 29), date(2027, 2, 28), 0),
        (date(2000, 2, 29), date(2028, 2, 29), 0),
    ],
)
def test_days_until_birthday(date_of_birth, today, expected):
    assert days_until_birthday(date_of_birth, today) == expected
Enter fullscreen mode Exit fullscreen mode

The DynamoDB repository is tested against moto, so the real boto3 calls run with no AWS account. The suite has 44 tests at 100% coverage and runs in under two seconds:

make install
make test
Enter fullscreen mode Exit fullscreen mode

3. A production-grade container

The old image ran python app.py, which meant the Flask development server with debug=True on 0.0.0.0, as root. The Werkzeug debugger allows arbitrary code execution, so that is never safe to expose. The new Dockerfile:

# syntax=docker/dockerfile:1

FROM python:3.13-slim AS build
ENV PIP_NO_CACHE_DIR=1 PIP_DISABLE_PIP_VERSION_CHECK=1
COPY requirements.txt .
RUN pip install --prefix=/install -r requirements.txt

FROM python:3.13-slim
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PORT=8000
RUN useradd --system --uid 10001 --no-create-home app
WORKDIR /srv
COPY --from=build /install /usr/local
COPY app ./app
COPY wsgi.py gunicorn.conf.py ./
USER 10001
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
    CMD ["python", "-c", "import os, urllib.request; urllib.request.urlopen(f'http://127.0.0.1:{os.environ[\"PORT\"]}/health', timeout=2)"]
CMD ["gunicorn", "wsgi:app"]
Enter fullscreen mode Exit fullscreen mode
  • It's a multi-stage build, and dependencies come from pinned requirements.txt.
  • It runs as a non-root user (uid 10001).
  • gunicorn replaces the dev server.
  • A .dockerignore allowlist keeps Terraform, tests and .git out of the image.

4. Infrastructure with Terraform

Pin everything

In v1, terraform init pulled whatever AWS provider was latest. When v6 removed the vpc = true argument on aws_eip, the configuration stopped validating, and every deploy would have failed. Now versions are pinned, lock files are committed, and the S3 backend uses native state locking (Terraform 1.10+):

terraform {
  required_version = ">= 1.10"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }

  backend "s3" {
    bucket       = "<your-state-bucket>"
    key          = "global/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true
  }
}
Enter fullscreen mode Exit fullscreen mode

Fargate service with automatic rollback

The ECS-on-EC2 setup needed a launch configuration (deprecated, and blocked for new AWS accounts), an Auto Scaling group, an ECS-optimised AMI and instance roles. Fargate removes all of that. The service is a single resource:

resource "aws_ecs_service" "app" {
  name                              = var.project_name
  cluster                           = aws_ecs_cluster.main.id
  task_definition                   = aws_ecs_task_definition.app.arn
  desired_count                     = var.min_tasks
  launch_type                       = "FARGATE"
  health_check_grace_period_seconds = 30
  wait_for_steady_state             = true

  deployment_circuit_breaker {
    enable   = true
    rollback = true
  }

  network_configuration {
    subnets          = aws_subnet.private[*].id
    security_groups  = [aws_security_group.service.id]
    assign_public_ip = false
  }

  load_balancer {
    target_group_arn = aws_lb_target_group.app.arn
    container_name   = local.container_name
    container_port   = var.container_port
  }

  lifecycle {
    # Application Auto Scaling owns the running task count.
    ignore_changes = [desired_count]
  }
}
Enter fullscreen mode Exit fullscreen mode
  • wait_for_steady_state makes terraform apply fail if the new tasks never become healthy.
  • The circuit breaker automatically rolls back to the last working task definition.

Least-privilege IAM

The task role can do exactly two things, on exactly one table:

data "aws_iam_policy_document" "task_dynamodb" {
  statement {
    actions   = ["dynamodb:GetItem", "dynamodb:PutItem"]
    resources = [aws_dynamodb_table.user_table.arn]
  }
}
Enter fullscreen mode Exit fullscreen mode

There's also a separate execution role, which ECS uses to pull the image and write logs. The table has point-in-time recovery and deletion protection.

Test the Terraform too

terraform validate only checks syntax. The repo also has a terraform test suite that plans against a mocked AWS provider, so CI can check the logic without credentials:

run "defaults" {
  command = plan

  assert {
    condition     = length(aws_nat_gateway.this) == 1 && length(aws_route.private_nat) == 2
    error_message = "Default should share one NAT gateway across both private subnets."
  }

  assert {
    condition     = jsondecode(aws_ecs_task_definition.app.container_definitions)[0].image == "123456789012.dkr.ecr.us-east-1.amazonaws.com/flask-docker-app:0123abc"
    error_message = "Task definition must deploy the image_tag that CI passes in."
  }
}
Enter fullscreen mode Exit fullscreen mode

Other runs check that setting certificate_arn switches the ALB to HTTPS with an HTTP-to-HTTPS redirect, and that single_nat_gateway = false creates one NAT gateway per AZ.

5. CI/CD with GitHub Actions and OIDC

No more access keys

v1 stored AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY as GitHub secrets. Now a small bootstrap stack, applied once by an admin, creates:

  • the GitHub OIDC identity provider;
  • a deploy role that only a job in the repo's production environment can assume;
  • an ECR repository with immutable tags, scan on push and a lifecycle policy.

The important part is the trust policy:

condition {
  test     = "StringEquals"
  variable = "token.actions.githubusercontent.com:sub"
  values   = ["repo:${var.github_repository}:environment:${var.github_environment}"]
}
Enter fullscreen mode Exit fullscreen mode

The deploy role gets PowerUserAccess, plus IAM permissions limited to roles prefixed with the project name. It can't create arbitrary admin roles.

The pipeline

Every pull request runs three jobs in parallel:

  1. Lint and test: ruff and pytest, with a 90% coverage gate.
  2. Build and smoke-test image: builds the Dockerfile, runs it, does a real PUT/GET round trip, and fails if the container runs as root.
  3. Terraform checks: fmt, validate for both stacks, and terraform test.

Merges to the default branch then run the deploy job:

deploy:
  needs: [test, container, terraform]
  if: >-
    github.ref_name == github.event.repository.default_branch &&
    (github.event_name == 'push' || github.event_name == 'workflow_dispatch')
  environment: production
  permissions:
    contents: read
    id-token: write
  env:
    IMAGE_TAG: ${{ github.sha }}
  steps:
    - uses: actions/checkout@v7

    - uses: aws-actions/configure-aws-credentials@v6
      with:
        role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }}
        aws-region: ${{ env.AWS_REGION }}

    # ...log in to ECR, build and push $IMAGE_TAG...

    - name: Terraform plan
      working-directory: terraform
      run: |
        terraform init -input=false
        terraform plan -input=false -var="image_tag=$IMAGE_TAG" -out=tfplan

    - name: Terraform apply
      working-directory: terraform
      run: terraform apply -input=false tfplan

    - name: Smoke test
      working-directory: terraform
      run: |
        url="$(terraform output -raw alb_url)"
        curl -fsS --retry 12 --retry-delay 10 --retry-all-errors "$url/health"
Enter fullscreen mode Exit fullscreen mode
  • Commit-SHA image tags. v1 always pushed :latest. The task definition never changed, so Terraform saw nothing to do and ECS kept running the old image. A unique tag per commit forces a new task definition and a rolling deployment.
  • plan -out then apply tfplan. What gets applied is exactly what was planned.
  • The production environment is the only thing the deploy role trusts. Restrict it to the default branch and optionally add required reviewers for a manual approval gate.

6. Deploy it yourself

  1. Bootstrap (once, with admin credentials):
   cd terraform/bootstrap
   terraform init
   terraform apply   # -var create_oidc_provider=false if your account already has the GitHub OIDC provider
Enter fullscreen mode Exit fullscreen mode
  1. Configure GitHub:

    • Create an environment named production, restricted to your default branch.
    • Add a repository variable AWS_DEPLOY_ROLE_ARN set to the deploy_role_arn output.
  2. Push to the default branch. The pipeline tests, builds, pushes, applies and smoke-tests. The ALB URL is printed in the job summary.

To serve HTTPS, pass an ACM certificate: -var certificate_arn=arn:aws:acm:.... The ALB then serves TLS 1.2/1.3 and redirects port 80.

7. What was wrong with v1 (and what I learned)

v1 problem Impact Fix
Unpinned Terraform providers AWS provider v6 removed aws_eip.vpc, so the config stopped validating required_providers pins and committed lock files
Always pushing :latest Task definition never changed, so deploys didn't roll out new code Immutable commit-SHA tags
days + 1 and == 365 birthday check Said "in 366 day(s)" on the actual birthday whenever the next birthday came after 29 Feb, and crashed for 29 Feb birthdays Plain date arithmetic with a leap-day rule
Flask debug server as root Remote code execution risk through the Werkzeug debugger gunicorn, non-root user
Tests needed live DynamoDB and specific dates Failed most days of the year, and in CI Injected clock, in-memory repo, moto
Long-lived AWS keys in CI Keys could leak and never expire GitHub OIDC with a scoped role
Two CloudWatch alarms with the same name One silently overwrote the other Target tracking only, which manages its own alarms
Launch configuration and EC2 ASG Deprecated, more to patch and pay for Fargate

The bigger lesson: a pipeline that only runs terraform apply isn't CI/CD. None of these bugs were hard to fix; they survived because nothing tested the code before it shipped. Adding the test, image and Terraform checks on every PR made all of them visible.

Cost and clean-up

For a demo, the biggest line items are usually the NAT gateway and the ALB, not Fargate. The stack defaults to a single NAT gateway (single_nat_gateway = false gives one per AZ for resilience), and DynamoDB traffic goes through the free gateway endpoint instead of NAT.

To tear everything down:

cd terraform
terraform apply   -var image_tag=<tag> -var dynamodb_deletion_protection=false
terraform destroy -var image_tag=<tag>
cd bootstrap && terraform destroy   # empty the ECR repository first
Enter fullscreen mode Exit fullscreen mode

Conclusion

The API is the same small birthday service, but it's now built the way production services should be:

  • the application is testable;
  • the container is locked down;
  • the infrastructure is pinned and tested;
  • the pipeline deploys immutable images without storing a single AWS key.

The full code, including the bootstrap stack, Terraform tests and diagram-as-code, is in the repository. Questions and suggestions are welcome in the comments.

Top comments (0)