Skip to content
Visual explainer 8h to learn 5 steps

AWS capstone: deploy the pipeline with infrastructure as code

Deploy S3, the queue or trigger, Lambda and DynamoDB with IaC from CI, with build and teardown commands for a disposable lab.

By Invicly Tech, , in AWS Cloud Engineering. About 13 minutes to read.

Topic 37 of 38

In short

This milestone turns the design into a stack that any CI run can build and tear down. You describe the bucket, queues, functions, table and roles in infrastructure as code, deploy them from GitHub Actions using short-lived OIDC credentials, and prove the pipeline works by sending sample files through it. Extensions add a scoped API and a written design for running the worker as a container.

Explained simply

In this milestone you build the service for real, but never by clicking in the console. Every resource lives in a template in your repository. One command creates the whole stack, and one command deletes it. That is what makes it a disposable lab: you can tear it down at night and rebuild it in minutes.

The deploy runs from GitHub Actions. Instead of storing AWS access keys as GitHub secrets, the workflow proves who it is with a short-lived token from GitHub. AWS checks that the token came from your repository and branch, then hands back temporary credentials that expire in about an hour. Nothing long-lived can leak.

A deploy is not finished when the stack turns green. You then send sample files through the pipeline and check the results. One good file, the same file again and one broken file show, in a single run, that processing works, duplicates are ignored and failures reach the dead-letter queue.

Two extensions round it off. A small API lets a client ask for an upload link and read a result, and nothing else. A written design shows how the worker would run as a container on ECS Fargate if files ever need more time or memory than Lambda allows.

Press Play on a diagram to walk through it one step at a time.

SequenceA release from merge to verified stack
GitHub Actions
AWS STS
CloudFormation
Smoke test
  1. 1AssumeRoleWithWebIdentity with the OIDC token for main
    GitHub Actions to AWS STS: AssumeRoleWithWebIdentity with the OIDC token for main
  2. 2Temporary credentials for the deploy role, about 1 hour
    AWS STS to GitHub Actions: Temporary credentials for the deploy role, about 1 hour
  3. 3Package code to S3, then create and execute a change set
    GitHub Actions to CloudFormation: Package code to S3, then create and execute a change set
  4. 4Stack status UPDATE_COMPLETE, or rolls back on failure
    CloudFormation to GitHub Actions: Stack status UPDATE_COMPLETE, or rolls back on failure
  5. 5Upload three sample files to the uploads bucket
    GitHub Actions to Smoke test: Upload three sample files to the uploads bucket
  6. 6Three items in DynamoDB, DLQ empty: job passes
    Smoke test to GitHub Actions: Three items in DynamoDB, DLQ empty: job passes
CompareWorker runtime choices
Lambda worker (deployed)
  • Up to 15 minutes per invocation
  • Scales with the event source mapping
  • No VPC needed
  • Pay per request and GB-second
ECS Fargate worker (designed)
  • Long-running jobs and big libraries
  • Scales on queue backlog
  • Needs VPC subnets and a network plan
  • Pay per vCPU and GB per second while tasks run

In depth

Writing the stack

Use one primary tool, CloudFormation or CDK, as in the infrastructure module. The stack contains: the uploads bucket with versioning, encryption, public access block, lifecycle rules and an SQS notification for the incoming/ prefix; the files-work queue with a redrive policy to files-dlq and maxReceiveCount of 5; a queue policy that allows the S3 service to send from that bucket only; the worker function, a published version and a live alias; an event source mapping on the alias with ReportBatchItemFailures; the results table on demand with PITR and TTL; log groups with retention; roles; and a CloudWatch alarm on DLQ depth.

Give the bucket a name that includes the account ID, because bucket names are global. Set the queue visibility timeout to at least six times the function timeout. Tag the stack with project and env so tags propagate to resources that support them.

  • Bucket: versioned, encrypted, private, lifecycle
  • Queue: redrive to DLQ after 5 receives
  • Worker: alias live, partial batch responses
  • Table: on demand, PITR, TTL
  • Alarm: DLQ visible messages above 0

Deploying from CI with OIDC

Create the IAM OIDC identity provider for token.actions.githubusercontent.com once in the sandbox account, outside the app stack. Create a deploy role whose trust policy allows sts:AssumeRoleWithWebIdentity from that provider, with conditions that aud equals sts.amazonaws.com and sub matches your repository on main, or a protected GitHub environment such as lab.

