AWS Builder Center
From Architecture to Execution: Building ECS Guardian on AWS

From Architecture to Execution: Building ECS Guardian on AWS

Follow the hands-on journey of building ECS Guardian on AWS, from configuring Lambda and SNS to setting up EventBridge scheduling. Learn how to deploy the tool, test its resource-scanning capabilities, and generate reports identifying unused container images, stale task definition revisions, and potentially idle ECS services.

Series: Safe Container Lifecycle Management on AWS with ECS Guardian (3 articles)

  1. 3
    From Architecture to Execution: Building ECS Guardian on AWS This article

📘 Introduction

In Part 1, I introduced ECS Guardian, a serverless tool designed to uncover container waste across Amazon ECR and Amazon ECS, identify potentially idle services using CloudWatch metrics, and deliver cost-saving opportunities through SNS email reports.
Now, it’s time to turn that design into a working solution.
In Part 2, we’ll build ECS Guardian step by step in the AWS console, from configuring notifications and creating demo resources to deploying the Lambda function and testing its cleanup workflow. We’ll also configure a weekly EventBridge schedule to run reports automatically, while keeping actual cleanup under human control.
By the end of this walkthrough, you’ll have:
  • An SNS topic with a confirmed email subscription.
  • A demo ECR repository, six ECS task definition revisions, and a running Fargate service.
  • A  container-guardian  Lambda function with its IAM execution role and permissions.
  • Verified report-mode and cleanup-mode executions.
  • A weekly EventBridge schedule that invokes report mode.
  • A cleanup process to remove the demo resources when you’re finished.
All scripts and IAM policy files used in this walkthrough are available in the project's GitHub repository, linked at the end of the article.
Let’s build ECS Guardian from the ground up and see how it identifies potential container waste in a real AWS environment.



📋 Prerequisites

Account and access
  • An AWS account with permissions to create IAM roles and policies, and to use ECR, ECS, Lambda, SNS, EventBridge Scheduler, and CloudWatch
  • Region set to  ap-south-1  (Mumbai) or any region of your choice throughout
  • A default VPC with public subnets, for the demo Fargate service
Tools
  • AWS Management Console access
  • AWS CloudShell, which provides the AWS CLI and Docker for building and pushing the demo images
  • An email inbox you can access, to confirm the SNS subscription and receive reports
Knowledge
  • Basic familiarity with containers, ECR repositories, and ECS task definitions and services
  • Basic understanding of IAM roles and inline policies
  • Ability to read Python (boto3) at a beginner level
Cost awareness
  • The demo runs one small Fargate task (0.25 vCPU, 0.5 GB), so keep the lab running only as long as needed and complete the teardown in Step VIII.



🔄 Execution Workflow Overview

Before diving into the AWS console, let’s look at how ECS Guardian works from trigger to report.
The workflow begins with Amazon EventBridge Scheduler, which invokes the  container-guardian  Lambda function weekly in report mode. The function examines three areas of your container environment: Amazon ECR images to identify unused images, ECS task definition revisions to find older revisions eligible for deregistration, and ECS service CPU utilization to identify potentially idle services.
The findings are then consolidated into a report and delivered through Amazon SNS to your subscribed email address. If cleanup is needed, you can manually invoke the function in cleanup mode to delete eligible images and deregister eligible task definition revisions. Idle ECS services are reported only and are never automatically modified.
This workflow separates resource discovery, reporting, and cleanup, keeping routine checks automated while leaving destructive actions under human control.
With the overall flow in mind, let’s move on to the AWS setup and configure each component step by step.




🛠️ Execution Workflow

Step I: Configure SNS Notifications

  • Navigate to Amazon SNS → Topics → Create topic.
  • Configure the following:- Type:  Standard 
  • Name:  ecs-guardian-reports 
  • Click Create topic.
  • Copy the Topic ARN. You will need it in Step III and Step IV.
  • Open the topic and click Create subscription.Protocol:  Email Endpoint: Your email address
  • Click Create subscription.
  • Open the confirmation email from AWS and click Confirm subscription.

  • Verify that the subscription status shows Confirmed.


Step II: Provision Demo Resources

Create the Task Execution Role
  • Navigate to IAM → Roles → Create role.
  • Trusted entity type:  AWS service 
  • Use case:  Elastic Container Service → Elastic Container Service Task 
  • Attach policy:  AmazonECSTaskExecutionRolePolicy 
  • Role name:  ecsTaskExecutionRole 
  • Click Create role.

  • Update the trust policy, using  ecs-task-trust-policy.json  from the GitHub repository as a reference.

