Cloud and deployment · Beginner · 18 min
Set an AWS budget and cost alerts before you build anything
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · AWS CLI 2.42.4
You will have a monthly AWS cost budget that emails you at 50, 80 and 100 percent of actual spend and at 100 percent of forecast, a zero-spend budget that catches the first cent, a Cost Anomaly Detection monitor, and a budget action ready to deny new launches, all created from JSON files with the AWS CLI.
On this page
The first AWS bill that surprises you is rarely large because of one big decision. It is a NAT gateway left running over a weekend, a test database nobody stopped, or a load balancer from a tutorial you forgot about. AWS will not warn you about any of these unless you ask it to, and the best time to ask is before you create your first resource.
In this tutorial you set up four safety nets, in this order:
- a monthly cost budget with email alerts at 50%, 80% and 100% of what you have actually spent, plus one at 100% of what AWS forecasts you will spend by the end of the month;
- a zero-spend budget that emails you within hours of the first cent of spend, including usage paid for by Free Tier credits;
- a Cost Anomaly Detection monitor that looks for unusual spend per service and sends you a daily summary;
- a budget action that, after you approve it, attaches a deny policy to the role you build with, so no new instances or databases can be launched.
You write each one as a small JSON file in ~/budget-demo first, check it with jq, and then create it with the AWS CLI, so you can read exactly what you asked for and reuse the files in your next account. Budgets and alerts are free to run; the pricing note in the budget action step covers the one part that can bill.
Step 1 · Install the AWS CLI and confirm the account
Install curl, unzip and jq, then version 2.42.4 of the AWS CLI from Amazon's versioned installer. uname -m prints x86_64 or aarch64, which matches Amazon's file names:
sudo apt update
sudo apt install -y curl unzip jq ca-certificates
AWS_CLI_VERSION=2.42.4
cd "$(mktemp -d)"
curl -fsSLo awscliv2.zip "https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m)-${AWS_CLI_VERSION}.zip"
unzip -q -o awscliv2.zip
sudo ./aws/install
aws --versionIf the CLI is already installed, the installer says so; run sudo ./aws/install --update instead. The CLI gets no updates from apt, so to upgrade later you run the same commands with a newer version number. The zip is a large download, so on a prepaid mobile bundle download it once over Wi-Fi and keep it.
Sign in with your admin profile, not the root user. If you use a named profile, run export AWS_PROFILE=<your-admin-profile> first (replace the placeholder); set up the AWS CLI with SSO and named profiles shows how. Then save your account ID for the rest of the tutorial:
mkdir -p ~/budget-demo
cd ~/budget-demo
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
echo "export ACCOUNT_ID=${ACCOUNT_ID}" > demo.env
echo "Account: ${ACCOUNT_ID}"Check it worked
aws --version starts with aws-cli/2.42.4, and the last line prints Account: followed by your 12-digit account ID. If it is not the account you meant, stop and fix your profile now, before you create anything in the wrong place.
Step 2 · Find out which Free Tier plan you are on
How much protection you need depends on when the account was opened.
- Accounts created after 15 July 2025 choose a Free account plan or a Paid account plan at sign-up. New customers get USD 100 in credits, and can earn up to USD 100 more by completing activities in the console. On the Free plan you are not charged at all: the plan ends after six months or when the credits run out, whichever comes first, and you then have to upgrade to keep using the account. The Free plan also leaves out some services that would use up the credits quickly. On the Paid plan, credits are used first and anything beyond them is billed at normal rates.
- Accounts created before that date stay on the older Free Tier: some services are free for 12 months from sign-up, some are short trials, and some have an always-free monthly allowance. Anything outside those limits is billed.
So a Paid plan account, or an older account, can run up a real bill on your card. A Free plan account cannot, but it can quietly burn through its credits, and once they are gone your experiments stop. Budgets help in both cases.
Ask AWS which plan you are on:
aws freetier get-account-plan-state --region us-east-1AWS describes these offers in US dollars and bills in US dollars by default. If you pay with a dollar card from a local bank, as many readers in Nigeria, Kenya and elsewhere do, your bank's exchange rate and card fees come on top, so set your budget a little below what you can really afford.
Check it worked
The answer contains accountPlanType with FREE or PAID, an accountPlanStatus, and, on the newer plans, accountPlanRemainingCredits and an accountPlanExpirationDate. An account opened before July 2025 may not show a plan at all; in that case check Credits and Free Tier in the Billing and Cost Management console instead. Write down which case you are in.
Step 3 · Write the monthly budget and its four alerts
A cost budget has two parts: the budget itself (name, amount, period) and up to five notifications, each with up to 10 email subscribers. Choose a monthly amount you would be comfortable losing; the examples use USD 20. Replace the email address with your own:
cd ~/budget-demo
cat >> demo.env <<'EOF'
export BUDGET_USD=20
export ALERT_EMAIL=you@example.com
EOF
. ./demo.envALERT_EMAIL is a placeholder: edit demo.env and put in the address you read every day before you go on, then run . ./demo.env again.
Now the budget. TimeUnit MONTHLY with no TimePeriod makes AWS start it on the first day of the current month and repeat it every month, so it never expires:
cat > monthly-budget.json <<EOF
{
"BudgetName": "monthly-cost-cap",
"BudgetType": "COST",
"TimeUnit": "MONTHLY",
"BudgetLimit": { "Amount": "${BUDGET_USD}", "Unit": "USD" }
}
EOFThen the four alerts. ACTUAL alerts fire on money already spent. The FORECASTED one fires when AWS predicts that you will pass 100% by the end of the month, which can give you days of warning, but AWS needs about five weeks of usage history before it can forecast, so in a new account the three actual alerts are the ones that matter at first:
alert() {
printf '{"Notification":{"NotificationType":"%s","ComparisonOperator":"GREATER_THAN","Threshold":%s,"ThresholdType":"PERCENTAGE"},"Subscribers":[{"SubscriptionType":"EMAIL","Address":"%s"}]}' "$1" "$2" "$ALERT_EMAIL"
}
printf '[%s,%s,%s,%s]' \
"$(alert ACTUAL 50)" "$(alert ACTUAL 80)" "$(alert ACTUAL 100)" "$(alert FORECASTED 100)" \
| jq . > monthly-alerts.json
jq -r '.[] | "\(.Notification.NotificationType) \(.Notification.Threshold)% -> \(.Subscribers[0].Address)"' monthly-alerts.jsonA small shell function writes one alert, so the four alerts cannot drift apart in their details. Piping the result through jq . both pretty-prints it and fails loudly if the JSON is broken.
Check it worked
The last command prints four lines: ACTUAL 50%, ACTUAL 80%, ACTUAL 100% and FORECASTED 100%, each followed by -> and your email address. jq . monthly-budget.json shows your amount as a string, for example "Amount": "20". AWS expects a string there, not a number.
Step 4 · Create the budget and read it back
Budgets belong to the account, not to a Region, so it does not matter which Region your profile uses. Create the budget with its alerts in one call. It prints nothing when it succeeds:
aws budgets create-budget \
--account-id "$ACCOUNT_ID" \
--budget file://monthly-budget.json \
--notifications-with-subscribers file://monthly-alerts.jsonRunning it a second time fails with a DuplicateRecordException, because budget names are unique in an account. To change a budget later, use aws budgets update-budget or edit it in the console.
Read it back, to see what AWS stored rather than what you meant to send:
aws budgets describe-budget --account-id "$ACCOUNT_ID" --budget-name monthly-cost-cap \
--query 'Budget.[BudgetName,BudgetLimit.Amount,TimeUnit,CalculatedSpend.ActualSpend.Amount]' --output text
aws budgets describe-notifications-for-budget --account-id "$ACCOUNT_ID" --budget-name monthly-cost-cap \
--query 'Notifications[].[NotificationType,Threshold]' --output textTwo things to know about what you just built. First, budget figures refresh up to three times a day, and charges can run past a threshold before the email arrives, so treat the 50% alert as your real warning and the 100% one as "already too late". Second, each actual alert is sent once per month, the first time spend crosses it. If you ignore it, AWS does not remind you.
Check it worked
The first command prints one line like monthly-cost-cap 20.0 MONTHLY 0.0 (your amount, and the spend so far this month). On a budget made a moment ago the last column can read None until AWS first refreshes the spend; that is normal. The second prints four lines: ACTUAL with 50, 80 and 100, and FORECASTED with 100. In the console, Billing and Cost Management then Budgets now lists monthly-cost-cap.
Step 5 · Add a zero-spend budget for a learning account
The monthly budget counts costs after credits, which is what you will pay. On an account that runs on Free Tier credits, that figure stays at zero while the credits drain, so the monthly budget never fires. A zero-spend budget closes that gap: it leaves credits out ("IncludeCredit": false), so it sees the full value of everything you use, and its single alert fires once that passes one cent. The console's Zero spend budget template does something similar; writing it yourself lets you see each setting:
cat > zero-spend-budget.json <<'EOF'
{
"BudgetName": "zero-spend",
"BudgetType": "COST",
"TimeUnit": "MONTHLY",
"BudgetLimit": { "Amount": "1", "Unit": "USD" },
"CostTypes": {
"IncludeTax": true,
"IncludeSubscription": true,
"UseBlended": false,
"IncludeRefund": true,
"IncludeCredit": false,
"IncludeUpfront": true,
"IncludeRecurring": true,
"IncludeOtherSubscription": true,
"IncludeSupport": true,
"IncludeDiscount": true,
"UseAmortized": false
}
}
EOF
printf '[{"Notification":{"NotificationType":"ACTUAL","ComparisonOperator":"GREATER_THAN","Threshold":0.01,"ThresholdType":"ABSOLUTE_VALUE"},"Subscribers":[{"SubscriptionType":"EMAIL","Address":"%s"}]}]' "$ALERT_EMAIL" \
| jq . > zero-spend-alert.json
aws budgets create-budget \
--account-id "$ACCOUNT_ID" \
--budget file://zero-spend-budget.json \
--notifications-with-subscribers file://zero-spend-alert.jsonABSOLUTE_VALUE means the threshold is in dollars, not a percentage of the limit, so the one-dollar limit only exists because a budget needs one. Once you are past learning and spend money on purpose, this budget fires every month on day one; delete it then (the last step shows how) and rely on the monthly one.
Check it worked
aws budgets describe-budgets --account-id "$ACCOUNT_ID" --query 'Budgets[].BudgetName' --output text prints both monthly-cost-cap and zero-spend. aws budgets describe-budget --account-id "$ACCOUNT_ID" --budget-name zero-spend --query 'Budget.CostTypes.IncludeCredit' prints false.
Step 6 · Turn on Cost Anomaly Detection
A budget only knows one number: the total. If your usual spend is USD 3 a month and one service jumps to USD 12, that is a fourfold rise, but the monthly budget stays quiet until the total reaches its thresholds. Cost Anomaly Detection compares each service with its own history and flags spend that looks unusual. It is part of the Billing and Cost Management console and adds nothing to your bill. It runs about three times a day, it can lag usage by up to 24 hours, and it needs about 10 days of history for a service before it can judge it, so it complements the budgets rather than replacing them.
Many accounts already have a monitor that AWS set up. List yours first:
aws ce get-anomaly-monitors --query 'AnomalyMonitors[].[MonitorName,MonitorType,MonitorDimension,MonitorArn]' --output textIf a line with DIMENSIONAL and SERVICE comes back, keep that monitor, save its ARN with the command below (replace the placeholder with the ARN from the list), and skip the next two commands.
export MONITOR_ARN=replace-with-arn-from-the-list
echo "export MONITOR_ARN=${MONITOR_ARN}" >> demo.envThat line in demo.env keeps MONITOR_ARN set when you open a new shell. If the list is empty, write a monitor that watches every AWS service separately:
cat > anomaly-monitor.json <<'EOF'
{
"MonitorName": "all-services",
"MonitorType": "DIMENSIONAL",
"MonitorDimension": "SERVICE"
}
EOFMONITOR_ARN=$(aws ce create-anomaly-monitor --anomaly-monitor file://anomaly-monitor.json --query MonitorArn --output text)
echo "export MONITOR_ARN=${MONITOR_ARN}" >> demo.envA monitor detects; a subscription tells you. This one emails a daily summary of anomalies whose total impact is USD 5 or more. Pick a lower figure if USD 5 is a lot for you:
. ./demo.env
jq -n --arg email "$ALERT_EMAIL" --arg monitor "${MONITOR_ARN:-arn:aws:ce::${ACCOUNT_ID}:anomalymonitor/replace-me}" '{
SubscriptionName: "daily-anomaly-summary",
MonitorArnList: [$monitor],
Subscribers: [{Type: "EMAIL", Address: $email}],
Frequency: "DAILY",
ThresholdExpression: {
Dimensions: {
Key: "ANOMALY_TOTAL_IMPACT_ABSOLUTE",
MatchOptions: ["GREATER_THAN_OR_EQUAL"],
Values: ["5"]
}
}
}' > anomaly-subscription.json
jq -r '.MonitorArnList[0], .Frequency' anomaly-subscription.jsonaws ce create-anomaly-subscription --anomaly-subscription file://anomaly-subscription.jsonDAILY and WEEKLY send email. If you want an alert the moment an anomaly is found, use IMMEDIATE, which needs an Amazon SNS topic as the subscriber instead of an email address; create CloudWatch alarms that email you walks through making a topic. Older examples use a plain Threshold number; that field is deprecated in favour of ThresholdExpression.
Check it worked
The jq line prints your monitor ARN (starting arn:aws:ce:: and your account ID, then anomalymonitor/) and DAILY. If it prints replace-me at the end, MONITOR_ARN was not set: go back and set it before you run create-anomaly-subscription. After that call, Cost Anomaly Detection in the console shows the monitor on the Cost monitors tab and daily-anomaly-summary on the Alert subscriptions tab.
Step 7 · Make the budget deny new launches when it is breached
Everything so far alerts. None of it stops spending: a budget at 300% still lets you launch another instance, and resources keep running while you sleep through the email. A budget action is the nearest thing AWS has to a brake. When a threshold is crossed it can attach an IAM policy, apply a service control policy in an organisation, or stop chosen EC2 or RDS instances.
Here it attaches a deny policy to the IAM role you build with, at 100% of actual spend, and only after you approve it. Be clear on its limits before you rely on it:
- it blocks new launches; instances, databases and NAT gateways that already exist keep running and billing until you remove them;
- it acts on billing data that is hours old, so spend can pass the threshold before it triggers;
- do not point it at the role you would need to undo it. Your admin role should stay untouched.
Budget monitoring is free, but budget actions are not always: on the AWS Budgets pricing page (read 26 November 2026), the first two action-enabled budgets in an account are free and each one after that costs USD 0.10 a day. This tutorial creates one.
Set the role the policy will be attached to. Replace the value with the name of an IAM role your scripts or CI use to create resources:
export TARGET_ROLE=replace-with-your-builder-roleWrite the deny policy. It names the launch calls behind the usual surprise bills:
cat > deny-new-launches.json <<'EOF'
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "BudgetBreachedNoNewSpend",
"Effect": "Deny",
"Action": [
"ec2:RunInstances",
"ec2:StartInstances",
"ec2:CreateNatGateway",
"rds:CreateDBInstance",
"rds:StartDBInstance",
"elasticloadbalancing:CreateLoadBalancer"
],
"Resource": "*"
}
]
}
EOF
DENY_POLICY_ARN=$(aws iam create-policy --policy-name budget-deny-new-launches \
--policy-document file://deny-new-launches.json --query Policy.Arn --output text)
echo "export DENY_POLICY_ARN=${DENY_POLICY_ARN}" >> demo.envAWS Budgets needs its own role to attach that policy. The trust policy lets only the Budgets service assume it, and only for budgets in your account. The permissions policy lets it attach and detach that one policy on that one role, nothing else:
aws iam get-role --role-name "$TARGET_ROLE" --query Role.Arn --output text
cat > budgets-trust.json <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "budgets.amazonaws.com" },
"Action": "sts:AssumeRole",
"Condition": {
"ArnLike": { "aws:SourceArn": "arn:aws:budgets::${ACCOUNT_ID}:budget/*" },
"StringEquals": { "aws:SourceAccount": "${ACCOUNT_ID}" }
}
}
]
}
EOF
cat > budgets-permissions.json <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["iam:AttachRolePolicy", "iam:DetachRolePolicy"],
"Resource": "arn:aws:iam::${ACCOUNT_ID}:role/${TARGET_ROLE}",
"Condition": { "ArnEquals": { "iam:PolicyARN": "${DENY_POLICY_ARN}" } }
}
]
}
EOF
ACTION_ROLE_ARN=$(aws iam create-role --role-name budgets-action-runner \
--assume-role-policy-document file://budgets-trust.json --query Role.Arn --output text)
aws iam put-role-policy --role-name budgets-action-runner \
--policy-name attach-deny-policy --policy-document file://budgets-permissions.json
echo "export ACTION_ROLE_ARN=${ACTION_ROLE_ARN}" >> demo.env
echo "export TARGET_ROLE=${TARGET_ROLE}" >> demo.envThe first line is a guard: if get-role fails with NoSuchEntity, TARGET_ROLE does not name a real role, so fix it before going on. Now attach the action to the monthly budget. MANUAL means AWS emails you and waits for you to approve it in the console; switch to AUTOMATIC only once you trust the setup:
aws budgets create-budget-action \
--account-id "$ACCOUNT_ID" \
--budget-name monthly-cost-cap \
--notification-type ACTUAL \
--action-type APPLY_IAM_POLICY \
--action-threshold ActionThresholdValue=100,ActionThresholdType=PERCENTAGE \
--definition "{\"IamActionDefinition\":{\"PolicyArn\":\"${DENY_POLICY_ARN}\",\"Roles\":[\"${TARGET_ROLE}\"]}}" \
--execution-role-arn "$ACTION_ROLE_ARN" \
--approval-model MANUAL \
--subscribers SubscriptionType=EMAIL,Address="$ALERT_EMAIL"Check it worked
aws iam get-policy --policy-arn "$DENY_POLICY_ARN" --query Policy.PolicyName --output text prints budget-deny-new-launches, and aws iam get-role-policy --role-name budgets-action-runner --policy-name attach-deny-policy --query PolicyName --output text prints attach-deny-policy. create-budget-action prints your account ID, monthly-cost-cap and an ActionId. In the console, open Budgets and then monthly-cost-cap: the budget's details list the action, with a status such as STANDBY while it waits for the threshold.
Step 8 · Know how to undo it and remove it
Keep the budgets and the anomaly monitor for as long as the account exists; they cost nothing. Two moments call for this step: when the action has fired and you want to build again, and when you close the account or want to start over.
If the action has run, the deny policy is attached to your builder role. Raise the budget or wait for the next month, then reverse the action so AWS detaches the policy:
ACTION_ID=$(aws budgets describe-budget-actions-for-budget --account-id "$ACCOUNT_ID" \
--budget-name monthly-cost-cap --query 'Actions[0].ActionId' --output text)
aws budgets execute-budget-action --account-id "$ACCOUNT_ID" --budget-name monthly-cost-cap \
--action-id "$ACTION_ID" --execution-type REVERSE_BUDGET_ACTIONTo remove everything this tutorial created, delete the action and the anomaly subscription first. The first line looks up the action ID again, so this works whether or not the action ever ran:
ACTION_ID=$(aws budgets describe-budget-actions-for-budget --account-id "$ACCOUNT_ID" \
--budget-name monthly-cost-cap --query 'Actions[0].ActionId' --output text)
aws budgets delete-budget-action --account-id "$ACCOUNT_ID" --budget-name monthly-cost-cap --action-id "$ACTION_ID"
SUB_ARN=$(aws ce get-anomaly-subscriptions --query 'AnomalySubscriptions[?SubscriptionName==`daily-anomaly-summary`].SubscriptionArn' --output text)
aws ce delete-anomaly-subscription --subscription-arn "$SUB_ARN"Only if you created all-services in this tutorial, delete that monitor too. The command looks it up by name, so it never touches a monitor AWS set up for you; if you reused an existing monitor, it finds nothing and deletes nothing:
OWN_MONITOR_ARN=$(aws ce get-anomaly-monitors --query 'AnomalyMonitors[?MonitorName==`all-services`].MonitorArn' --output text)
if [ -n "$OWN_MONITOR_ARN" ] && [ "$OWN_MONITOR_ARN" != "None" ]; then
aws ce delete-anomaly-monitor --monitor-arn "$OWN_MONITOR_ARN"
fiThe next commands permanently delete both budgets, the budgets-action-runner role and its policy, the deny policy and your working folder, including the JSON files. Copy the files somewhere safe first if you want to reuse them. The commands do not touch your builder role itself:
cd ~/budget-demo
. ./demo.env
aws budgets delete-budget --account-id "$ACCOUNT_ID" --budget-name zero-spend
aws budgets delete-budget --account-id "$ACCOUNT_ID" --budget-name monthly-cost-cap
aws iam delete-role-policy --role-name budgets-action-runner --policy-name attach-deny-policy
aws iam delete-role --role-name budgets-action-runner
aws iam delete-policy --policy-arn "$DENY_POLICY_ARN"
cd ~
rm -rf ~/budget-demoIf delete-policy fails with DeleteConflict, the policy is still attached to your builder role: reverse the action as shown above, or run aws iam detach-role-policy --role-name "$TARGET_ROLE" --policy-arn "$DENY_POLICY_ARN", then try again.
Check it worked
aws budgets describe-budgets --account-id "$ACCOUNT_ID" --query 'Budgets[].BudgetName' --output text no longer lists monthly-cost-cap or zero-spend, aws iam get-role --role-name budgets-action-runner fails with NoSuchEntity, and ls ~/budget-demo says the folder does not exist.
Next steps
- Lock down the account the budgets protect, if you have not yet: secure the AWS root account and your first admin user.
- When an alert does arrive, track down the cause: find and stop what is costing you on AWS.
- Get emails for broken servers and failing functions as well as spend: create CloudWatch alarms that email you.
- Keep the JSON files from this tutorial in a private repository and create the same budgets in every new account on its first day.
Related tutorials
- Tag cloud resources so you know what costs whatYou will have a four-key tagging scheme applied to every AWS resource through Terraform default_tags, a script that lists resources missing a tag, a tag policy ready for your organisation and cost allocation tags that split the bill by project.
- Store and serve files with Cloudflare R2 from a WorkerYou will build a Worker that uploads, downloads and lists files in an R2 bucket, with a size limit, a content-type allowlist, ETag and range support and a bearer token, test it locally with Wrangler and Vitest, and reach the same bucket through R2's S3-compatible API.
- Store container images in Amazon ECR with scanning and lifecycle policiesYou will have a private Amazon ECR repository with immutable tags and scan on push, an nginx image copied into it with crane, its vulnerability findings read from the CLI, a lifecycle policy that keeps the ten newest tagged images, and pull access granted to a second AWS account.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials