AWS Fundamentals Explained: Cloud Basics for Data Engineers

Why buying servers breaks a growing shop and how AWS fixes it: how one API call works, regions and AZs, shared responsibility, the 12 things to set up in a new account, the topics, pros and cons, a real Charminar Cart platform, and small Python code, with copy-paste boto3 code below.

Animated explainer of AWS fundamentals: first Charminar Cart buys 10 servers months ahead for its October sale, pays for idle capacity and has no second site; then AWS rents capacity in the Mumbai region with three Availability Zones and the chart follows demand; then one API call travels through credentials, signing, the regional endpoint, the IAM check, the service and CloudTrail, with regions, AZs and the shared responsibility model below; a checklist of 12 account set-up steps; why a data engineer needs the basics mapped to the 6-stage framework; 15 topics; a balance of pros and cons; the Charminar Cart data platform standing on the fundamentals; 12 lines of boto3 code; and console, CLI, SDK and IaC compared
1

Before you start

This page explains AWS fundamentals for data engineers in 10 animated steps: first the problem without the cloud, then the fix, how one AWS API call works (with regions, Availability Zones and the shared responsibility model), what to set up when you open an account, why a data engineer needs these basics, the topics, pros and cons, one real architecture, a small piece of code, and the four ways to drive AWS. At the bottom: copy-paste Python code for the first tasks in any AWS account, and the full Python code of a small multi-service bootstrap project.

πŸ›’ The story: Charminar Cart outgrows its server room

Charminar Cart is the online shop from Hyderabad you met on the earlier pages (Asha, Ravi, Meena, Kiran). Its data runs on 2 servers most of the year. In October, the festive-sale month, it needs 10 servers for order processing and the nightly reports. Ravi (finance head) and Meena (data engineer) compare two ways to get that capacity. The same numbers are used in the animation and in these notes:

Own servers (step 1)AWS (step 2)
Servers needed2 a month, 10 in October2 a month, 10 in October
How they get themBuy 10 in July for β‚Ή30 lakh (β‚Ή3 lakh each)Rent them in the Mumbai region when needed
Time until a new server runs3 months (order, delivery, rack and install)Minutes
Server-months paid in a year10 Γ— 12 = 1202 Γ— 11 + 10 = 32
Server-months used32 (so 88 idle = 73 % wasted)32 (0 idle)
Upfront costβ‚Ή30 lakhβ‚Ή0 (pay per second or hour of use)
Places the data lives1 room in the Hyderabad office3 Availability Zones in ap-south-1

Tip: the rupee numbers are a simple classroom example, not a price quote. Real AWS prices depend on the service, the size and the region; use the AWS Pricing Calculator for real numbers.

☁️ AWS in one paragraph

Cloud computing means renting computers, storage, databases and ready-made services over the internet, paying only for what you use, instead of buying and running your own hardware. Amazon Web Services (AWS) is the largest cloud provider. It runs data centres grouped into Availability Zones, and Availability Zones grouped into Regions around the world (two in India: Mumbai ap-south-1 and Hyderabad ap-south-2). You open an AWS account, give people and programs permissions with IAM, and use the services through the web console, the AWS CLI, an SDK such as boto3 for Python, or infrastructure-as-code templates. Every one of those paths ends in the same thing: a signed HTTPS request to an AWS API.

πŸ“– Words used on this page

WordMeaning in one line
On-premises (on-prem)Servers you buy and run yourself, in your own office or data centre.
RegionA geographic area with its own set of AWS data centres, e.g. ap-south-1 (Mumbai).
Availability Zone (AZ)One or more data centres inside a region, with separate power and network; a region has at least three.
ElasticityCapacity grows and shrinks with the load, and so does the bill.
Root userThe e-mail address that created the account; it can do everything, so it is locked away.
IAMIdentity and Access Management: who (users, roles) can do what (policies) on which resources.
ARNAmazon Resource Name: the unique name of a resource, e.g. arn:aws:s3:::charminar-cart-dev-raw.
TagA key=value label on a resource, e.g. project=charminar-cart.
ProfileA named set of credentials and settings saved by the AWS CLI, shared with boto3.
boto3The AWS SDK for Python: Python functions that call AWS APIs.

Step-by-step notes

1

😱 Without the cloud: the problem

In simple words

Before the cloud, a company bought servers for its highest expected load and kept them in its own server room. You had to guess the peak months in advance, pay for everything at once, and wait for the hardware to arrive.

  • Big upfront cost: β‚Ή30 lakh in July, before one sale order.
  • Slow: purchase order, delivery, racking and installation take about 3 months.
  • Idle capacity: 120 server-months paid, 32 used: 73 % wasted.
  • No disaster recovery (DR): one room in one city; a power cut, flood or fire stops everything.
  • You run everything: disks, OS patches, air conditioning, UPS, security guards, spare parts.
  • Hard to experiment: trying a new database means another purchase.

🎬 In the animation: the server room shows 10 servers (2 green = busy, 8 grey = idle); a 4-point timeline goes July β†’ October; the chart shows 2 servers needed each month and 10 in October, a dashed "bought 10" line, and the idle part in red; ⚑ a power cut stops the room; Ravi turns 😑; six problem cards appear.

Real-time scenario

In July Ravi signs β‚Ή30 lakh for 10 servers. They are racked in late September. In October they run hot for the sale; from November they sit idle again. In December a power cut in the office stops the nightly sales report for a whole day because there is no second site.

How to say it in an interview

"On-prem you buy for the peak and pay for it all year. Capacity takes months to add, utilisation is low, and you need a second site for disaster recovery, which doubles the cost."

Common mistake

Watch out: "cloud is always cheaper" is not true. A server that runs flat out 24 Γ— 7 for years can be cheaper on-prem. The cloud wins on variable load, speed and not running data centres yourself.

2

πŸ˜€ With AWS: the solution

In simple words

With AWS, Charminar Cart rents servers and services in the Mumbai region (ap-south-1). It starts them when needed and stops them when the sale is over. This is pay-as-you-go and elastic capacity.

  • β‚Ή0 upfront: you pay per second or per hour of use (depends on the service).
  • Minutes, not months: a new server starts from the console, the CLI or Python.
  • 32 server-months paid instead of 120: capacity follows the demand curve.
  • High availability: the region has 3 AZs; run in at least two and one data centre can fail without stopping you.
  • Global: more than 30 regions; Hyderabad (ap-south-2) is a second Indian region for DR.

🎬 In the animation: the region card shows 3 AZ boxes; green dots fly in and extra green servers appear in each AZ for October; the chart's green bars follow the demand exactly ("paid 32, used 32, 0 idle"); the counters show β‚Ή0 upfront, 32 server-months, minutes and 3 AZs; Ravi turns πŸ˜€.

Real-time scenario

On 1 October Meena raises the order-processing group from 2 to 10 servers with one setting. On 1 November she sets it back to 2. The AWS bill for October is higher, every other month is small, and a budget e-mails Ravi when spend crosses 80 % of the plan.

How to say it in an interview

"The cloud turns capital expense into operating expense: no upfront purchase, pay per use, capacity in minutes, and multiple AZs per region for high availability without building a second data centre."

Common mistake

Watch out: elastic only saves money if something scales down. Forgotten test servers, idle notebooks and old snapshots are the most common reason for a surprise bill.

3

βš™οΈ How it works inside: one API call, the global infrastructure, shared responsibility

In simple words: the life of one API call

  1. Your code (boto3, the CLI or the console in your browser) wants to call an API, e.g. DescribeAvailabilityZones.
  2. Credentials: the SDK looks for them in a fixed order: parameters in code, environment variables, the shared credentials and config files (your profile, including SSO), and finally the IAM role of the machine (EC2, Lambda, Glue) it runs on.
  3. Signed request: the request is signed with Signature Version 4 (SigV4), using the secret key and the current time, so AWS knows who sent it and that nobody changed it.
  4. Regional endpoint: it goes over HTTPS to the service's endpoint in your region, e.g. ec2.ap-south-1.amazonaws.com.
  5. IAM check: AWS checks the identity, then the policies. An explicit Deny always wins; otherwise you need an Allow; with neither, the answer is AccessDenied (the default is deny).
  6. The service works in the region's AZs and returns JSON.
  7. Logged and billed: CloudTrail records who called what, when and from where; the billing meter counts usage.

🎬 In the animation: seven tiles appear left to right; a green DescribeAZs pill hops through all of them and a dashed green "response: JSON" arrow returns to your code. Then a red CreateBucket pill stops at the IAM check, which flashes red, and drops into "AccessDenied". Below: the Mumbai region with 3 AZs (each with data centres, own power, own network), edge and global cards, and the shared responsibility model: YOU (in the cloud) and AWS (of the cloud).

Global infrastructure

PieceWhat it isWhy a data engineer cares
RegionA geographic area with at least 3 AZs. Regions are isolated from each other.Most resources (S3 buckets, Glue jobs, queues) live in one region; pick it first. Data does not leave a region unless you copy it.
Availability ZoneOne or more data centres with separate power, cooling and network, connected to the other AZs of the region by fast private links.Managed services like S3 and DynamoDB already spread data over AZs; for your own servers and databases, use Multi-AZ.
Edge locationPoints of presence in many cities for CloudFront (CDN) and Route 53 (DNS).Rarely used in pipelines; serves dashboards and files fast to users.
Global servicesIAM, billing, Organizations, Route 53 are not tied to a region.An IAM role works in every region; IAM ARNs have no region part.

Shared responsibility model

AWS: security OF the cloudYou: security IN the cloud
Data centres, guards, hardware, power, coolingYour data: classification, encryption settings, backups
Global network and the regions / AZsIAM users, roles, policies, MFA, access keys
The virtualisation layer under EC2Operating system patches on your EC2 servers
Software of managed services (S3, Lambda, Glue)Settings: is the bucket public? which network can reach the database?

The line moves with the service: on EC2 you patch the operating system; on Lambda or Glue AWS does it and you only own the code, the data and the permissions.

Real-time scenario

Kiran's Glue job fails with AccessDenied on s3:PutObject. The request reached AWS, was signed correctly and hit the right region, but the Glue role had no Allow for the curated bucket. Meena adds one statement to the role's policy and the next run succeeds. CloudTrail shows both the failed and the successful call.

How to say it in an interview

"Every AWS action is a signed API call to a regional endpoint. IAM evaluates it: explicit deny wins, then an allow is needed, otherwise it is denied by default. AWS secures the infrastructure; I secure my data, identities and configuration."

Common mistake

Watch out: "I cannot see my bucket / job / queue" is very often the wrong region in the console or in AWS_REGION, not a missing resource. Check the region selector first.

4

πŸ“‹ What to set up when you open an AWS account

In simple words

Twelve things, most done once on day 1. The code section below does numbers 4 to 10 from Python.

#Set upHowRule of thumb
1Lock the root userStrong password, MFA, no access keysUse root only for the few tasks that need it (e.g. closing the account, some billing settings).
2People sign in via SSOIAM Identity Center users and groupsOne login per person, short-lived credentials; IAM users with long-term keys only when there is no other way.
3MFA everywhereAuthenticator app or security keyEvery human login. Programs use roles, not passwords.
4Pick the regionAWS_REGION, profile regionClose to users, data residency rules, price, and the services you need must exist there.
5Budget + alertsAWS BudgetsMonthly cost budget; e-mail at 50 % and 80 % actual and 100 % forecast.
6Billing alarmCloudWatch alarm on AWS/Billing EstimatedChargesTurn on billing alerts in Billing preferences first; the metric exists only in us-east-1.
7CLI profiles, no keys in codeaws configure sso or aws configureboto3 reads the same profile. Never paste keys into code or Git.
8Tag standardproject, env, owner, cost-centerActivate them as cost allocation tags in Billing to see cost per project.
9Naming + ARNsproject-env-purpose(-account)Predictable names make ARNs, policies and searches simple. S3 bucket names are global: add the account id.
10CloudTrailA multi-region trail to an S3 bucketThe console keeps 90 days of management events; a trail keeps them as long as you want.
11Separate environmentsAWS Organizations: dev, test, prod accountsAn account is the strongest boundary for cost and security. Service control policies (SCPs) set guardrails.
12Quotas + Free Tier rulesService Quotas consoleEvery service has limits per account and region. Free Tier offers change; read the current page.

🎬 In the animation: twelve cards appear one by one, each with a green βœ“ and its typical value in a blue chip (day 1, Identity Center, ap-south-1, 25 USD dev, us-east-1, 4 tags…).

Real-time scenario

On her first day Meena gets an Identity Center login with MFA (no root password, no keys). She runs aws configure sso, saves the profile charminar-dev, and runs whoami.py from the code section below: it shows the dev account id, region ap-south-1 and identity type assumed-role (Identity Center logins are roles). The dev account already has a 25 USD budget, a billing alarm and a CloudTrail trail.

Free Tier today

In July 2025 AWS changed the Free Tier for new accounts: new customers get credits (AWS announced up to 200 USD) and can choose a free plan for up to 6 months or a paid plan. Older accounts keep the earlier 12-month and always-free offers. These rules change, so read the current Free Tier page before you promise students "it is free", and always create the budget anyway.

Common mistake

Watch out: creating access keys for the root user "just to try the CLI". If they leak (a public GitHub repo is enough), someone controls your whole account. Use an Identity Center user or, at worst, an IAM user with limited permissions.

5

πŸ§‘β€πŸ’» Why a data engineer must learn the AWS basics

In simple words

  • Every job runs as an IAM role: a Glue job, a Lambda function, an EMR cluster, an Airflow (MWAA) task each assume a role. Wrong role = AccessDenied.
  • You are asked about the bill: Glue DPU-hours, Athena data scanned, Redshift nodes and S3 storage are your pipeline's cost. Budgets and tags explain it.
  • The region decides a lot: Indian customer data in an Indian region; S3, Glue and Athena of one pipeline in the same region (cross-region traffic costs money and adds latency).
  • ARNs and tags are everywhere: IAM policies, Step Functions definitions, alarms and event rules all point at ARNs.
  • Automation: the CLI and boto3 start jobs, copy files and check status from scripts and Airflow DAGs.
  • Your side of shared responsibility: a public bucket with customer phone numbers is a data engineer's mistake, not AWS's.
  • Interviews: region vs AZ, IAM user vs role, the shared responsibility model and "how do you control cost" open most AWS data engineering interviews.
6-stage frameworkWhere the basics fit
Stage 1 Β· Programsboto3 is Python: your programs create and control AWS resources.
Stage 2 Β· ServicesIAM, CloudWatch, Budgets, CloudTrail: the base services every pipeline uses.
Stage 3 Β· PlatformsService categories: pick compute (EC2 server-based, Lambda/Glue serverless, Athena query-only).
Stage 6 Β· StoragesPick storage by category: S3 (lake), Redshift (warehouse), RDS/DynamoDB (operational), ElastiCache (cache).

🎬 In the animation: Meena asks why she should learn regions and IAM; seven reason cards appear; on the right the 6-stage panel lights Stages 1, 2, 3 and 6 with one line each.

Real-time scenario

Meena's Athena query works in the console but her Airflow task fails. The console was on ap-south-1; the DAG's connection had no region and used us-east-1, where the Glue table does not exist. One line, region_name="ap-south-1", fixed it.

Common mistake

Watch out: giving a pipeline role AdministratorAccess "to make it work". It works, and one bug or leaked credential can then delete every bucket. Grant the exact actions on the exact ARNs (the bootstrap code below does this).

6

🧩 AWS fundamentals: topics and purposes

In simple words

TopicPurpose in one line
RegionsSeparate geographic areas; you choose where data and services live.
Availability ZonesIsolated data centres in a region; spread across them to survive one failing.
Edge locationsCloudFront and Route 53 points close to users for fast content and DNS.
Shared responsibilityAWS secures the cloud itself; you secure what you put in it and how you configure it.
Root userThe account owner login: MFA, no access keys, used rarely.
IAM users, groups, rolesUsers = long-term identities, groups = bundles of users, roles = temporary identities that services and people assume.
IAM Identity CenterSingle sign-on for people across all accounts, with short-lived credentials (works with aws configure sso).
ARNsarn:partition:service:region:account-id:resource; global services leave region (and S3 buckets also account) empty.
TagsKey=value labels for cost allocation, automation and attribute-based access control.
Billing + Free TierPay-as-you-go bill per service; new accounts get Free Tier credits and offers.
Budgets + alarmsAWS Budgets and CloudWatch billing alarms notify you before the bill becomes a surprise.
CLI, profiles, boto3The CLI saves profiles in ~/.aws/config and ~/.aws/credentials; boto3 reads the same files.
Console, CLI, SDK, IaCFour ways to call the same APIs: click, command, code, template (step 10).
VPC basicsYour private network in a region: CIDR range, subnets (one AZ each), route tables, internet gateway, VPC endpoints.
Service categoriesCompute, storage, database, analytics, integration, security, management: the map in the table below.

The data engineer's AWS service map

CategoryServices you will meetUsed for
ComputeEC2, Lambda, AWS Batch, ECS / FargateRun code: servers, functions, containers
StorageS3, EBS, EFSThe data lake (S3), disks for servers
DatabaseRDS / Aurora, DynamoDB, ElastiCacheSource systems, operational data, caches
AnalyticsGlue (jobs, crawlers, Data Catalog), Athena, EMR, Redshift, Kinesis, QuickSight, Lake FormationProcess, query, stream, govern and visualise data
IntegrationSQS, SNS, EventBridge, Step Functions, MWAA (Airflow), API GatewayMove events and orchestrate pipelines
MigrationDMS, DataSync, Transfer FamilyBring data in from databases, file shares, SFTP
SecurityIAM, Identity Center, KMS, Secrets ManagerIdentities, encryption keys, passwords
ManagementCloudWatch, CloudTrail, CloudFormation, Organizations, Budgets, Cost ExplorerMonitor, audit, automate, control cost
NetworkingVPC, VPC endpoints, Route 53, CloudFrontPrivate networks, DNS, content delivery

🎬 In the animation: fifteen cards light one by one in five colours: blue = global infrastructure, red = identity, orange = naming, gold = cost, pink = tools, purple = network and categories.

Common mistake

Watch out: mixing up IAM users and roles. A Glue job never gets a user with keys; it gets a role. People should get Identity Center access, which is also a role behind the scenes.

7

βš–οΈ Pros and cons

Pros

  • No upfront cost; pay as you go.
  • Capacity in minutes, not months.
  • Elastic: scale up for the sale, back down after.
  • High availability across AZs; DR in a second region.
  • More than 30 regions, two in India.
  • Managed services: no servers to patch for S3, Lambda, Glue, Athena.
  • Security tools built in: IAM, KMS, CloudTrail.

Cons

  • Bill surprises when nobody watches (idle resources, data transfer).
  • A huge catalogue (over 200 services) and a real learning curve.
  • Lock-in: managed services are AWS-specific.
  • Data transfer out to the internet and between regions costs money.
  • Misconfiguration is your responsibility.
  • Quotas and limits per account and region.
  • Region-wide incidents still happen; critical systems need a plan.

🎬 In the animation: seven green pros and seven red cons appear in turn; the beam tilts toward the pros; the verdict says the pros win only with budgets, tags and IAM from day 1.

How to say it in an interview

"For spiky, growing workloads the cloud wins on cost and speed. The trade-offs are cost discipline, lock-in and the configuration responsibility, which I handle with budgets, tags, least-privilege IAM and infrastructure as code."

8

πŸ—οΈ Where it sits in a real project

In simple words

The Charminar Cart data platform: seller CSV files and app orders arrive, a Lambda function writes them to the S3 raw zone, a Glue job cleans them into staged and aggregates them into curated, and Athena answers SQL on curated. The fundamentals are not one box: they are the floor under every box.

  • Account: a dev account (prod is a separate account in the same Organization).
  • Region: everything in ap-south-1, spread over 3 AZs by the managed services.
  • VPC: the default VPC with an S3 gateway endpoint so Glue reaches S3 privately.
  • IAM roles: lambda-ingest may only write raw; glue-etl reads raw and writes staged and curated.
  • Tags on every bucket; a budget, a billing alarm and a CloudTrail trail.

🎬 In the animation: five zones fill left to right, a πŸ“„ seller file travels Seller CSV β†’ Lambda β†’ S3 raw β†’ Glue β†’ S3 curated β†’ Athena, then the gold foundation band appears with eight tiles, followed by the real results of the bootstrap run and "why the basics matter here".

Real-time scenario

The bootstrap code at the bottom of this page creates this whole dev platform in one run (5 buckets, 2 roles, the endpoint, the budget, the alarm and the trail), then smoke-tests it: the ingest role writes 8 orders to raw, the Glue role keeps 6 for curated (1 had no amount, 1 was cancelled).

9

🐍 A small piece of code

In simple words

The first script to run in any new terminal. It answers three questions: which account, which identity and which region and AZs.

  • Lines 2-3: a Session holds the region and the credentials (found by the provider chain); session.client("sts") creates a client for one service.
  • Lines 5-7: get_caller_identity needs no permissions and never fails because of IAM policies: perfect to check who you are.
  • Lines 9-10: describe_availability_zones lists the AZs of the session's region.
  • Lines 11-12: print the region and the AZ names.

🎬 In the animation: the highlight moves over lines 2-3, 5-7, 9-10 and 11-12; "who?" flies to STS and "ARN" comes back, "AZs?" flies to EC2 and "3 AZs" comes back; the terminal prints the four real lines.

πŸ“„ charminar-aws-basics/first_steps.py

import boto3
session = boto3.Session(region_name="ap-south-1")
sts = session.client("sts")

me = sts.get_caller_identity()
print("account:", me["Account"])
print("you are:", me["Arn"])

ec2 = session.client("ec2")
zones = ec2.describe_availability_zones()["AvailabilityZones"]
print("region :", session.region_name)
print("AZs    :", [z["ZoneName"] for z in zones])

Output

account: 123456789012
you are: arn:aws:sts::123456789012:user/moto
region : ap-south-1
AZs    : ['ap-south-1a', 'ap-south-1b', 'ap-south-1c']

On real AWS you see your own 12-digit account id and your ARN, for example arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_DataEngineer_…/meena for an Identity Center login.

Common mistake

Watch out: creating clients at the top of a Lambda file is good (reused between calls); creating a new client inside a loop of 10,000 items is slow. Create a client once and reuse it.

10

🧰 Console vs CLI vs SDK vs IaC

ConsoleAWS CLISDK (boto3)IaC (CloudFormation, CDK, Terraform)
HowClick in a browseraws <service> <command>Python callsA template describes the end state
Best forLearning, looking, debuggingQuick tasks, shell scriptsLogic inside pipelinesWhole environments
RepeatableNoYes, as a scriptYes, it is codeYes, versioned in Git, with drift detection
Data engineer exampleWhy did last night's Glue run fail?aws s3 cp a test fileStart a Glue job and poll it from AirflowSame buckets, roles and jobs in dev, test, prod