The workflow needs permissions id-token: write and contents: read. It runs aws-actions/configure-aws-credentials with role-to-assume set to the role ARN, then validates and deploys. Run cfn-lint or cdk synth on pull requests with no AWS access at all; only the main-branch job gets the deploy role. After the deploy, the same job runs the smoke test and fails the run if the expected items are missing.

FlowCI stages for the capstone
  1. 1
    Pull request

    Lint, unit tests with the fake model, template validation

  2. 2
    Merge to main

    Job requests an OIDC token

  3. 3
    Assume deploy role

    Trust checks repo and branch

  4. 4
    Deploy stack

    Change set executed; rollback on failure

  5. 5
    Smoke test

    Three sample files, expected results checked

Sample events and what they prove

Keep fixtures in the repository under samples/: invoice-contoso.csv (valid), the same file uploaded again under the same key, and invoice-broken.csv with a missing column. The worker derives file_id from the bucket, key and version ID or ETag, so a duplicate delivery of the same object produces the same file_id.

After upload, expect: one item for the good file with status processed; a log line for the duplicate saying it was skipped by the conditional write; and the broken file's message in files-dlq after five receives, with the DLQ alarm in ALARM. Because waiting for five receives takes time, the smoke test can poll for up to a few minutes, or you can lower maxReceiveCount in the lab stage. Record the outputs as evidence. You can also invoke the worker locally with a saved SQS test event before any cloud deploy.

Adding a scoped API

Add an API Gateway HTTP API with two routes. POST /uploads returns a presigned PUT URL for incoming/ plus a new file_id, valid for a few minutes. GET /results/{file_id} reads one item from the results table. Protect the routes with a JWT authorizer from your identity provider, or IAM authorization for a machine client; for a lab, an authorizer pointing at a test Amazon Cognito user pool works.