Create the ECR repository
  • Navigate to Amazon ECR → Private registry → Repositories → Create repository.
  • Repository name:  guardian-demo-app 
  • Leave the other settings as default and click Create.

Push container images
  • Open AWS CloudShell. Make sure the region is  ap-south-1 .
  • Use the script provided in the GitHub repository below. It builds four versioned images (v1 to v4) and pushes them to your ECR repository:  push-demo-images.sh 

  • In ECR → guardian-demo-app, verify that 4 images exist with tags  v1 ,  v2 ,  v3 ,  v4 .

Register task definition revisions
  • Navigate to ECS → Task definitions → guardian-demo-task and verify revisions 1 to 6 exist.

Note: revisions 1 to 4 use images  v1  to  v4  respectively, while revisions 5 and 6 both use  v2 .
Create the ECS cluster and service
  • Navigate to Amazon ECS → Clusters → Create cluster.
  • Enter the cluster name:  guardian-demo-cluster .
  • Select the infrastructure option:  AWS Fargate (serverless) .
  • Click Create.

  • Open the cluster, go to Services, and click Create.
  • Configure the service:- - Compute options: Launch type →  FARGATE 
  • Family:  guardian-demo-task 
  • Revision:  6 
  • Service name:  guardian-demo-svc 
  • Desired tasks:  1 
  • Networking: Default VPC, public subnets, and Public IP turned on
  • Security group: Default security group is fine; no inbound traffic is needed.
  • Click Create.
  • Verify that the service shows 1/1 tasks Running.

Note: the service runs the  v2  image, which is intentionally not the newest. This demonstrates that the Guardian never deletes an image that is still in use.

Step III: Create the Lambda IAM Role

Create the role
  • Navigate to IAM → Roles → Create role.
  • Trusted entity type:  AWS service 
  • Use case:  Lambda 
  • Attach policy:  AWSLambdaBasicExecutionRole 
  • Role name:  ContainerGuardianRole 
  • Click Create role.

Attach the inline policy
  • Open  ContainerGuardianRole  → Add permissions → Create inline policy.
  • Switch to the JSON editor and paste the policy from the GitHub repository:
  • Replace the SNS ARN with the Topic ARN from Step I.
  • Policy name:  ContainerGuardianPolicy 
  • Click Create policy.
  • Verify  ContainerGuardianPolicy  appears under the role's Inline policies.


Step IV: Create the Lambda Function

  • Navigate to AWS Lambda → Functions → Create function.
  • Select Author from scratch and configure:
  • Function name:  container-guardian 
  • Runtime:  Python 3.12 
  • Execution role: Use an existing role →  ContainerGuardianRole 
  • Click Create function.

  • In the Code tab, open  lambda_function.py , delete the sample code, and paste the Guardian code from the GitHub repository:   container_guardian.py  . It scans ECR, ECS and CloudWatch, then publishes the report to SNS.
  • Click Deploy.

Configure the function
  • Go to Configuration → General configuration → Edit and set:
  • Timeout:  5 min 0 sec 
  • Memory:  256 MB 
  • Go to Configuration → Environment variables → Edit and add the variables below. These are test values, so the demo items get flagged right away.

  • Go to Configuration → Environment variables → Edit and add the following (these are test values, so the demo items get flagged right away):
  • TOPIC_ARN: Your SNS Topic ARN from Step I
  • IMAGE_AGE_DAYS: 0
  • KEEP_LATEST_IMAGES: 1
  • KEEP_TASKDEF_REVISIONS: 2
  • IDLE_CPU_PERCENT: 5
  • IDLE_DAYS: 1
  • Click Save.

Note: the Fargate price variables ( VCPU_HOUR ,  GB_HOUR ) default to US East rates. For accurate numbers, check the AWS Fargate pricing page for  ap-south-1  and add those two variables.

Step V: Run Report Mode (Dry Run)

  • Wait about 10 minutes after the ECS service started, so CloudWatch has CPU data for it.
  • Open the Test tab in Lambda and create a test event:
  • Event name:  report 
  • Event JSON:  {"mode": "report"} 
  • Click Test.
  • Verify the result shows:
  •  "unused_images": 2 
  •  "stale_taskdefs": 4 
  •  "idle_services": 1 

  • Open your email and read the report.

Expected results
  • Images  v1  and  v3  flagged: neither is running, and neither is referenced by a retained task definition.
  • Image  v2  not flagged: it is used by the running service and by retained revisions 5 and 6.
  • Image  v4  not flagged: it is protected as the newest image ( KEEP_LATEST_IMAGES=1 ).
  • Task definition revisions 1 to 4 flagged: they fall outside the two newest revisions and are not in use.
  •  guardian-demo-svc  flagged as idle: the Nginx container receives no traffic and uses almost no CPU.

Step VI: Run Cleanup Mode

  • Review the dry-run report and confirm you are happy with what it lists.
  • In the Lambda Test tab, create a second test event:
  • Event name:  cleanup 
  • Event JSON:  {"mode": "cleanup"} 
  • Click Test.

  • Verify the email now says DELETED instead of FOUND.

  • Navigate to ECR → guardian-demo-app and verify only  v2  and  v4  remain.

  • Navigate to ECS → Task definitions → guardian-demo-task and verify revisions 1 to 4 show Inactive, while 5 and 6 are still Active.

  • Open ECS → guardian-demo-svc and verify the service is still running normally.

Note: cleanup mode recalculates everything at the moment you run it. It deletes what is unused right now, not what an older report listed.

Step VII: Schedule Weekly Reports

  • In Lambda → Configuration → Environment variables, switch to production values:
  •  IDLE_DAYS :  7 
  •  IMAGE_AGE_DAYS :  30 
  •  KEEP_LATEST_IMAGES :  10 
  •  KEEP_TASKDEF_REVISIONS :  5 
  • Click Save.

  • Navigate to Amazon EventBridge → Scheduler → Schedules → Create schedule.
  • Configure the following:
  • Schedule name:  ecs-guardian-weekly 
  • Occurrence:  Recurring schedule 
  • Schedule type:  Cron-based schedule 
  • Cron expression:  0 9 ? * MON *  (every Monday, 9:00 AM)
  • Time zone:  Asia/Kolkata 
  • Flexible time window:  Off 
  • Click Next. For the target, select Templated targets → AWS Lambda:
  • Function:  container-guardian 
  • Payload:  {"mode": "report"} 
  • Let EventBridge create a new execution role for the schedule.
  • Click Create schedule.
  • Verify the schedule status shows Enabled.





Step VIII: Clean Up Resources

Delete the following resources in this order:
  • Delete the EventBridge schedule ecs-guardian-weekly.

  • Delete the Lambda function container-guardian.

  • Delete the CloudWatch log group /aws/lambda/container-guardian.

  • Delete the ECS service guardian-demo-svc (select Force delete if asked), then verify the task has stopped.

  • Delete the ECS cluster guardian-demo-cluster.

  • Delete the ECR repository guardian-demo-app (this also deletes its remaining images).

  • Delete the SNS topic ecs-guardian-reports and its subscription.

  • Delete the IAM role ContainerGuardianRole

  • Delete the auto-created EventBridge Scheduler execution role (named like Amazon_EventBridge_Scheduler_LAMBDA_...).

  • Delete ecsTaskExecutionRole




💻 Source Code & Repository

For the complete ECS Guardian project, including the Python Lambda function, IAM policies, shell scripts, architecture documentation, deployment and cleanup guides, security practices, and execution outcomes, please refer to the accompanying GitHub repository.
🔗 GitHub Repository:  ecs-guardian 



📌 Conclusion

Container platforms accumulate waste quietly. Every deployment leaves behind an image and a task definition revision, and forgotten services keep running around the clock. ECS Guardian addresses this with a single serverless Lambda function that scans Amazon ECR, Amazon ECS, and Amazon CloudWatch, identifies what is unused, and emails a cost-savings report through Amazon SNS every week.
The key design principle is to be conservative and keep a human in the loop. The Guardian reports by default, protects anything in use or recently created, exempts tagged resources, and never touches idle services automatically. Deletion happens only when someone reviews the findings and explicitly triggers cleanup mode.
The result is a low-cost, low-risk way to keep a container platform tidy and reduce storage and compute spend, with no servers to manage.



🔑 Key Takeaways

  • Waste builds up silently. Old images, stale task definition revisions, and idle services all add to your AWS bill.
  • One Lambda function covers it all. It scans ECR, ECS, and CloudWatch, then reports through SNS on a weekly EventBridge schedule.
  • Safety comes first. Dry run by default, keep-latest-N rules, usage checks, and the guardian:ignore=true tag prevent accidental deletion.
  • Humans make the final call. Cleanup is manual, and idle services are only ever reported.



➡️ Up Next: Beyond the Build

ECS Guardian is built and running, but building a tool is only the beginning. In part 3, Beyond the Build: Securing, Tuning, and Extending ECS Guardian, we’ll go deeper into the security decisions, threshold tuning, current limitations, and opportunities to extend the Guardian further.
The focus shifts from making it work to making it safer, more adaptable, and ready for real-world environments.

Series: Safe Container Lifecycle Management on AWS with ECS Guardian (3 articles)

  1. 3
    From Architecture to Execution: Building ECS Guardian on AWS This article
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article