🎬 In the animation: four columns appear one by one with HOW, BEST FOR, REPEATABLE? and DATA ENGINEER USES IT TO, plus "pick it for"; the rule of thumb says learn in the console, repeat with the CLI, automate with boto3, build environments with IaC.

How to say it in an interview

"All four call the same APIs with the same IAM permissions. I explore in the console, script small tasks with the CLI, use boto3 inside pipelines, and create infrastructure with IaC so every environment is identical and reviewed in Git."

Common mistake

Watch out: creating production resources by clicking. Nobody can repeat it exactly, and the next environment differs. The bootstrap code below is a Python version of the IaC idea (idempotent: run it again and it only fixes differences); in real teams use CloudFormation, CDK or Terraform.

Comparison tables

Region vs Availability Zone vs edge location

RegionAvailability ZoneEdge location
WhatGeographic areaData centre(s) inside a regionPoint of presence in a city
Exampleap-south-1 (Mumbai)ap-south-1a (zone ID aps1-az1)CloudFront location in Hyderabad
How manyMore than 30 worldwideAt least 3 per regionHundreds
You choose it forLatency, residency, price, servicesHigh availability (Multi-AZ)Fast delivery to users (automatic)

Tip: the AZ name (ap-south-1a) is mapped randomly per account; the zone ID (aps1-az1) is the same physical AZ in every account. Use zone IDs when two accounts must agree.

Root user vs IAM user vs IAM role vs Identity Center user

Root userIAM userIAM roleIdentity Center user
WhoAccount owner e-mailA person or old appA service (Glue, Lambda) or a person for a sessionA person in your company
CredentialsPassword (+ MFA)Password and/or long-term access keysTemporary (STS), expire automaticallyTemporary, through SSO
PermissionsEverything, cannot be limited by IAMPolicies attachedPolicies attached + trust policy (who may assume)Permission sets per account
Use forAlmost nothingOnly when nothing else worksEvery pipeline and serviceEvery human login

On-premises vs cloud

On-premisesAWS
Cost modelCapital expense, upfrontOperating expense, pay per use
CapacityFixed, bought for the peakElastic
Time to new capacityWeeks to monthsMinutes
Disaster recoverySecond site = second buildingAnother AZ or region
Who patches the hardwareYouAWS
Who secures data and accessYouStill you (shared responsibility)

Worth knowing

Mistakes beginners make

  1. Using the root user every day, or creating access keys for it.
  2. Putting access keys in code, notebooks or Git. Use profiles locally and roles on AWS.
  3. Not setting a budget on day 1, then finding a forgotten cluster on the bill.
  4. Looking in the wrong region and thinking a resource is gone.
  5. Giving pipeline roles AdministratorAccess instead of exact actions on exact ARNs.
  6. Making an S3 bucket public "for a quick test".
  7. No tags, so nobody can say which team or pipeline costs what.
  8. Building production by clicking in the console instead of code or templates.

Try it yourself

  1. Who am I, really? Run whoami.py twice: once with AWS_PROFILE unset and once with a profile. Hint: the "credentials" line changes (env, shared-credentials-file, sso…) and the identity ARN changes with it.
  2. Two Indian regions. Change regions.py to also print the opt-in status of ap-south-2 for your account. Hint: a correct result shows either opted-in / opt-in-not-required (you can use it) or not-opted-in (enable it in the console first).
  3. ARN reader. Give arn_tools.parse an SQS ARN, an IAM role ARN and an S3 object ARN. Hint: only the SQS one has a region; the S3 one has neither region nor account.
  4. Tag police. Create a third bucket with only project and env tags and run tag_audit_handler.py. Hint: the report lists that bucket with ['cost-center', 'owner'] missing.
  5. Your own budget. Set MONTHLY_BUDGET_USD to your real limit, run budget_alerts.py in your account and check the Budgets console. Hint: you see one budget with three alerts, and the SNS topic in us-east-1 waits for you to confirm the e-mail.

Interview questions

Q. What is the difference between a region and an Availability Zone?

A region is a geographic area such as Mumbai; it contains at least three Availability Zones. An AZ is one or more data centres with separate power and network, connected to the other AZs by low-latency links. I pick the region for latency, data residency, cost and service availability, and spread workloads over AZs for high availability.

Q. Explain the shared responsibility model.

AWS is responsible for security of the cloud: data centres, hardware, network and the software of managed services. I am responsible for security in the cloud: my data, encryption settings, IAM identities and policies, network rules and, on EC2, the operating system. The more managed the service, the smaller my part, but data and access are always mine.

Q. IAM user or IAM role for a Glue job?

A role. The role has a trust policy that lets glue.amazonaws.com assume it and a permissions policy with exactly the S3, Glue Catalog and logs actions the job needs. Roles give temporary credentials, so there are no long-term keys to leak or rotate.

Q. How does IAM decide whether a request is allowed?

By default everything is denied. AWS evaluates all policies that apply; if any has an explicit Deny, the request is denied. Otherwise it needs at least one Allow. Guardrails like SCPs and permission boundaries can only limit, never grant.

Q. How do you protect a new AWS account?

MFA on the root user and no root access keys, Identity Center logins with MFA for people, least-privilege roles for services, a CloudTrail trail for all regions, a budget and a billing alarm, S3 Block Public Access, and separate accounts for dev and prod under AWS Organizations.

Q. How do you control AWS cost on a data project?

Budgets with alerts per account, a tag standard activated as cost allocation tags so Cost Explorer shows cost per pipeline, lifecycle rules on S3, partitioned and columnar data so Athena scans less, right-sized Glue workers, auto-stopping notebooks, and a weekly look at Cost Explorer.

Q. What is an ARN and where do you use it?

An Amazon Resource Name uniquely identifies a resource: arn, partition, service, region, account and resource. I use ARNs in IAM policies to scope permissions, in Step Functions to name Lambda functions and Glue jobs, in event rules and alarms. S3 bucket ARNs have no region or account; IAM ARNs have no region.

Q. How does boto3 find credentials?

Through the default provider chain: explicit parameters, then environment variables, then the shared config and credentials files with the selected profile (including SSO), then the container or EC2 instance role. On Lambda and Glue it uses the execution role automatically, so the code never contains keys.

Q. Console, CLI, SDK or infrastructure as code?

The console to learn and debug, the CLI for quick scripted tasks, boto3 inside pipelines, and IaC such as CloudFormation, CDK or Terraform to create environments. All use the same APIs and IAM permissions; IaC makes dev, test and prod identical and reviewable.

Q. Why use multiple AWS accounts?

An account is the strongest isolation boundary for security, quotas and billing. Separate dev, test and prod accounts mean a mistake in dev cannot delete prod data, costs are clear per environment, and SCPs from AWS Organizations can enforce rules like allowed regions.

Python AWS basics code: copy, change the config, run

Tested against moto (local AWS emulator); not run in a real AWS account. Every file below was extracted from this page into an empty folder and run in order by a script; every Output block is the real output of that run. The AWS CLI commands were run with AWS CLI version 1 against the same emulator.

Emulator limits hit: moto shows its own list of regions (on real AWS the count and the opt-in regions depend on your account), uses the fixed account id 123456789012 and the identity user/moto, does not send budget or alarm e-mails, has no Cost Explorer data (so cost_report.py prints "no cost data"), reports no internet gateway on the default VPC (real default VPCs have one), does not enforce IAM policies (so the "denied" checks are not proven here), and its tagging API lists only the S3 buckets of this lab. Not run at all: aws configure / aws configure sso (need a real account).

πŸ“ The folder

charminar-aws-basics/
  requirements.txt
  config.py               <- the only file you edit
  first_steps.py          the 12 lines of step 9
  whoami.py               session / profile / identity check
  regions.py              regions, opt-in status, AZs
  arn_tools.py            read and build ARNs
  tagging.py              tagged bucket, find by tag, missing-tags report
  budget_alerts.py        monthly budget + CloudWatch billing alarm
  cost_report.py          this month's cost by service and by tag
  vpc_peek.py             default VPC and subnets per AZ
  tag_audit_handler.py    Lambda: daily missing-tags audit
  cleanup.py              delete what the lab created
  policies/lab_runner_policy.json
  policies/data_team_boundary.json

0. One-time setup on your laptop (real AWS)

Install AWS CLI version 2 from the AWS documentation, then save a profile. With IAM Identity Center (recommended) use aws configure sso; with an IAM user's access key use aws configure. The CLI writes ~/.aws/config and ~/.aws/credentials; boto3 reads the same files. Not run here (it needs a real account):

aws configure sso --profile charminar-dev      # Identity Center: asks for the start URL, opens the browser
# or, with an IAM user's access key (never the root user's):
aws configure --profile charminar-dev          # asks for key id, secret, region (ap-south-1), output (json)
export AWS_PROFILE=charminar-dev               # Windows PowerShell: $env:AWS_PROFILE="charminar-dev"
aws sts get-caller-identity                    # must show YOUR account and identity

1. requirements.txt and config.py

boto3 is the AWS SDK for Python; moto is only for testing on a laptop without AWS. config.py is the only file you change: region, project and environment names, a globally unique bucket name, your e-mail, the budget and the required tags. There are no keys in the code: boto3.Session(profile_name=AWS_PROFILE) uses the profile if you set one, otherwise the normal provider chain. client() passes AWS_ENDPOINT_URL, which is set only for the local emulator; on real AWS it is None. Budgets, Cost Explorer and billing metrics are global/billing services and are called in us-east-1.

πŸ“„ charminar-aws-basics/requirements.txt

boto3>=1.34
moto[server]>=5.0      # only for testing on your laptop without AWS

πŸ“„ charminar-aws-basics/config.py

"""config.py - the ONLY file you need to edit. Every other script imports from here.

Credentials are never written in code: boto3 finds them itself (AWS CLI profile, environment
variables, or the IAM role of the EC2 / Lambda / Glue machine the script runs on).
"""
import os

import boto3

# ============================ CONFIG: change these =============================
AWS_REGION = os.getenv("AWS_REGION", "ap-south-1")        # Mumbai (Hyderabad is ap-south-2)
AWS_PROFILE = os.getenv("AWS_PROFILE")                     # e.g. "regularpython"; None = default chain
ENDPOINT_URL = os.getenv("AWS_ENDPOINT_URL")               # only for local testing (moto); unset on real AWS

PROJECT = "charminar-cart"                                 # goes into every name and tag
ENV = os.getenv("APP_ENV", "dev")                          # dev / test / prod
OWNER = "data-team@charminarcart.example"                  # who to call when the bill jumps
DEMO_BUCKET = os.getenv("DEMO_BUCKET", "charminar-cart-dev-basics-change-me")  # globally unique name

MONTHLY_BUDGET_USD = "25"                # AWS Budgets work in USD: about Rs 2,100 a month
ALERT_EMAIL = os.getenv("ALERT_EMAIL", "you@example.com")  # gets the budget and billing e-mails
BILLING_ALARM_USD = 20                   # CloudWatch billing alarm threshold
BILLING_REGION = "us-east-1"             # billing metrics live only in N. Virginia

REQUIRED_TAGS = {                        # every resource must carry these keys
    "project": PROJECT,
    "env": ENV,
    "owner": OWNER,
    "cost-center": "data-engineering",
}
# ==============================================================================

_session = boto3.Session(profile_name=AWS_PROFILE, region_name=AWS_REGION)