The API role holds only s3:PutObject on incoming/* and dynamodb:GetItem on the table. It cannot list the bucket, read other users' files or delete anything. Add a route throttle so a runaway client cannot flood the queue. Test it: a request without a token gets 401, a valid request returns a URL, and a PUT to the URL after it expires gets 403.

Designing the container option

Lambda stops a function after 15 minutes and limits memory and temporary storage. If some files need longer processing or a large native library, design a worker that runs as an ECS service on Fargate. The task polls files-work with long polling, processes, writes the result and deletes the message. Its task role carries the same permissions as the Lambda worker; its execution role only pulls the image from ECR and writes logs.

Scale the service on queue depth with Application Auto Scaling target tracking, using a custom metric such as backlog per task, and allow a minimum of zero tasks out of hours. Running in a VPC brings back the network costs: use public subnets with public IPs (public IPv4 is billed hourly) or private subnets with VPC endpoints, and avoid a NAT gateway if you can. Write this as a design document with a cost line, rather than deploying it, unless you choose to pay.

  • Task role: app permissions; execution role: pull image and write logs
  • Scale on queue backlog, minimum zero
  • Visibility timeout longer than the longest job
  • Network choice decides the fixed cost

Learn it in 5 short steps

About 1h 35m each. Track them with a timer in your plan.

  1. 1
    Write the IaC stack~1h 35m
  2. 2
    Deploy from CI with OIDC~1h 35m
  3. 3
    Send sample events~1h 35m
  4. 4
    Add a scoped API~1h 35m
  5. 5
    Document a container deployment design~1h 35m

Key points

  • One template or CDK app creates every resource, tagged with project and env, so build and teardown are single commands.
  • The CI role trusts GitHub's OIDC provider only for your repository and branch or environment; no long-lived access keys exist.
  • Set the queue visibility timeout to at least six times the worker's function timeout so in-flight messages do not reappear early.
  • A sample event set with a good file, a duplicate and a broken file proves success, idempotency and the dead-letter path in one run.
  • The API only issues presigned upload URLs and reads results by file_id; it never needs permission to delete anything.

Key terms

Tap a card to flip it. 0/5 known

Examples

bash
# build (from repo root, credentials for the sandbox account)
aws cloudformation package --template-file infra/stack.yaml \
  --s3-bucket <artifact-bucket> --output-template-file out.yaml
aws cloudformation deploy --template-file out.yaml --stack-name files-lab \
  --capabilities CAPABILITY_NAMED_IAM --tags project=files-lab env=lab
# teardown: empty the versioned bucket first, then delete the stack
python scripts/empty_bucket.py files-lab-uploads-<account-id>
aws cloudformation delete-stack --stack-name files-lab
aws cloudformation wait stack-delete-complete --stack-name files-lab

Build and teardown commands for the disposable lab. The bucket must be empty, including old versions, before the stack can delete it.

The deploy job in GitHub Actions

Step 1: create the OIDC provider and deploy role once. Step 2: store the role ARN as a repository variable, not a secret, because it is not sensitive. Step 3: the job requests an ID token, assumes the role, packages and deploys. Step 4: the smoke test script uploads the samples and checks DynamoDB. Expected evidence: the run log shows an assumed-role session name, the stack update completes, and the smoke test passes. Rollback: CloudFormation rolls back a failed update by itself; for a bad but successful deploy, revert the commit and let CI redeploy.

yaml
permissions: { id-token: write, contents: read }
jobs:
  deploy:
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    environment: lab
    steps:
      - uses: actions/checkout@v7
      - uses: aws-actions/configure-aws-credentials@v6
        with: { role-to-assume: "${{ vars.DEPLOY_ROLE_ARN }}", aws-region: eu-west-1 }
      - run: aws sts get-caller-identity
      - run: ./scripts/deploy.sh
      - run: ./scripts/smoke_test.sh

The idempotent write in the worker

Step 1: build file_id from the bucket, key and version ID so the same object always gives the same ID. Step 2: write the result with a condition that no item with that ID exists yet. Step 3: if the condition fails, log a duplicate and treat the message as done, so it is deleted from the queue. Step 4: any other error is reported as a batch item failure so SQS retries only that message. Evidence: sending the same message twice leaves one item and one duplicate log line.

python
from botocore.exceptions import ClientError

def save_result(table, file_id: str, result: dict) -> bool:
    try:
        table.put_item(
            Item={"file_id": file_id, **result},
            ConditionExpression="attribute_not_exists(file_id)",
        )
        return True
    except ClientError as e:
        if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
            print({"fileId": file_id, "event": "duplicate_skipped"})
            return False
        raise

Quick reference

  • Build: aws cloudformation package, then aws cloudformation deploy with --capabilities CAPABILITY_NAMED_IAM
  • Teardown: empty the versioned bucket, then aws cloudformation delete-stack
  • OIDC trust: aud = sts.amazonaws.com, sub = repo:ORG/REPO:ref:refs/heads/main
  • Workflow needs permissions id-token: write; no AWS keys in GitHub secrets
  • Visibility timeout at least 6 times the function timeout
  • Event source mapping: FunctionResponseTypes ReportBatchItemFailures
  • Samples: valid file, duplicate, broken file; expect 1 item, 1 skip log, 1 DLQ message

Common mistakes

  • Trusting token.actions.githubusercontent.com without a sub condition, which lets any repository on GitHub assume your deploy role.
  • Leaving a function timeout of 5 minutes with the default 30-second queue visibility timeout, so every message is processed twice.
  • Creating resources by hand during debugging and forgetting them, so the stack deletes cleanly but the bill does not stop.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which trust policy condition stops other GitHub repositories from assuming your deploy role?

Question 2

2The worker timeout is 2 minutes and the queue visibility timeout is 30 seconds. What happens?

Question 3

3Why does the API role get s3:PutObject on incoming/* but no s3:GetObject?

Question 4

4When is the ECS Fargate worker the better choice?

Question 5

5delete-stack fails on the uploads bucket. What is the right fix for a disposable lab?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write the trust policy condition block for a deploy role used only by the main branch of fabrikam/files-lab.

  2. Exercise 2medium

    Write a smoke test that uploads the three sample files and checks the results table has an item for the good file.

  3. Exercise 3hard

    Write a teardown script that empties the versioned bucket, deletes the stack, then lists any resources still tagged project=files-lab.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

CloudFormation or CDK for the capstone?
Either works. CDK writes CloudFormation for you from code and helps with repeated patterns; plain CloudFormation is easier to read in a review. Use the tool you practised in the infrastructure module.
Can I test without deploying to AWS?
Yes for the code. Run the worker with saved test events, use the fake model for any Bedrock call, and mock AWS calls with the moto library or DynamoDB local. The IAM, notification and queue wiring can only be proved in a real account.
Why keep the OIDC provider outside the app stack?
The provider and deploy role must exist before CI can deploy anything, and deleting the app stack in teardown should not lock CI out of the account.

Go deeper

ShareXLinkedInWhatsApp