π° How to Automatically Restrict IAM User Access After AWS Budget Limit is Reached (Beginner's Guide)
π― What Are We Building?
We will:
- Set a spend limit (budget) in AWS.
- Send an alert using Amazon SNS when the limit is reached.
- Trigger an AWS Lambda function that will restrict an IAM user.
- The IAM user will lose AWS access automatically when the budget is exceeded.
β Prerequisites
- Basic AWS Account
- IAM user to test (you can create a new one for this demo)
- IAM permissions to create budgets, Lambda functions, and SNS topics
π§ Step 1: Create an AWS Budget
- Go to the AWS Console β Billing β Budgets.
- Click Create Budget β Cost Budget.
- Set your spend limit (for example,
$10per month for testing). - Add an alert threshold at
100%of the budget. - Create a new SNS Topic when prompted (youβll configure it later).
π οΈ Example:
- Budget:
$100/month - Alert at:
100%
π Step 2: Create an SNS Topic
- Go to Amazon SNS β Topics β Create Topic.
- Choose Standard Topic.
- Set the name (example: BudgetExceedTopic).
- Click Create Topic.
- Subscribe Lambda to SNS
- You will link this SNS topic to a Lambda function in the next step.
π₯οΈ Step 3: Create a Lambda Function
- Go to Lambda β Create Function β Author from scratch.
- Function name: RestrictIAMUserFunction
- Runtime: Python
3.12(or latest)
Paste This Code:
import boto3
import json
iam = boto3.client('iam')
def lambda_handler(event, context):
user_name = 'adeel' # Change this to your IAM username
deny_policy = {
"Version": "2012-10-17",
"Statement": [{
"Effect": "Deny",
"Action": "*",
"Resource": "*"
}]
}
iam.put_user_policy(
UserName=user_name,
PolicyName='DenyAllPolicy',
PolicyDocument=json.dumps(deny_policy)
)
return {"status": f"Permissions restricted for user {user_name}"}
π Step 4: Add IAM Permissions to Lambda
- The Lambda needs permissions to:
- Write logs
- Attach IAM policies Inline Policy to Add:
- π Replace YOUR_ACCOUNT_ID With your AWS Account ID.
- If you want to restrict all users, use:
"Resource": "arn:aws:iam::YOUR_ACCOUNT_ID:user/*"
π Step 5: Connect SNS to Lambda
- Go to your SNS Topic β Subscriptions β Create Subscription.
- Choose Protocol: AWS Lambda.
- Choose the Lambda function you just created.
- Confirm the subscription.
βοΈ Now, when the budget threshold is exceeded, SNS will automatically trigger the Lambda function.
β Step 6: Review and Test
- AWS Budget β Budget β Alerts should now trigger your SNS topic when the budget is crossed.
- SNS will trigger the Lambda function.
- Lambda will restrict the IAM user by attaching a deny-all policy.
βοΈ You can verify this by checking the user in IAM β Inline Policies.
π₯ Key Tips
- AWS Budgets update a few times a day, so the restriction is not instant, but timely.
- Always test on a non-production user first.
- You can enhance this by making the Lambda dynamically read the username from the SNS message.
β¨ Thanks for reading!
If you found this blog helpful, subscribe to my Channel CloudTipsByAD



Top comments (0)