def client(service, region=None):
    """one place that builds every boto3 client (endpoint_url is None on real AWS)"""
    return _session.client(service, region_name=region or AWS_REGION, endpoint_url=ENDPOINT_URL)


def session():
    return _session


def tag_list(extra=None):
    """REQUIRED_TAGS as the [{"Key": ..., "Value": ...}] list most AWS APIs want"""
    tags = dict(REQUIRED_TAGS, **(extra or {}))
    return [{"Key": k, "Value": v} for k, v in tags.items()]

2. whoami.py: check the session first

Prints the profile, region, where the credentials came from (creds.method: env, shared-credentials-file, sso, iam-role…), the account id and the identity ARN from STS, warns if you are the root user, and shows the account alias. Run it at the start of every session; it catches the wrong profile or region before anything is created.

πŸ“„ charminar-aws-basics/whoami.py

"""whoami.py - check the session BEFORE you touch anything: which account, which identity, which region.

Run it first in every new terminal. Most "it worked yesterday" problems are a wrong profile or region.
"""
import sys

from botocore.exceptions import ClientError, NoCredentialsError

import config as C


def main():
    s = C.session()
    creds = s.get_credentials()
    if creds is None:
        sys.exit("No credentials found. Run: aws configure --profile <name>  then  export AWS_PROFILE=<name>")
    print("profile       :", C.AWS_PROFILE or "(default chain)")
    print("region        :", s.region_name)
    print("credentials   :", creds.method)          # shared-credentials-file, env, iam-role, sso ...
    print("endpoint      :", C.ENDPOINT_URL or "real AWS")
    try:
        me = C.client("sts").get_caller_identity()
    except (ClientError, NoCredentialsError) as e:
        sys.exit(f"STS call failed: {e}")
    arn = me["Arn"]
    print("account id    :", me["Account"])
    print("identity ARN  :", arn)
    kind = arn.split(":")[5].split("/")[0]        # user / assumed-role / root
    print("identity type :", kind)
    if arn.endswith(":root"):
        print("WARNING: you are using the ROOT user. Create an IAM Identity Center user or IAM user and stop using root.")
    aliases = C.client("iam").list_account_aliases()["AccountAliases"]
    print("account alias :", aliases[0] if aliases else "(none - set one with iam create-account-alias)")


if __name__ == "__main__":
    main()

3. regions.py and arn_tools.py: global infrastructure and names

describe_regions(AllRegions=True) returns every region with its OptInStatus: newer regions must be enabled per account before use. describe_availability_zones is regional, so regions.py creates one client per region. arn_tools.py splits an ARN into its six parts and builds the ARNs you will write in policies.

πŸ“„ charminar-aws-basics/regions.py

"""regions.py - regions, opt-in status and Availability Zones (the global infrastructure from code)."""
import config as C

INDIA = ["ap-south-1", "ap-south-2"]          # Mumbai, Hyderabad


def enabled_regions():
    ec2 = C.client("ec2")
    regs = ec2.describe_regions(AllRegions=True)["Regions"]
    on = [r["RegionName"] for r in regs if r["OptInStatus"] in ("opt-in-not-required", "opted-in")]
    off = [r["RegionName"] for r in regs if r["OptInStatus"] == "not-opted-in"]
    return sorted(on), sorted(off)


def zones(region):
    ec2 = C.client("ec2", region=region)
    return [(z["ZoneName"], z["ZoneId"], z["State"]) for z in ec2.describe_availability_zones()["AvailabilityZones"]]


def main():
    on, off = enabled_regions()
    print(f"regions enabled for this account: {len(on)}")
    print(f"opt-in regions not enabled      : {len(off)} (e.g. {', '.join(off[:3])})")
    for r in INDIA:
        print(f"\n{r}:")
        for name, zid, state in zones(r):
            print(f"  {name:<12} id={zid:<9} {state}")


if __name__ == "__main__":
    main()

πŸ“„ charminar-aws-basics/arn_tools.py

"""arn_tools.py - read and build ARNs (Amazon Resource Names).

arn:partition:service:region:account-id:resource
S3 bucket ARNs have no region and no account; IAM ARNs have no region (IAM is global).
"""
import config as C


def parse(arn):
    parts = arn.split(":", 5)
    if len(parts) != 6 or parts[0] != "arn":
        raise ValueError(f"not an ARN: {arn}")
    _, partition, service, region, account, resource = parts
    return {"partition": partition, "service": service, "region": region or "(global)",
            "account": account or "(none)", "resource": resource}


def build(service, resource, region="", account=""):
    return f"arn:aws:{service}:{region}:{account}:{resource}"


def main():
    account = C.client("sts").get_caller_identity()["Account"]
    examples = [
        build("s3", "charminar-cart-dev-raw"),
        build("s3", "charminar-cart-dev-raw/orders/*"),
        build("iam", "role/charminar-glue-role", account=account),
        build("lambda", "function:charminar-order-validator", C.AWS_REGION, account),
        build("sqs", "charminar-orders", C.AWS_REGION, account),
        build("glue", "table/sales/orders", C.AWS_REGION, account),
    ]
    for arn in examples:
        p = parse(arn)
        print(arn)
        print(f"   service={p['service']:<7} region={p['region']:<11} account={p['account']:<13} resource={p['resource']}")


if __name__ == "__main__":
    main()

4. tagging.py: tags you can search and audit

πŸ“„ charminar-aws-basics/tagging.py

"""tagging.py - create a tagged bucket, add tags, find resources by tag, report missing tags.

Tags are key=value labels. They drive cost reports (activate them as cost allocation tags in
Billing), automation and access rules. Keys are case-sensitive: "Env" and "env" are different tags.
"""
from botocore.exceptions import ClientError

import config as C


def create_tagged_bucket(name):
    s3 = C.client("s3")
    try:
        if C.AWS_REGION == "us-east-1":
            s3.create_bucket(Bucket=name)
        else:
            s3.create_bucket(Bucket=name, CreateBucketConfiguration={"LocationConstraint": C.AWS_REGION})
        print(f"created bucket   {name}")
    except ClientError as e:
        if e.response["Error"]["Code"] != "BucketAlreadyOwnedByYou":
            raise
        print(f"bucket exists    {name}")
    s3.put_bucket_tagging(Bucket=name, Tagging={"TagSet": C.tag_list({"zone": "demo"})})
    tags = {t["Key"]: t["Value"] for t in s3.get_bucket_tagging(Bucket=name)["TagSet"]}
    print(f"tags on bucket   {tags}")


def untagged_bucket(name):
    """a bucket created the lazy way, so the audit has something to find"""
    s3 = C.client("s3")
    try:
        s3.create_bucket(Bucket=name, CreateBucketConfiguration={"LocationConstraint": C.AWS_REGION})
    except ClientError as e:
        if e.response["Error"]["Code"] != "BucketAlreadyOwnedByYou":
            raise
    s3.put_bucket_tagging(Bucket=name, Tagging={"TagSet": [{"Key": "project", "Value": C.PROJECT}]})


def find_by_tag(key, value):
    api = C.client("resourcegroupstaggingapi")
    arns = []
    for page in api.get_paginator("get_resources").paginate(TagFilters=[{"Key": key, "Values": [value]}]):
        arns += [r["ResourceARN"] for r in page["ResourceTagMappingList"]]
    return sorted(arns)


def missing_tags_report():
    api = C.client("resourcegroupstaggingapi")
    bad = []
    for page in api.get_paginator("get_resources").paginate():
        for r in page["ResourceTagMappingList"]:
            have = {t["Key"] for t in r["Tags"]}
            missing = sorted(set(C.REQUIRED_TAGS) - have)
            if missing:
                bad.append((r["ResourceARN"], missing))
    return bad


def main():
    create_tagged_bucket(C.DEMO_BUCKET)
    untagged_bucket(C.DEMO_BUCKET + "-tmp")
    print(f"\nresources with project={C.PROJECT}:")
    for arn in find_by_tag("project", C.PROJECT):
        print("  ", arn)
    print("\nmissing required tags:")
    report = missing_tags_report()
    for arn, missing in report:
        print(f"   {arn}  -> missing {missing}")
    if not report:
        print("   none: every resource is tagged")


if __name__ == "__main__":
    main()

5. budget_alerts.py: budget and billing alarm

Creates a monthly COST budget of MONTHLY_BUDGET_USD with three e-mail alerts (50 % and 80 % of actual spend, 100 % of forecast), or updates it if it exists. Then it creates an SNS topic in us-east-1, subscribes your e-mail (click the confirmation link AWS sends) and a CloudWatch alarm on AWS/Billing EstimatedCharges checked every 6 hours. Turn on "Receive CloudWatch billing alerts" in the Billing preferences once, or the metric never appears.

πŸ“„ charminar-aws-basics/budget_alerts.py

"""budget_alerts.py - the first thing to do in a new account: a monthly budget + a billing alarm.

1. AWS Budgets: e-mail at 50 % and 80 % of the ACTUAL spend and at 100 % of the FORECAST.
2. CloudWatch billing alarm on AWS/Billing EstimatedCharges (lives only in us-east-1).
   Turn on "Receive CloudWatch billing alerts" once in Billing preferences, or the metric never appears.
Safe to run again: an existing budget / topic / alarm is updated, not duplicated.
"""
from botocore.exceptions import ClientError

import config as C

BUDGET_NAME = f"{C.PROJECT}-monthly"


def notifications():
    rules = [("ACTUAL", 50), ("ACTUAL", 80), ("FORECASTED", 100)]
    return [{"Notification": {"NotificationType": kind, "ComparisonOperator": "GREATER_THAN",
                              "Threshold": pct, "ThresholdType": "PERCENTAGE"},
             "Subscribers": [{"SubscriptionType": "EMAIL", "Address": C.ALERT_EMAIL}]}
            for kind, pct in rules]


def create_budget(account):
    b = C.client("budgets", region=C.BILLING_REGION)
    budget = {"BudgetName": BUDGET_NAME, "BudgetType": "COST", "TimeUnit": "MONTHLY",
              "BudgetLimit": {"Amount": C.MONTHLY_BUDGET_USD, "Unit": "USD"}}
    try:
        cur = b.describe_budget(AccountId=account, BudgetName=BUDGET_NAME)["Budget"]
    except ClientError as e:
        if e.response["Error"]["Code"] != "NotFoundException":
            raise
        b.create_budget(AccountId=account, Budget=budget, NotificationsWithSubscribers=notifications())
        print(f"budget created   {BUDGET_NAME}: {C.MONTHLY_BUDGET_USD} USD / month")
        cur = None
    if cur and float(cur["BudgetLimit"]["Amount"]) != float(C.MONTHLY_BUDGET_USD):
        b.update_budget(AccountId=account, NewBudget=budget)      # only the limit changed
        print(f"budget updated   {BUDGET_NAME}: {C.MONTHLY_BUDGET_USD} USD / month")
    elif cur:
        print(f"budget exists    {BUDGET_NAME}: {C.MONTHLY_BUDGET_USD} USD / month")
    for n in b.describe_notifications_for_budget(AccountId=account, BudgetName=BUDGET_NAME)["Notifications"]:
        print(f"   alert when {n['NotificationType'].lower():<10} > {n['Threshold']:.0f} %  -> {C.ALERT_EMAIL}")


def create_billing_alarm():
    sns = C.client("sns", region=C.BILLING_REGION)
    topic = sns.create_topic(Name=f"{C.PROJECT}-billing-alerts",
                             Tags=C.tag_list())["TopicArn"]          # create_topic is idempotent
    sns.subscribe(TopicArn=topic, Protocol="email", Endpoint=C.ALERT_EMAIL)   # confirm the e-mail AWS sends
    cw = C.client("cloudwatch", region=C.BILLING_REGION)
    name = f"{C.PROJECT}-bill-over-{C.BILLING_ALARM_USD}-usd"
    cw.put_metric_alarm(
        AlarmName=name, Namespace="AWS/Billing", MetricName="EstimatedCharges",
        Dimensions=[{"Name": "Currency", "Value": "USD"}], Statistic="Maximum",
        Period=21600, EvaluationPeriods=1, Threshold=C.BILLING_ALARM_USD,
        ComparisonOperator="GreaterThanThreshold", TreatMissingData="notBreaching",
        AlarmActions=[topic], Tags=C.tag_list())
    a = cw.describe_alarms(AlarmNames=[name])["MetricAlarms"][0]
    print(f"billing alarm    {a['AlarmName']} ({a['MetricName']} > {a['Threshold']:.0f} USD, every 6 h)")
    print(f"alarm action     SNS topic {topic.split(':')[-1]} in {C.BILLING_REGION}")


def main():
    account = C.client("sts").get_caller_identity()["Account"]
    create_budget(account)
    create_billing_alarm()


if __name__ == "__main__":
    main()

6. cost_report.py and vpc_peek.py

cost_report.py asks Cost Explorer for this month's unblended cost grouped by service and by the project tag. Enable Cost Explorer once in the console; each API request has a small charge, so run it once a day, not in a loop. vpc_peek.py shows the default VPC, one subnet per AZ and whether an internet gateway is attached.

πŸ“„ charminar-aws-basics/cost_report.py

"""cost_report.py - this month's cost per service and per "project" tag (Cost Explorer API).

Cost Explorer must be enabled once in the Billing console. Each API call is billed (a small fee per
request), so run it daily, not in a loop. Tag-based numbers need the tag ACTIVATED as a cost allocation tag.
"""
import datetime as dt

import config as C


def month_range(today=None):
    today = today or dt.date.today()
    start = today.replace(day=1)
    end = today + dt.timedelta(days=1)          # End is exclusive
    return start.isoformat(), end.isoformat()


def cost_by(group_type, key):
    ce = C.client("ce", region=C.BILLING_REGION)
    start, end = month_range()
    resp = ce.get_cost_and_usage(TimePeriod={"Start": start, "End": end}, Granularity="MONTHLY",
                                 Metrics=["UnblendedCost"], GroupBy=[{"Type": group_type, "Key": key}])
    rows = []
    for period in resp["ResultsByTime"]:
        for g in period["Groups"]:
            amt = float(g["Metrics"]["UnblendedCost"]["Amount"])
            rows.append((g["Keys"][0], amt))
    return sorted(rows, key=lambda r: -r[1])


def show(title, rows):
    print(title)
    if not rows:
        print("   (no cost data yet: new account, Cost Explorer not enabled, or a local emulator)")
    for name, amt in rows[:10]:
        print(f"   {name:<40} {amt:>10.2f} USD")


def main():
    show("this month by service:", cost_by("DIMENSION", "SERVICE"))
    show("this month by project tag:", cost_by("TAG", "project"))


if __name__ == "__main__":
    main()

πŸ“„ charminar-aws-basics/vpc_peek.py

"""vpc_peek.py - VPC basics at a glance: the default VPC and one subnet per Availability Zone.

A VPC is your private network in one region. Subnets live in ONE AZ each. Every region of a new
account comes with a default VPC (CIDR 172.31.0.0/16) and one default public subnet per AZ.
"""
import config as C


def main():
    ec2 = C.client("ec2")
    vpcs = ec2.describe_vpcs(Filters=[{"Name": "is-default", "Values": ["true"]}])["Vpcs"]
    if not vpcs:
        print("no default VPC in", C.AWS_REGION)
        return
    vpc = vpcs[0]
    print(f"default VPC in {C.AWS_REGION}: CIDR {vpc['CidrBlock']}")
    subnets = ec2.describe_subnets(Filters=[{"Name": "vpc-id", "Values": [vpc["VpcId"]]}])["Subnets"]
    for s in sorted(subnets, key=lambda s: s["AvailabilityZone"]):
        public = "public" if s["MapPublicIpOnLaunch"] else "private"
        print(f"   subnet {s['CidrBlock']:<16} in {s['AvailabilityZone']}  ({public}, {s['AvailableIpAddressCount']} free IPs)")
    igws = ec2.describe_internet_gateways(Filters=[{"Name": "attachment.vpc-id", "Values": [vpc["VpcId"]]}])["InternetGateways"]
    print(f"   internet gateway attached: {'yes' if igws else 'no'}")


if __name__ == "__main__":
    main()

7. tag_audit_handler.py: the audit as a Lambda function

The same missing-tags report as a Lambda handler. Deploy it with config.py and tagging.py in the zip, give the role tag:GetResources (and sns:Publish if you set AUDIT_TOPIC_ARN), and trigger it daily with an EventBridge schedule. Locally the __main__ block calls the handler with a test event.

πŸ“„ charminar-aws-basics/tag_audit_handler.py

"""tag_audit_handler.py - a Lambda function that runs the missing-tags audit every morning.

Schedule it with an EventBridge rule, e.g. cron(30 3 * * ? *) = 9:00 AM IST. The function's role needs
tag:GetResources and sns:Publish. Locally: python tag_audit_handler.py
"""
import json
import os

import config as C
from tagging import missing_tags_report

TOPIC_ARN = os.getenv("AUDIT_TOPIC_ARN")        # optional: publish the report to SNS


def lambda_handler(event, context):
    bad = missing_tags_report()
    report = {"checked_tags": sorted(C.REQUIRED_TAGS), "untagged": len(bad),
              "resources": [{"arn": arn, "missing": m} for arn, m in bad]}
    if bad and TOPIC_ARN:
        C.client("sns").publish(TopicArn=TOPIC_ARN, Subject="Untagged AWS resources",
                                Message=json.dumps(report, indent=2))
    return report


if __name__ == "__main__":
    print(json.dumps(lambda_handler({"source": "local-test"}, None), indent=2))

8. cleanup.py: leave nothing running

Deletes the two lab buckets (after emptying them), the budget, the alarm and the topic. It refuses to run without --yes.

πŸ“„ charminar-aws-basics/cleanup.py

"""cleanup.py - delete what the lab created, so nothing keeps costing money. Asks for --yes."""
import sys

from botocore.exceptions import ClientError

import config as C
from budget_alerts import BUDGET_NAME


def empty_and_delete(bucket):
    s3 = C.client("s3")
    try:
        for page in s3.get_paginator("list_objects_v2").paginate(Bucket=bucket):
            for o in page.get("Contents", []):
                s3.delete_object(Bucket=bucket, Key=o["Key"])
        s3.delete_bucket(Bucket=bucket)
        print("deleted bucket  ", bucket)
    except ClientError as e:
        print("skip bucket     ", bucket, e.response["Error"]["Code"])


def main():
    if "--yes" not in sys.argv:
        sys.exit("This deletes the lab buckets, budget, alarm and topic. Run again with --yes")
    for b in (C.DEMO_BUCKET, C.DEMO_BUCKET + "-tmp"):
        empty_and_delete(b)
    account = C.client("sts").get_caller_identity()["Account"]
    C.client("budgets", region=C.BILLING_REGION).delete_budget(AccountId=account, BudgetName=BUDGET_NAME)
    print("deleted budget  ", BUDGET_NAME)
    C.client("cloudwatch", region=C.BILLING_REGION).delete_alarms(AlarmNames=[f"{C.PROJECT}-bill-over-{C.BILLING_ALARM_USD}-usd"])
    sns = C.client("sns", region=C.BILLING_REGION)
    sns.delete_topic(TopicArn=f"arn:aws:sns:{C.BILLING_REGION}:{account}:{C.PROJECT}-billing-alerts")
    print("deleted alarm and SNS topic")


if __name__ == "__main__":
    main()

9. IAM policies (least privilege)

lab_runner_policy.json is everything these scripts need and nothing more: read-only "look around" calls, S3 actions only on charminar-cart-dev-basics-* buckets, budgets, the billing alarm and topic only with the charminar-cart- prefix, and Cost Explorer read. Replace 111122223333 with your account id. data_team_boundary.json is a guardrail example (use it as a permissions boundary or as an SCP in AWS Organizations): it denies regional services outside the two Indian regions and denies creating a Glue job, Lambda function or queue without a project tag.

πŸ“„ charminar-aws-basics/policies/lab_runner_policy.json

{
  "Version": "2012-10-17",
  "Statement": [
    {"Sid": "WhoAmIAndLookAround", "Effect": "Allow",
     "Action": ["sts:GetCallerIdentity", "iam:ListAccountAliases", "ec2:DescribeRegions",
                "ec2:DescribeAvailabilityZones", "ec2:DescribeVpcs", "ec2:DescribeSubnets",
                "ec2:DescribeInternetGateways", "tag:GetResources"],
     "Resource": "*"},
    {"Sid": "LabBucketsOnly", "Effect": "Allow",
     "Action": ["s3:CreateBucket", "s3:DeleteBucket", "s3:PutBucketTagging", "s3:GetBucketTagging",
                "s3:ListBucket", "s3:DeleteObject"],
     "Resource": ["arn:aws:s3:::charminar-cart-dev-basics-*", "arn:aws:s3:::charminar-cart-dev-basics-*/*"]},
    {"Sid": "BudgetsForThisAccount", "Effect": "Allow",
     "Action": ["budgets:ViewBudget", "budgets:ModifyBudget"],
     "Resource": "arn:aws:budgets::111122223333:budget/charminar-cart-*"},
    {"Sid": "BillingAlarmAndTopic", "Effect": "Allow",
     "Action": ["cloudwatch:PutMetricAlarm", "cloudwatch:DescribeAlarms", "cloudwatch:DeleteAlarms",
                "sns:CreateTopic", "sns:Subscribe", "sns:DeleteTopic", "sns:TagResource"],
     "Resource": ["arn:aws:cloudwatch:us-east-1:111122223333:alarm:charminar-cart-*",
                  "arn:aws:sns:us-east-1:111122223333:charminar-cart-*"]},
    {"Sid": "CostExplorerRead", "Effect": "Allow",
     "Action": ["ce:GetCostAndUsage"], "Resource": "*"}
  ]
}

πŸ“„ charminar-aws-basics/policies/data_team_boundary.json

{
  "Version": "2012-10-17",
  "Statement": [
    {"Sid": "OnlyIndianRegions", "Effect": "Deny",
     "NotAction": ["iam:*", "sts:*", "budgets:*", "ce:*", "cloudwatch:*", "sns:*", "support:*", "organizations:*"],
     "Resource": "*",
     "Condition": {"StringNotEquals": {"aws:RequestedRegion": ["ap-south-1", "ap-south-2"]}}},
    {"Sid": "TagWhatYouCreate", "Effect": "Deny",
     "Action": ["glue:CreateJob", "lambda:CreateFunction", "sqs:CreateQueue"],
     "Resource": "*",
     "Condition": {"Null": {"aws:RequestTag/project": "true"}}}
  ]
}

10. How to run it

On real AWS: do the one-time setup above, export AWS_PROFILE=charminar-dev, change DEMO_BUCKET and ALERT_EMAIL in config.py (or export them), skip the emulator block, and run the same commands. On your laptop without AWS: run every block below in one terminal, in this order.

Terminal: install (Python 3.9 or newer)

python3 -m venv .venv
source .venv/bin/activate          # Windows (Git Bash): source .venv/Scripts/activate
pip install -q -r requirements.txt

Terminal: start the local AWS emulator (laptop only)

moto_server -p 8430 > moto.log 2>&1 &
echo $! > moto.pid
sleep 3
export AWS_ENDPOINT_URL=http://127.0.0.1:8430
export AWS_ACCESS_KEY_ID=testing AWS_SECRET_ACCESS_KEY=testing
export AWS_DEFAULT_REGION=ap-south-1

Who am I?

python whoami.py

Output

profile       : (default chain)
region        : ap-south-1
credentials   : env
endpoint      : http://127.0.0.1:8430
account id    : 123456789012
identity ARN  : arn:aws:sts::123456789012:user/moto
identity type : user
account alias : (none - set one with iam create-account-alias)

The 12 lines of step 9

python first_steps.py

Output: see the step 9 card above.

Regions, AZs and ARNs

python regions.py

Output

regions enabled for this account: 24
opt-in regions not enabled      : 14 (e.g. ap-east-1, ap-east-2, ap-south-2)

ap-south-1:
  ap-south-1a  id=aps1-az1  available
  ap-south-1b  id=aps1-az3  available
  ap-south-1c  id=aps1-az2  available

ap-south-2:
  ap-south-2a  id=aps2-az1  available
  ap-south-2b  id=aps2-az2  available
  ap-south-2c  id=aps2-az3  available
python arn_tools.py

Output

arn:aws:s3:::charminar-cart-dev-raw
   service=s3      region=(global)    account=(none)        resource=charminar-cart-dev-raw
