# Cost basics and the course project

Budgets, billing alerts, Cost Explorer, tags and the ways to pay less, read in a real account. Then the project brief that ties the whole AWS course together.

Course: [AWS for DevOps](https://devops.rajeev.pro/courses/aws), lesson 17. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/aws/17-cost-basics

## What you will learn

- Read the billing dashboard and the Free Tier page, and know what each number means
- Set up a zero-spend budget and understand actual versus forecast alerts
- Break your spend down by service in Cost Explorer
- Tag resources so the bill can be split by project, team or environment
- Know when right-sizing, Savings Plans, Spot and Trusted Advisor save money
- Build the course project and tear it down without a surprise bill

## The bill is part of the design

Every lesson in this course ended with a cost line and a clean-up. That habit matters more than any tool
here: most surprise AWS bills come from something left running, like a NAT gateway, a load balancer or a
database nobody deleted. The tools in this lesson don't stop that. They make sure you **find out the same day**,
and then show you **where** the money went.

Before cost tools, teams often waited for the monthly invoice to notice a forgotten resource. By then, the charge
had already accumulated and nobody knew which project owned it. Billing tools give you earlier signals and a way
to group spend. They do not stop a resource from being created or left running. In this lesson, you'll inspect
the bill, set alerts, find the source of a charge, and choose a sensible cost action before committing to a long
term discount.

All of it lives in **Billing and Cost Management**, a global console (no Region). The screenshots and outputs
come from the practice account used for this course. Its account ID is replaced with `111122223333`.

## Billing and the Free Tier

> **Figure.** AWS Billing Dashboard. AWS summary: (1) current month's total forecast USD 3.33, shown as INR 315.95; current month-to-date balance and prior month show No data to display; 14 active services and 17 active Regions. (2) Highest cost: Elastic File System. The left menu lists Bills, Cost Explorer, Free Tier, Cost Categories, Cost Allocation Tags and Budgets and Planning.
>
> (1) This month's forecast: a projection from usage so far, not a bill. (2) The service costing the most this month, the first place to look.

The dashboard answers "am I spending, and on what?" in one screen. The currency switch is only for display:
AWS bills in US dollars, so learn to read the USD figure. **Bills** has the itemised invoice for each month.

The **Free Tier** page tracks every free offer you're using and how close each one is to its limit:

> **Figure.** Free Tier page. Summary: (1) Month-to-date usage, 21 service offers in use. (2) Service offerings at or above usage limits, 0 of 21. The Free Tier offers in use table lists AWS Key Management Service, 20000 requests always free per month, 845 used, (3) forecasted 1,541; AWS Glue 513 of 1,000,000 requests; Amazon Simple Queue Service 286 of 1,000,000; CloudWatch 0 of 5 GB-Mo.
>
> (1) Free offers in use this month. (2) How many are at or over their limit: the number to watch. (3) The forecast tells you before you cross a limit, not after.

Two kinds of offer show up here. **Always free** ones (KMS requests, SQS requests, CloudWatch storage) reset
every month and never expire. Others depend on when your account was created and change over time, so
read the current [AWS Free Tier](https://aws.amazon.com/free/) page rather than trusting a blog post. Free
Tier covers usage, not mistakes: a NAT gateway or an idle load balancer was never free.

## Budgets and alerts

A **budget** compares what you spend with a limit you set, and emails you (or posts to SNS, or runs an action)
when a threshold is crossed. **Billing → Budgets:**

> **Figure.** Budgets overview with one budget. (1) academy-5usd. (2) Thresholds OK, health status Healthy, Primary View, budget 5 dollars, amount used 0 dollars. (3) The Create budget button. A blue banner says email recipients added on or after September 30, 2026 must verify their address before receiving budget notifications.
>
> (1) The budget this account runs with. (2) Thresholds OK: nothing has crossed an alert yet. (3) Create budget, used below.

> **Figure.** Budget details for academy-5usd. Budget health: (1) current vs budgeted 0.00%, amount spent 0.00 of 5.00 dollars; (2) forecasted vs budgeted 164.38%, 8.22 of 5.00 dollars, in red. Alerts: thresholds OK, no actions, (3) email verification 0/1 email verified. Details: cost budget, 5 dollars, monthly, starting 2026-10-01.
>
> (1) Actual spend this month: $0.00. (2) The forecast says $8.22, over the limit. (3) The alert email isn't verified yet, so notifications won't reach anyone.

This page has two real lessons in it.

**Actual versus forecast.** Each alert watches either **actual** spend (money already spent) or **forecasted**
spend (where AWS thinks the month will end). Here the forecast is already at 164%, but no email went out,
because both alerts watch actual spend:

```sh
$ aws budgets describe-notifications-for-budget --account-id 111122223333 --budget-name academy-5usd \
    --query 'Notifications[].[NotificationType,ComparisonOperator,Threshold]' --output text
ACTUAL	GREATER_THAN	100.0
ACTUAL	GREATER_THAN	80.0
```

A forecast alert warns you mid-month, while there's still time to act; an actual alert confirms it happened.
Use both on real budgets. Forecasts early in a month are rough, since they extrapolate from a few days.

**Verify the email.** Since September 30, 2026, new email recipients must click a verification link before
budget emails reach them. A budget with an unverified address looks healthy and stays silent. After
creating one, open the budget and check **Email verification** says the address is verified.

> **Figure.** The budget academy-5usd has a 5 dollar monthly limit. It has two alerts on actual spend: at 80 percent, 4 dollars, and at 100 percent, 5 dollars; each emails you. A forecasted alert is a different type: it warns when AWS predicts the month will exceed the limit, before money is spent. Actual alerts stay quiet while actual spend is zero, even if the forecast is high. A budget never stops resources; you still delete them or use a budget action.
>
> academy-5usd emails at $4 and $5 of actual spend. A forecasted alert would warn earlier.

## A zero-spend budget

For a learning account, the best budget is one that fires on the first cent. **Create budget** starts with a
choice between a template and full customisation:

> **Figure.** Create budget, Choose budget type. Budget setup: (1) Use a template (simplified) selected, Customize (advanced) the alternative. Templates: (2) Zero spend budget selected, which notifies you once your spending exceeds 0.01 dollars; also Monthly cost budget, Daily Savings Plans coverage budget and Daily reservation utilization budget.
>
> (1) Use a template. (2) Zero spend budget: notifies you once spending exceeds $0.01.

> **Figure.** The Zero spend budget template form. (1) Budget name My Zero-Spend Budget. (2) Email recipients you@example.com, up to 10. Scope: all AWS services are in scope. (3) Info box: You will be notified via email when any spend above 0.01 dollars is incurred. Template settings can be changed later.
>
> (1) A name. (2) Who gets the email (up to 10 addresses). (3) What it does: one email the moment anything costs money. Create budget is just below this.

This walkthrough stopped here and pressed **Cancel**: the practice account already has its budget. In your
own account, press **Create budget**, then verify the address from the email AWS sends. The **Monthly cost
budget** template is the next step up: a dollar limit with an actual alert and a forecast alert.

From the CLI, the same check works for any budget:

```sh
$ aws budgets describe-budgets --account-id 111122223333 \
    --query 'Budgets[].{Name:BudgetName,Limit:BudgetLimit.Amount,Actual:CalculatedSpend.ActualSpend.Amount,Forecast:CalculatedSpend.ForecastedSpend.Amount}' --output table
-------------------------------------------------
|                DescribeBudgets                |
+--------+------------+--------+----------------+
| Actual | Forecast   | Limit  |     Name       |
+--------+------------+--------+----------------+
|  0.0   |  8.219     |  5.0   |  academy-5usd  |
+--------+------------+--------+----------------+
```

> **Video.** [How to Set Up a Zero-Spend Budget on AWS (Step-by-Step)](https://www.youtube.com/watch?v=QA0zNRiGLfY) (WirfonCloud)

## Cost Explorer

A budget tells you **that** you spent; **Cost Explorer** tells you **on what**. It shows up to 13 months of
history (once it's enabled), grouped by service, Region, account, usage type or tag:

> **Figure.** Cost Explorer, New cost and usage report. Report parameters on the right: date range 2026-04-01 to 2026-09-30, last 6 months; (1) granularity Monthly; (2) group by dimension Service. (3) Cost and usage overview: total cost -0.00 dollars, average monthly cost -0.00 dollars, service count 27. Below, the cost and usage graph.
>
> (1) Monthly granularity; switch to Daily to find the day something started. (2) Grouped by service. (3) Six months of this practice account: $0.00, because every lesson cleaned up after itself.

Twenty-seven services used, and the total still rounds to zero. That's the clean-up habit paying off. The
usual investigation goes: group by **Service** to find the expensive one, then by **Usage type** to see what
in it (hours, GB stored, data out), then by **Region** to find where.

The same data from the CLI. The Cost Explorer API lives in `us-east-1`, and every request costs $0.01, so script it
sparingly:

```sh
$ aws ce get-cost-and-usage --time-period Start=2026-10-01,End=2026-10-18 --granularity MONTHLY \
    --metrics UnblendedCost --group-by Type=DIMENSION,Key=SERVICE \
    --query 'ResultsByTime[0].Groups[].[Keys[0],Metrics.UnblendedCost.Amount]' --output text \
    | sort -t$'\t' -k2 -gr | head -5
EC2 - Other	0.0000155226
Amazon Simple Storage Service	0.0000003192
Tax	0
AmazonCloudWatch	0
Amazon Virtual Private Cloud	0
```

**EC2 - Other** is everything EC2 bills apart from instance hours: EBS volumes and snapshots, NAT gateways,
Elastic IPs. It's the line to check first when compute looks cheap but the bill doesn't. Here it's a
fraction of a cent.

**Cost Anomaly Detection**, in the same menu, learns your normal spend per service and emails you when a day
looks unusual. It catches the slow leaks that never cross a budget threshold.

> **Video.** [How can I use Cost Explorer to analyze my spending and usage?](https://www.youtube.com/watch?v=8oF4yDWA3qA) (Amazon Web Services)

## Tags and cost categories

The bill knows services and Regions; it doesn't know that the RDS database belongs to the payments team.
**Tags** fix that. Put the same keys on everything (`project`, `env`, `owner`), then **activate** them as cost
allocation tags so they become a dimension in Cost Explorer:

> **Figure.** Cost Allocation Tags page. Cost allocation tags (22), with Undo, Deactivate and (2) Activate buttons. The table lists tag keys AmazonDataZoneBlueprint, AmazonDataZoneDomain, AmazonDataZoneEnvironment, AmazonDataZoneProject, AmazonDataZoneScopeName, AmazonECSManaged, aws:cloudformation:logical-id and aws:cloudformation:stack-id, each with (1) status Inactive, type Resource, last used October 2026.
>
> (1) Every tag key AWS has seen, all Inactive: none of them splits the bill yet. (2) Activate turns a key into a cost dimension.

Two rules catch people out. Tags only count from the moment you activate them (and take up to a day to
appear), so activate early. And a tag missing from a resource is a gap in every report, so enforce tags in
Terraform with `default_tags` on the provider instead of hoping people remember.

```sh
$ aws ce list-cost-allocation-tags --status Active --query 'CostAllocationTags[].TagKey'
[]
```

**Cost categories** group spend by your own rules, for example "everything tagged `team=payments` plus account
`prod-payments`" → category **Payments**. They're how finance gets a report by team without reading tags. Build
them after the tags are in place.

> **Video.** [How can I tag my AWS resources to divide up my bill by cost center or project?](https://www.youtube.com/watch?v=HmXkLtSYHtk&t=25s) (Amazon Web Services)

## Paying less

Once you know where the money goes, there are four levers, in the order to try them:

| Lever               | What it does                                                                        | Fits                                |
| ------------------- | ----------------------------------------------------------------------------------- | ----------------------------------- |
| **Delete**          | remove what nobody uses: old snapshots, unattached EBS volumes, idle load balancers | always first, and free              |
| **Right-size**      | move to a smaller or newer instance type that still meets the load                  | servers mostly idle on CPU and RAM  |
| **Savings Plans**   | commit to a dollar amount per hour for 1 or 3 years, pay a lower rate               | steady load that will still be here |
| **Spot** (lesson 3) | spare capacity at a large discount, taken back with a 2-minute warning              | CI runners, batch jobs, test fleets |

**Compute Optimizer** reads CloudWatch metrics from supported resources and suggests a better size. It can review
EC2, Auto Scaling groups, EBS, Lambda and ECS on Fargate. You must opt in before recommendations are available.
This account has not opted in:

```sh
$ aws compute-optimizer get-enrollment-status --region ap-south-1 --query status
"Inactive"
```

**Savings Plans → Recommendations** looks at your past on-demand spend and suggests a commitment:

> **Figure.** Savings Plans Recommendations. Recommendation parameters: (1) Compute Savings Plans selected, applying to EC2, Fargate and Lambda regardless of Region, instance family, size, tenancy and operating system; other types Database, EC2 Instance and SageMaker Savings Plans. (2) Options: term 1-year, payment all upfront, based on the past 30 days. (3) Recommendations (0), last updated Oct 14, 2026; on-demand spend, estimated spend and savings all empty.
>
> (1) Compute Savings Plans cover EC2, Fargate and Lambda in any Region. (2) Term, payment and look-back period. (3) No recommendation: this account has no steady usage to commit to.

Zero recommendations is reasonable for this practice account: AWS only recommends one when average on-demand
spend is above $0.10 an hour. A Savings Plan is a commitment. Buy only against a steady baseline you expect to
keep, never against a short-lived peak.

**Trusted Advisor** runs checks across cost, security, fault tolerance and service limits:

> **Figure.** Trusted Advisor Recommendations. (1) Checks summary: 0 action recommended, 0 investigation recommended, 0 checks with excluded items. (2) Recommended Actions: Upgrade your AWS Support plan to get all Trusted Advisor checks, with an Upgrade button.
>
> (1) Nothing flagged. (2) Most checks, including the cost ones, need a Business or higher Support plan.

On the free Basic plan you get the core security checks and service limits. The cost checks (idle load
balancers, underused instances, unassociated Elastic IPs) come with a paid Support plan, which a company
account usually has. In a personal account, Cost Explorer and the clean-up habit cover the same ground.

> **Things that bill while doing nothing.** NAT gateways, load balancers, RDS instances (even stopped ones restart after 7 days), EBS volumes and snapshots, Elastic IPs not attached to a running instance, and public IPv4 addresses. Stopping an EC2 instance stops compute charges only; its volume keeps billing. When you finish a lab, delete, then check the console.

> **In production.** Every account gets a monthly budget with forecast and actual alerts going to a team list, not one person. Tags are enforced in Terraform and by a tag policy in AWS Organizations, Cost Anomaly Detection watches every service, and someone owns a monthly cost review. Savings Plans cover the steady baseline; Spot runs CI and batch work.

## The course project

So far, each service has been a separate exercise. The project connects them into one environment described in
Terraform. `terraform apply` creates the stack, and `terraform destroy` removes it. Build it in your own GitHub
repository so changes can be reviewed before deployment. It is production-shaped, but that does not make it
production-ready without the reviews, policies and recovery tests your team requires.

**Requirements**

- A VPC across two Availability Zones, with public and private subnets (lesson 4).
- An Application Load Balancer in public subnets. Place at least two instances in private subnets and allow
  inbound traffic only from the load balancer (lesson 5).
- A static site in a private S3 bucket. Serve it through CloudFront Origin Access Control (lessons 6 and 9).
- An RDS database in private subnets. Store its password in Secrets Manager, never in code (lessons 10 and 15).
- Give instances permissions through an IAM role. Do not use access keys (lesson 2).
- Send CloudWatch alarms for unhealthy targets and 5xx errors to an SNS topic (lesson 13).
- Add `project`, `env` and `owner` default tags. Define a monthly AWS Budget with actual and forecast alerts.
- Use GitHub Actions on pull requests to run `terraform fmt -check`, `validate` and `plan`. Authenticate to AWS
  with OIDC (lesson 2).

**Suggested repository layout**

```text
aws-project/
├── .github/workflows/terraform.yml
├── modules/
│   ├── network/      # VPC, subnets, routes, endpoints
│   ├── web/          # launch template, ASG, ALB, security groups
│   ├── data/         # RDS, Secrets Manager secret
│   └── site/         # S3 bucket, CloudFront, OAC
├── main.tf           # wires the modules together
├── budget.tf         # aws_budgets_budget with alerts
├── variables.tf
├── outputs.tf        # ALB DNS name, CloudFront domain
└── README.md         # what it builds, what it costs, how to destroy it
```

**How to check it works**

1. Apply from an empty account and confirm `terraform apply` completes.
2. Request the ALB DNS name several times. Confirm both Availability Zones serve traffic.
3. Open the CloudFront domain. Confirm the S3 URL itself returns `AccessDenied`.
4. Terminate one instance. Confirm Auto Scaling replaces it and the alarm fires, then clears.
5. The next day, filter Cost Explorer by `project`. Confirm the charge is tagged, not unallocated.
6. Run `terraform destroy`. Check the console for leftover load balancers, databases and NAT gateways.

**Stretch goals**

- Remote state in S3 with locking, so a second person can run the same code safely.
- HTTPS on your own domain with Route 53 and an ACM certificate (lessons 8 and 9).
- Run the app on ECS Fargate instead of EC2 (lesson 11), and compare the cost in Cost Explorer.

The load balancer, NAT gateway (if you add one) and database bill by the hour. Build, test and destroy in one
session. Keep the zero-spend budget on while you work.

## Mission: A cost check of your account

Without creating anything, find out how your account is set up for cost: which budgets exist and what they alert on, what this month cost by service, which tags split the bill, and whether right-sizing is turned on. Write down one thing to fix.

- You need: An AWS account and the AWS CLI with read access to Billing
- You'll have: The budget's limit, actual and forecast spend and alert types, the top services this month, the active cost tags and the Compute Optimizer status

```sh
$ export AWS_REGION=us-east-1      # the Budgets and Cost Explorer APIs live here
$ ACC=$(aws sts get-caller-identity --query Account --output text)
$ aws budgets describe-budgets --account-id $ACC \
    --query 'Budgets[].[BudgetName,BudgetLimit.Amount,CalculatedSpend.ActualSpend.Amount,CalculatedSpend.ForecastedSpend.Amount]' --output text
academy-5usd	5.0	0.0	8.219
$ aws budgets describe-notifications-for-budget --account-id $ACC --budget-name academy-5usd \
    --query 'Notifications[].[NotificationType,ComparisonOperator,Threshold]' --output text
ACTUAL	GREATER_THAN	100.0
ACTUAL	GREATER_THAN	80.0
$ aws ce get-cost-and-usage --time-period Start=2026-10-01,End=2026-10-18 --granularity MONTHLY \
    --metrics UnblendedCost --group-by Type=DIMENSION,Key=SERVICE \
    --query 'ResultsByTime[0].Groups[].[Keys[0],Metrics.UnblendedCost.Amount]' --output text \
    | sort -t$'\t' -k2 -gr | head -5
EC2 - Other	0.0000155226
Amazon Simple Storage Service	0.0000003192
Tax	0
AmazonCloudWatch	0
Amazon Virtual Private Cloud	0
$ aws ce list-cost-allocation-tags --status Active --query 'CostAllocationTags[].TagKey'
[]
$ aws compute-optimizer get-enrollment-status --region ap-south-1 --query status
"Inactive"
```

The Cost Explorer call costs $0.01; everything else is free, and nothing is created, so there's nothing to
clean up. In this account the one thing to fix was clear: the budget only alerts on actual spend and its
email isn't verified yet.

## Try it

- Open Billing → Free Tier and find the offer closest to its limit.
- If you have no budget yet, create one from the Zero spend budget template with your own email, then verify the address from the email AWS sends.
- Run `aws budgets describe-budgets` and compare the actual and forecasted spend.
- Open Cost Explorer, group by Service and switch Granularity to Daily. Which day cost the most?
- Open Cost Allocation Tags and find the tag keys AWS has seen in your account. Which ones are active?
- Open Savings Plans → Recommendations. Does your account have enough steady usage for one?

## Quiz

1. You created an AWS account for practice. What is the first cost control to set up?
   - A Savings Plan
   - **A zero-spend budget that emails you as soon as anything costs money** (answer)
   - A Trusted Advisor upgrade
   Why: The zero-spend template alerts once spend goes above $0.01. You hear about a forgotten resource on day one, not at the end of the month.

2. A budget shows actual spend $0.00 but forecasted spend at 164% of the limit, and no email arrived. Why?
   - Budgets never send email
   - **Its alerts only watch actual spend, so a forecast over the limit doesn't trigger them** (answer)
   - The forecast is always wrong
   Why: An alert is either ACTUAL or FORECASTED. academy-5usd has two ACTUAL alerts (80% and 100%), so it stays quiet until real money is spent.

3. Your team wants the monthly bill split by project. What do you do?
   - **Tag every resource with a project key and activate that key as a cost allocation tag** (answer)
   - Create one AWS account per resource
   - Read the bill line by line
   Why: Activated tags become a dimension in Cost Explorer. Tags only count from when they're activated, so do it before you need the report.

4. A web app runs steadily on EC2 and Fargate all year. Which option lowers the price without changing the architecture?
   - Spot Instances
   - A bigger instance type
   - **A Compute Savings Plan** (answer)
   Why: You commit to a dollar amount per hour for 1 or 3 years, and it applies across EC2, Fargate and Lambda in any Region. Spot is for work that can be interrupted.

5. You finished the course project for the day. What keeps it from costing money overnight?
   - Stopping the EC2 instances
   - **Running terraform destroy and checking the console and the budget the next day** (answer)
   - Closing the browser tab
   Why: Load balancers, NAT gateways, databases and EBS volumes keep billing when instances are stopped. Destroy everything, then check.

## Resources

- [Managing your costs with AWS Budgets](https://docs.aws.amazon.com/cost-management/latest/userguide/budgets-managing-costs.html) (AWS Docs)
- [Analyzing your costs with Cost Explorer](https://docs.aws.amazon.com/cost-management/latest/userguide/ce-what-is.html) (AWS Docs)
- [Using cost allocation tags](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html) (AWS Docs)
- [What is AWS Compute Optimizer?](https://docs.aws.amazon.com/compute-optimizer/latest/ug/what-is-compute-optimizer.html) (AWS Docs)
- [What are Savings Plans?](https://docs.aws.amazon.com/savingsplans/latest/userguide/what-is-savings-plans.html) (AWS Docs)
- [Cost optimization pillar (Well-Architected)](https://docs.aws.amazon.com/wellarchitected/latest/cost-optimization-pillar/welcome.html) (AWS Docs)