arn:aws:s3:::charminar-cart-dev-raw/orders/*
   service=s3      region=(global)    account=(none)        resource=charminar-cart-dev-raw/orders/*
arn:aws:iam::123456789012:role/charminar-glue-role
   service=iam     region=(global)    account=123456789012  resource=role/charminar-glue-role
arn:aws:lambda:ap-south-1:123456789012:function:charminar-order-validator
   service=lambda  region=ap-south-1  account=123456789012  resource=function:charminar-order-validator
arn:aws:sqs:ap-south-1:123456789012:charminar-orders
   service=sqs     region=ap-south-1  account=123456789012  resource=charminar-orders
arn:aws:glue:ap-south-1:123456789012:table/sales/orders
   service=glue    region=ap-south-1  account=123456789012  resource=table/sales/orders

Tags

python tagging.py

Output

created bucket   charminar-cart-dev-basics-change-me
tags on bucket   {'project': 'charminar-cart', 'env': 'dev', 'owner': 'data-team@charminarcart.example', 'cost-center': 'data-engineering', 'zone': 'demo'}

resources with project=charminar-cart:
   arn:aws:s3:::charminar-cart-dev-basics-change-me
   arn:aws:s3:::charminar-cart-dev-basics-change-me-tmp

missing required tags:
   arn:aws:s3:::charminar-cart-dev-basics-change-me-tmp  -> missing ['cost-center', 'env', 'owner']

The same checks with the AWS CLI

aws sts get-caller-identity
aws ec2 describe-availability-zones --region ap-south-1 --query "AvailabilityZones[].ZoneName" --output text
aws s3api list-buckets --query "Buckets[].Name" --output text

Output

{
    "UserId": "AKIAIOSFODNN7EXAMPLE",
    "Account": "123456789012",
    "Arn": "arn:aws:sts::123456789012:user/moto"
}
ap-south-1a	ap-south-1b	ap-south-1c
charminar-cart-dev-basics-change-me	charminar-cart-dev-basics-change-me-tmp

Budget and billing alarm

python budget_alerts.py

Output

budget created   charminar-cart-monthly: 25 USD / month
   alert when actual     > 50 %  -> you@example.com
   alert when actual     > 80 %  -> you@example.com
   alert when forecasted > 100 %  -> you@example.com
billing alarm    charminar-cart-bill-over-20-usd (EstimatedCharges > 20 USD, every 6 h)
alarm action     SNS topic charminar-cart-billing-alerts in us-east-1

Cost report and VPC

python cost_report.py

Output

this month by service:
   (no cost data yet: new account, Cost Explorer not enabled, or a local emulator)
this month by project tag:
   (no cost data yet: new account, Cost Explorer not enabled, or a local emulator)
python vpc_peek.py

Output

default VPC in ap-south-1: CIDR 172.31.0.0/16
   subnet 172.31.0.0/20    in ap-south-1a  (public, 4091 free IPs)
   subnet 172.31.16.0/20   in ap-south-1b  (public, 4091 free IPs)
   subnet 172.31.32.0/20   in ap-south-1c  (public, 4091 free IPs)
   internet gateway attached: no

The Lambda audit, locally

python tag_audit_handler.py

Output

{
  "checked_tags": [
    "cost-center",
    "env",
    "owner",
    "project"
  ],
  "untagged": 1,
  "resources": [
    {
      "arn": "arn:aws:s3:::charminar-cart-dev-basics-change-me-tmp",
      "missing": [
        "cost-center",
        "env",
        "owner"
      ]
    }
  ]
}

Clean up and stop the emulator

python cleanup.py --yes

Output

deleted bucket   charminar-cart-dev-basics-change-me
deleted bucket   charminar-cart-dev-basics-change-me-tmp
deleted budget   charminar-cart-monthly
deleted alarm and SNS topic
kill $(cat moto.pid)
deactivate

11. Common errors and fixes

Error or symptomCauseFix
NoCredentialsError: Unable to locate credentialsNo profile, no env variables, no roleaws configure sso or aws configure, then export AWS_PROFILE=…
ProfileNotFound: The config profile (x) could not be foundAWS_PROFILE names a profile that is not in ~/.aws/configaws configure list-profiles; fix the name or unset AWS_PROFILE
NoRegionError: You must specify a regionNo region in code, env or profileSet AWS_REGION or region = ap-south-1 in the profile
ExpiredToken / The SSO session has expiredTemporary credentials ran outaws sso login --profile charminar-dev
AccessDenied ... is not authorized to perform: s3:CreateBucketNo Allow for that action on that ARN, or an explicit Deny (SCP, boundary)Read the action and ARN in the message; add exactly that to the policy; check guardrails
IllegalLocationConstraintExceptioncreate_bucket outside us-east-1 without (or with a wrong) LocationConstraintPass CreateBucketConfiguration={"LocationConstraint": region}
BucketAlreadyExistsBucket names are global; someone else has itAdd your account id or a suffix to the name
SignatureDoesNotMatch / InvalidClientTokenIdWrong secret key, a deactivated key, or the computer clock is wrongCreate a new key or use SSO; sync the system clock
Resource "missing" in the consoleThe console shows another regionSwitch the region selector; check AWS_REGION in your scripts
Billing alarm never fires / metric not foundBilling alerts not enabled, or alarm created outside us-east-1Enable billing alerts in Billing preferences; create the alarm in us-east-1

Big data architecture Python code (Charminar Cart platform bootstrap)

πŸ“„ charminar-bootstrap/requirements.txt

boto3>=1.34
moto[server]>=5.0

πŸ“„ charminar-bootstrap/config.py

"""config.py - Charminar Cart AWS bootstrap: one data-platform landing zone per environment."""
import os

import boto3

AWS_REGION = os.getenv("AWS_REGION", "ap-south-1")
AWS_PROFILE = os.getenv("AWS_PROFILE")
ENDPOINT_URL = os.getenv("AWS_ENDPOINT_URL")
BILLING_REGION = "us-east-1"

PROJECT = "charminar-cart"
ENV = os.getenv("APP_ENV", "dev")
OWNER = "data-team@charminarcart.example"
ALERT_EMAIL = os.getenv("ALERT_EMAIL", "oncall@charminarcart.example")
MONTHLY_BUDGET_USD = os.getenv("MONTHLY_BUDGET_USD", "150")
BILLING_ALARM_USD = int(os.getenv("BILLING_ALARM_USD", "120"))

ZONES = {
    # zone: (versioning, lifecycle rule)
    "raw": (True, {"transition_days": 30, "storage_class": "STANDARD_IA"}),
    "staged": (False, {"expire_days": 7}),
    "curated": (True, None),
    "athena-results": (False, {"expire_days": 7}),
    "logs": (False, {"expire_days": 90}),
}

REQUIRED_TAGS = ["project", "env", "owner", "cost-center"]
BASE_TAGS = {"project": PROJECT, "env": ENV, "owner": OWNER, "cost-center": "data-engineering",
             "managed-by": "bootstrap-python"}

_session = boto3.Session(profile_name=AWS_PROFILE, region_name=AWS_REGION)


def client(service, region=None, creds=None):
    kw = {}
    if creds:
        kw = {"aws_access_key_id": creds["AccessKeyId"], "aws_secret_access_key": creds["SecretAccessKey"],
              "aws_session_token": creds["SessionToken"]}
        return boto3.client(service, region_name=region or AWS_REGION, endpoint_url=ENDPOINT_URL, **kw)
    return _session.client(service, region_name=region or AWS_REGION, endpoint_url=ENDPOINT_URL)

πŸ“„ charminar-bootstrap/naming.py

"""naming.py - one naming convention, ARNs and tags for every resource."""
import functools

import config as C


@functools.lru_cache(maxsize=1)
def account_id():
    return C.client("sts").get_caller_identity()["Account"]


def name(*parts):
    return "-".join([C.PROJECT, C.ENV, *parts])


def bucket(zone):
    return name(zone, account_id())                 # account id keeps the global name unique


def bucket_arn(zone, objects=False):
    return f"arn:aws:s3:::{bucket(zone)}" + ("/*" if objects else "")


def role_arn(role):
    return f"arn:aws:iam::{account_id()}:role/{role}"


def tags(extra=None, style="list"):
    t = dict(C.BASE_TAGS, **(extra or {}))
    if style == "dict":
        return t
    return [{"Key": k, "Value": v} for k, v in t.items()]

πŸ“„ charminar-bootstrap/s3_zones.py

"""s3_zones.py - one bucket per lake zone: private, encrypted, versioned where needed, lifecycle, tags."""
from botocore.exceptions import ClientError

import config as C
from naming import bucket, tags


def _create(s3, b):
    try:
        if C.AWS_REGION == "us-east-1":
            s3.create_bucket(Bucket=b)
        else:
            s3.create_bucket(Bucket=b, CreateBucketConfiguration={"LocationConstraint": C.AWS_REGION})
        return "created"
    except ClientError as e:
        if e.response["Error"]["Code"] in ("BucketAlreadyOwnedByYou", "BucketAlreadyExists"):
            return "exists "
        raise


def _lifecycle(rule, zone):
    r = {"ID": f"{zone}-lifecycle", "Status": "Enabled", "Filter": {"Prefix": ""}}
    if "expire_days" in rule:
        r["Expiration"] = {"Days": rule["expire_days"]}
    if "transition_days" in rule:
        r["Transitions"] = [{"Days": rule["transition_days"], "StorageClass": rule["storage_class"]}]
    return {"Rules": [r]}


def build_zone(zone):
    s3 = C.client("s3")
    b = bucket(zone)
    state = _create(s3, b)
    s3.put_public_access_block(Bucket=b, PublicAccessBlockConfiguration={
        "BlockPublicAcls": True, "IgnorePublicAcls": True, "BlockPublicPolicy": True, "RestrictPublicBuckets": True})
    s3.put_bucket_encryption(Bucket=b, ServerSideEncryptionConfiguration={
        "Rules": [{"ApplyServerSideEncryptionByDefault": {"SSEAlgorithm": "AES256"}, "BucketKeyEnabled": True}]})
    versioning, rule = C.ZONES[zone]
    if versioning:
        s3.put_bucket_versioning(Bucket=b, VersioningConfiguration={"Status": "Enabled"})
    if rule:
        s3.put_bucket_lifecycle_configuration(Bucket=b, LifecycleConfiguration=_lifecycle(rule, zone))
    s3.put_bucket_tagging(Bucket=b, Tagging={"TagSet": tags({"zone": zone})})
    return state, b


def build_all():
    out = {}
    for zone in C.ZONES:
        state, b = build_zone(zone)
        out[zone] = b
        v, rule = C.ZONES[zone]
        extra = []
        if v:
            extra.append("versioned")
        if rule and "expire_days" in rule:
            extra.append(f"expire {rule['expire_days']} d")
        if rule and "transition_days" in rule:
            extra.append(f"IA after {rule['transition_days']} d")
        print(f"  {state} s3://{b:<52} {', '.join(extra) or '-'}")
    return out


def describe(zone):
    s3 = C.client("s3")
    b = bucket(zone)
    enc = s3.get_bucket_encryption(Bucket=b)["ServerSideEncryptionConfiguration"]["Rules"][0]
    pab = s3.get_public_access_block(Bucket=b)["PublicAccessBlockConfiguration"]
    ver = s3.get_bucket_versioning(Bucket=b).get("Status", "Off")
    return {"encryption": enc["ApplyServerSideEncryptionByDefault"]["SSEAlgorithm"],
            "public_blocked": all(pab.values()), "versioning": ver}

πŸ“„ charminar-bootstrap/iam_roles.py

"""iam_roles.py - service roles with least-privilege inline policies scoped to the zone buckets."""
import json

from botocore.exceptions import ClientError

import config as C
from naming import account_id, bucket_arn, name, tags


def trust(service):
    return {"Version": "2012-10-17", "Statement": [{
        "Effect": "Allow", "Principal": {"Service": service}, "Action": "sts:AssumeRole"}]}


def trust_with_local_test(service):
    """local emulator only: let this account assume the role for the smoke test; on real AWS only the service may"""
    doc = trust(service)
    if C.ENDPOINT_URL:
        doc["Statement"].append({"Effect": "Allow", "Principal": {"AWS": f"arn:aws:iam::{account_id()}:root"},
                                 "Action": "sts:AssumeRole"})
    return doc


def glue_policy():
    return {"Version": "2012-10-17", "Statement": [
        {"Sid": "ReadRaw", "Effect": "Allow", "Action": ["s3:GetObject"], "Resource": [bucket_arn("raw", True)]},
        {"Sid": "WriteStagedCurated", "Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
         "Resource": [bucket_arn("staged", True), bucket_arn("curated", True)]},
        {"Sid": "ListZones", "Effect": "Allow", "Action": ["s3:ListBucket"],
         "Resource": [bucket_arn("raw"), bucket_arn("staged"), bucket_arn("curated")]},
        {"Sid": "Logs", "Effect": "Allow", "Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
         "Resource": "arn:aws:logs:*:*:log-group:/aws-glue/*"}]}


def ingest_policy():
    return {"Version": "2012-10-17", "Statement": [
        {"Sid": "WriteRawOnly", "Effect": "Allow", "Action": ["s3:PutObject"], "Resource": [bucket_arn("raw", True)]},
        {"Sid": "Logs", "Effect": "Allow", "Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
         "Resource": "arn:aws:logs:*:*:*"}]}


ROLES = {
    "glue-etl": ("glue.amazonaws.com", glue_policy),
    "lambda-ingest": ("lambda.amazonaws.com", ingest_policy),
}


def ensure_role(short, service, policy_fn):
    iam = C.client("iam")
    role = name(short)
    try:
        iam.create_role(RoleName=role, AssumeRolePolicyDocument=json.dumps(trust_with_local_test(service)),
                        Description=f"{C.PROJECT} {short} role", Tags=tags(), MaxSessionDuration=3600)
        state = "created"
    except ClientError as e:
        if e.response["Error"]["Code"] != "EntityAlreadyExists":
            raise
        state = "exists "
    iam.put_role_policy(RoleName=role, PolicyName=f"{role}-least-privilege", PolicyDocument=json.dumps(policy_fn()))
    arn = iam.get_role(RoleName=role)["Role"]["Arn"]
    n = len(policy_fn()["Statement"])
    print(f"  {state} {arn}  ({n} statements, trusted by {service})")
    return arn


def build_all():
    return {short: ensure_role(short, svc, fn) for short, (svc, fn) in ROLES.items()}


def assume(role_arn, session_name="bootstrap-smoke-test"):
    return C.client("sts").assume_role(RoleArn=role_arn, RoleSessionName=session_name, DurationSeconds=900)["Credentials"]

πŸ“„ charminar-bootstrap/network.py

"""network.py - VPC basics for the data platform: default VPC, subnets per AZ, an S3 gateway endpoint."""
import config as C
from naming import tags


def default_vpc():
    ec2 = C.client("ec2")
    vpc = ec2.describe_vpcs(Filters=[{"Name": "is-default", "Values": ["true"]}])["Vpcs"][0]
    subnets = ec2.describe_subnets(Filters=[{"Name": "vpc-id", "Values": [vpc["VpcId"]]}])["Subnets"]
    return vpc, sorted(subnets, key=lambda s: s["AvailabilityZone"])


def s3_gateway_endpoint(vpc_id):
    """traffic from Glue / EMR in the VPC to S3 stays on the AWS network (gateway endpoints have no hourly charge)"""
    ec2 = C.client("ec2")
    svc = f"com.amazonaws.{C.AWS_REGION}.s3"
    found = ec2.describe_vpc_endpoints(Filters=[{"Name": "vpc-id", "Values": [vpc_id]},
                                                {"Name": "service-name", "Values": [svc]}])["VpcEndpoints"]
    if found:
        return "exists ", svc
    rts = [r["RouteTableId"] for r in ec2.describe_route_tables(
        Filters=[{"Name": "vpc-id", "Values": [vpc_id]}])["RouteTables"]]
    ec2.create_vpc_endpoint(VpcId=vpc_id, ServiceName=svc, VpcEndpointType="Gateway", RouteTableIds=rts,
                            TagSpecifications=[{"ResourceType": "vpc-endpoint", "Tags": tags()}])
    return "created", svc


def build():
    vpc, subnets = default_vpc()
    print(f"  VPC {vpc['CidrBlock']} in {C.AWS_REGION}: {len(subnets)} subnets in "
          f"{', '.join(s['AvailabilityZone'] for s in subnets)}")
    state, svc = s3_gateway_endpoint(vpc["VpcId"])
    print(f"  {state} gateway endpoint {svc}")
    return vpc["VpcId"]

πŸ“„ charminar-bootstrap/guardrails.py

"""guardrails.py - cost and audit guardrails: budget, billing alarm, alert topic, CloudTrail."""
import json

from botocore.exceptions import ClientError

import config as C
from naming import account_id, bucket, name, tags


def alert_topic():
    sns = C.client("sns", region=C.BILLING_REGION)
    arn = sns.create_topic(Name=name("alerts"), Tags=tags())["TopicArn"]
    sns.subscribe(TopicArn=arn, Protocol="email", Endpoint=C.ALERT_EMAIL)
    return arn


def budget():
    b = C.client("budgets", region=C.BILLING_REGION)
    bn = name("monthly-budget")
    spec = {"BudgetName": bn, "BudgetType": "COST", "TimeUnit": "MONTHLY",
            "BudgetLimit": {"Amount": C.MONTHLY_BUDGET_USD, "Unit": "USD"},
            "CostFilters": {"TagKeyValue": [f"user:project${C.PROJECT}"]}}
    subs = [{"SubscriptionType": "EMAIL", "Address": C.ALERT_EMAIL}]
    notes = [{"Notification": {"NotificationType": t, "ComparisonOperator": "GREATER_THAN", "Threshold": p,
                               "ThresholdType": "PERCENTAGE"}, "Subscribers": subs}
             for t, p in (("ACTUAL", 80), ("FORECASTED", 100))]
    try:
        cur = b.describe_budget(AccountId=account_id(), BudgetName=bn)["Budget"]
    except ClientError as e:
        if e.response["Error"]["Code"] != "NotFoundException":
            raise
        b.create_budget(AccountId=account_id(), Budget=spec, NotificationsWithSubscribers=notes)
        return "created", bn
    if float(cur["BudgetLimit"]["Amount"]) == float(C.MONTHLY_BUDGET_USD):
        return "exists ", bn
    b.update_budget(AccountId=account_id(), NewBudget=spec)
    return "updated", bn


def billing_alarm(topic_arn):
    cw = C.client("cloudwatch", region=C.BILLING_REGION)
    an = name("bill-over", f"{C.BILLING_ALARM_USD}usd")
    cw.put_metric_alarm(AlarmName=an, Namespace="AWS/Billing", MetricName="EstimatedCharges",
                        Dimensions=[{"Name": "Currency", "Value": "USD"}], Statistic="Maximum", Period=21600,
                        EvaluationPeriods=1, Threshold=C.BILLING_ALARM_USD, ComparisonOperator="GreaterThanThreshold",
                        TreatMissingData="notBreaching", AlarmActions=[topic_arn], Tags=tags())
    return an


def trail():
    """CloudTrail: who did what, when, from where. Logs go to the logs bucket."""
    logs = bucket("logs")
    policy = {"Version": "2012-10-17", "Statement": [
        {"Sid": "AclCheck", "Effect": "Allow", "Principal": {"Service": "cloudtrail.amazonaws.com"},
         "Action": "s3:GetBucketAcl", "Resource": f"arn:aws:s3:::{logs}"},
        {"Sid": "Write", "Effect": "Allow", "Principal": {"Service": "cloudtrail.amazonaws.com"},
         "Action": "s3:PutObject", "Resource": f"arn:aws:s3:::{logs}/cloudtrail/AWSLogs/{account_id()}/*",
         "Condition": {"StringEquals": {"s3:x-amz-acl": "bucket-owner-full-control"}}}]}
    C.client("s3").put_bucket_policy(Bucket=logs, Policy=json.dumps(policy))
    ct = C.client("cloudtrail")
    tn = name("trail")
    try:
        ct.create_trail(Name=tn, S3BucketName=logs, S3KeyPrefix="cloudtrail", IsMultiRegionTrail=True,
                        IncludeGlobalServiceEvents=True, EnableLogFileValidation=True, TagsList=tags())
        state = "created"
    except ClientError as e:
        if e.response["Error"]["Code"] != "TrailAlreadyExistsException":
            raise
        state = "exists "
    ct.start_logging(Name=tn)
    return state, tn, ct.get_trail_status(Name=tn)["IsLogging"]


def build():
    topic = alert_topic()
    print(f"  topic    {topic.split(':')[-1]} -> {C.ALERT_EMAIL}")
    state, bn = budget()
    print(f"  {state} budget {bn}: {C.MONTHLY_BUDGET_USD} USD / month (80 % actual, 100 % forecast)")
    print(f"  alarm    {billing_alarm(topic)}")
    state, tn, on = trail()
    print(f"  {state} trail {tn}: multi-region, logging={on}")

πŸ“„ charminar-bootstrap/sample_data.py

"""sample_data.py - one day of Charminar Cart orders (seller upload, 14 Oct 2026)."""
DAY = "2026-10-14"
ORDERS_CSV = """order_id,city,amount,status
CC-5001,Hyderabad,1299.00,DELIVERED
CC-5002,Warangal,499.00,DELIVERED
CC-5003,Hyderabad,2450.50,SHIPPED
CC-5004,Nellore,899.00,DELIVERED
CC-5005,Hyderabad,,DELIVERED
CC-5006,Chennai,1799.00,CANCELLED
CC-5007,Warangal,650.00,SHIPPED
CC-5008,Bengaluru,3200.00,DELIVERED
"""

πŸ“„ charminar-bootstrap/smoke_test.py

"""smoke_test.py - prove the platform works: ingest role writes raw, Glue role promotes raw -> staged -> curated.

Each step runs with the temporary credentials of the role (sts:AssumeRole), exactly like the real service would.
"""
import csv
import io
import json

import config as C
from iam_roles import assume
from naming import bucket, name, role_arn
from sample_data import DAY, ORDERS_CSV


def ingest(creds):
    key = f"orders/ingest_date={DAY}/orders.csv"
    C.client("s3", creds=creds).put_object(Bucket=bucket("raw"), Key=key, Body=ORDERS_CSV.encode())
    return key


def promote(creds, raw_key):
    s3 = C.client("s3", creds=creds)
    rows = list(csv.DictReader(io.StringIO(s3.get_object(Bucket=bucket("raw"), Key=raw_key)["Body"].read().decode())))
    good = [r for r in rows if r["amount"] and r["status"] != "CANCELLED"]
    bad = [r["order_id"] for r in rows if not r["amount"]]
    staged_key = f"orders/order_date={DAY}/orders.jsonl"
    s3.put_object(Bucket=bucket("staged"), Key=staged_key,
                  Body="\n".join(json.dumps(r) for r in good).encode())
    by_city = {}
    for r in good:
        c = by_city.setdefault(r["city"], {"orders": 0, "revenue": 0.0})
        c["orders"] += 1
        c["revenue"] = round(c["revenue"] + float(r["amount"]), 2)
    cur_key = f"city_sales/order_date={DAY}/summary.json"
    s3.put_object(Bucket=bucket("curated"), Key=cur_key, Body=json.dumps(by_city, sort_keys=True).encode())
    return len(rows), len(good), bad, by_city, cur_key


def denied_write(creds):
    """least privilege check: the ingest role must NOT be able to read curated data"""
    try:
        C.client("s3", creds=creds).get_object(Bucket=bucket("curated"), Key="anything")
        return "allowed (policies are not enforced here)"
    except Exception as e:                      # AccessDenied on real AWS
        return type(e).__name__


def run():
    ingest_creds = assume(role_arn(name("lambda-ingest")), "ingest-smoke")
    raw_key = ingest(ingest_creds)
    print(f"  lambda-ingest wrote s3://{bucket('raw')}/{raw_key}")
    glue_creds = assume(role_arn(name("glue-etl")), "glue-smoke")
    total, good, bad, by_city, cur_key = promote(glue_creds, raw_key)
    print(f"  glue-etl read {total} rows: {good} kept, rejected (no amount): {', '.join(bad)}, cancelled skipped")
    for city, v in sorted(by_city.items(), key=lambda kv: -kv[1]["revenue"]):
        print(f"    {city:<10} {v['orders']} order{'s' if v['orders'] > 1 else ' '}  Rs {v['revenue']:>9,.2f}")
    print(f"  curated  s3://{bucket('curated')}/{cur_key}")
    return by_city

πŸ“„ charminar-bootstrap/audit.py

"""audit.py - inventory by tag and the missing-tags check (what a nightly governance job runs)."""
from collections import Counter

import config as C


def inventory():
    api = C.client("resourcegroupstaggingapi")
    res = []
    for page in api.get_paginator("get_resources").paginate(
            TagFilters=[{"Key": "project", "Values": [C.PROJECT]}, {"Key": "env", "Values": [C.ENV]}]):
        res += page["ResourceTagMappingList"]
    return res


def report():
    res = inventory()
    kinds = Counter(r["ResourceARN"].split(":")[2] for r in res)
    print(f"  {len(res)} resources tagged project={C.PROJECT}, env={C.ENV}: "
          + ", ".join(f"{k} {v}" for k, v in sorted(kinds.items())))
    missing = 0
    for r in res:
        keys = {t["Key"] for t in r["Tags"]}
        gap = [k for k in C.REQUIRED_TAGS if k not in keys]
        if gap:
            missing += 1
            print(f"  missing {gap}: {r['ResourceARN']}")
    print(f"  required tags present on all: {'yes' if not missing else 'no'}")
    iam = C.client("iam")
    roles = [r["RoleName"] for r in iam.list_roles()["Roles"] if r["RoleName"].startswith(f"{C.PROJECT}-{C.ENV}-")]
    print(f"  IAM roles (global, listed by IAM): {', '.join(sorted(roles))}")

πŸ“„ charminar-bootstrap/teardown.py

"""teardown.py - remove the dev landing zone (empty buckets first). Needs --yes."""
import sys

from botocore.exceptions import ClientError

import config as C
from iam_roles import ROLES
from naming import account_id, bucket, name


def empty(s3, b):
    for page in s3.get_paginator("list_object_versions").paginate(Bucket=b):
        for v in page.get("Versions", []) + page.get("DeleteMarkers", []):
            s3.delete_object(Bucket=b, Key=v["Key"], VersionId=v["VersionId"])


def main():
    if "--yes" not in sys.argv or C.ENV == "prod":
        sys.exit("refusing: pass --yes, and never on prod")
    ct = C.client("cloudtrail")
    ct.delete_trail(Name=name("trail"))
    s3 = C.client("s3")
    for zone in C.ZONES:
        try:
            empty(s3, bucket(zone))
            s3.delete_bucket(Bucket=bucket(zone))
        except ClientError as e:
            print("  skip", bucket(zone), e.response["Error"]["Code"])
    iam = C.client("iam")
    for short in ROLES:
        role = name(short)
        iam.delete_role_policy(RoleName=role, PolicyName=f"{role}-least-privilege")
        iam.delete_role(RoleName=role)
    C.client("budgets", region=C.BILLING_REGION).delete_budget(AccountId=account_id(), BudgetName=name("monthly-budget"))
    C.client("cloudwatch", region=C.BILLING_REGION).delete_alarms(AlarmNames=[name("bill-over", f"{C.BILLING_ALARM_USD}usd")])
    C.client("sns", region=C.BILLING_REGION).delete_topic(
        TopicArn=f"arn:aws:sns:{C.BILLING_REGION}:{account_id()}:{name('alerts')}")
    print(f"  removed {len(C.ZONES)} buckets, {len(ROLES)} roles, trail, budget, alarm, topic")


if __name__ == "__main__":
    main()

πŸ“„ charminar-bootstrap/run_pipeline.py

"""run_pipeline.py - bootstrap the Charminar Cart dev data platform end to end, then smoke-test it."""
import config as C
import audit
import guardrails
import iam_roles
import network
import s3_zones
import smoke_test
from naming import account_id


def main():
    me = C.client("sts").get_caller_identity()
    print(f"== 0. who am I: account {me['Account']}, region {C.AWS_REGION}, env {C.ENV} ==")
    print("== 1. S3 lake zones ==")
    s3_zones.build_all()
    print("  raw:", s3_zones.describe("raw"))
    print("== 2. IAM roles (least privilege) ==")
    iam_roles.build_all()
    print("== 3. network ==")
    network.build()
    print("== 4. guardrails: budget, billing alarm, CloudTrail ==")
    guardrails.build()
    print("== 5. smoke test with the roles ==")
    smoke_test.run()
    print("== 6. audit by tags ==")
    audit.report()
    print(f"== done: dev platform ready in account {account_id()} ==")


if __name__ == "__main__":
    main()
python3 -m venv .venv
source .venv/bin/activate          # Windows (Git Bash): source .venv/Scripts/activate
pip install -q -r requirements.txt
moto_server -p 8430 > moto.log 2>&1 &
echo $! > moto.pid
sleep 3
export AWS_ENDPOINT_URL=http://127.0.0.1:8430
export AWS_ACCESS_KEY_ID=testing AWS_SECRET_ACCESS_KEY=testing
export AWS_DEFAULT_REGION=ap-south-1
python run_pipeline.py

Output

== 0. who am I: account 123456789012, region ap-south-1, env dev ==
== 1. S3 lake zones ==
  created s3://charminar-cart-dev-raw-123456789012                  versioned, IA after 30 d
  created s3://charminar-cart-dev-staged-123456789012               expire 7 d
  created s3://charminar-cart-dev-curated-123456789012              versioned
  created s3://charminar-cart-dev-athena-results-123456789012       expire 7 d
  created s3://charminar-cart-dev-logs-123456789012                 expire 90 d
  raw: {'encryption': 'AES256', 'public_blocked': True, 'versioning': 'Enabled'}
== 2. IAM roles (least privilege) ==
  created arn:aws:iam::123456789012:role/charminar-cart-dev-glue-etl  (4 statements, trusted by glue.amazonaws.com)
  created arn:aws:iam::123456789012:role/charminar-cart-dev-lambda-ingest  (2 statements, trusted by lambda.amazonaws.com)
== 3. network ==
  VPC 172.31.0.0/16 in ap-south-1: 3 subnets in ap-south-1a, ap-south-1b, ap-south-1c
  created gateway endpoint com.amazonaws.ap-south-1.s3
== 4. guardrails: budget, billing alarm, CloudTrail ==
  topic    charminar-cart-dev-alerts -> oncall@charminarcart.example
  created budget charminar-cart-dev-monthly-budget: 150 USD / month (80 % actual, 100 % forecast)
  alarm    charminar-cart-dev-bill-over-120usd
  created trail charminar-cart-dev-trail: multi-region, logging=True
== 5. smoke test with the roles ==
  lambda-ingest wrote s3://charminar-cart-dev-raw-123456789012/orders/ingest_date=2026-10-14/orders.csv
  glue-etl read 8 rows: 6 kept, rejected (no amount): CC-5005, cancelled skipped
    Hyderabad  2 orders  Rs  3,749.50
    Bengaluru  1 order   Rs  3,200.00
    Warangal   2 orders  Rs  1,149.00
    Nellore    1 order   Rs    899.00
  curated  s3://charminar-cart-dev-curated-123456789012/city_sales/order_date=2026-10-14/summary.json
== 6. audit by tags ==
  5 resources tagged project=charminar-cart, env=dev: s3 5
  required tags present on all: yes
  IAM roles (global, listed by IAM): charminar-cart-dev-glue-etl, charminar-cart-dev-lambda-ingest
== done: dev platform ready in account 123456789012 ==
python run_pipeline.py > rerun.log
head -4 rerun.log

Output

== 0. who am I: account 123456789012, region ap-south-1, env dev ==
== 1. S3 lake zones ==
  exists  s3://charminar-cart-dev-raw-123456789012                  versioned, IA after 30 d
  exists  s3://charminar-cart-dev-staged-123456789012               expire 7 d
python teardown.py --yes

Output

  removed 5 buckets, 2 roles, trail, budget, alarm, topic
kill $(cat moto.pid)
deactivate

Related AWS documentation and announcements (found by web search in October 2026, titles and links only, pages not re-read line by line): AWS Free Tier now offers $200 in credits and 6-month free plan, Now open: the 30th AWS Region, Asia Pacific (Hyderabad), AWS Budgets pricing, Establishing your cloud foundation on AWS: security assurance, re:Post: does a billing alarm cost money.