Aim: By the end of this page you can explain what the AWS cloud is and use it safely from Python: pick a region, talk to AWS with the console, the CLI and boto3, know who secures what, keep the bill under control, and read ARNs and tags, the base for every other AWS page.
Description: Before S3, Glue or Athena, a data engineer needs the ground rules of AWS. On this page you compare on-premises servers with the cloud, learn regions and availability zones, open the three doors into AWS (console, AWS CLI and boto3), understand the shared responsibility model and pay-as-you-go pricing, and read ARNs and tags, using RegularMart’s account 123456789012 in ap-south-1 and code you can run yourself.
aws configure, sessions, the credential chain.Before you start: basic Python (variables, loops, functions, dictionaries), a terminal, and an AWS account (Free Tier) for the hands-on part.
Install the AWS library for Python and the AWS CLI, then tell them your keys and region once:
pip install boto3 awscli aws configure # AWS Access Key ID : AKIA...EXAMPLE # AWS Secret Access Key : **************** # Default region name : ap-south-1 # Default output format : json
🔑 Never paste real keys into code, chats or GitHub. aws configure asks for them once and stores them in ~/.aws/credentials. Keys on this page are fake placeholders like AKIA...EXAMPLE.
💸 AWS Free Tier covers most of these labs. When you finish, delete what you made: aws s3 rb s3://regularmart-raw --force (repeat for each regularmart-… bucket), aws sns delete-topic --topic-arn <arn>, aws budgets delete-budget --account-id <id> --budget-name rm-monthly
Create the resources (run once · python setup_regularmart.py):
# setup_regularmart.py · creates the RegularMart buckets (region ap-south-1)
import boto3
REGION = "ap-south-1"
s3 = boto3.client("s3", region_name=REGION)
for name in ["regularmart-raw", "regularmart-processed",
"regularmart-curated", "regularmart-athena-results"]:
s3.create_bucket(Bucket=name,
CreateBucketConfiguration={"LocationConstraint": REGION})
print("created bucket", name)Bucket names are global across all AWS accounts. If “regularmart-raw” is taken, add your initials (for example regularmart-raw-sd) and use that name everywhere. Real output of this script: created bucket regularmart-raw · created bucket regularmart-processed · created bucket regularmart-curated · created bucket regularmart-athena-results
Save these files next to your scripts. orders.csv is the same 5 RegularMart orders as the whole series. usage_example.csv uses round practice prices, NOT real AWS prices (use the AWS Pricing Calculator for real numbers).
orders.csv
order_id,customer_id,product,amount,order_date 5001,1,Mobile,15000,2024-01-05 5002,2,Laptop,55000,2024-01-07 5003,1,Headphones,2000,2024-01-09 5004,4,Watch,3500,2024-01-10 5005,6,Shoes,2500,2024-01-11
usage_example.csv
service,meter,quantity,price_per_unit_usd S3,GB-month stored,50,0.025 S3,1000 GET requests,200,0.0004 Glue,DPU-hour,10,0.44 Athena,TB scanned,0.2,5.0 Lambda,1M requests,3,0.2
student_policy.json
{"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["s3:ListBucket", "s3:GetObject", "s3:PutObject"],
"Resource": ["arn:aws:s3:::regularmart-*",
"arn:aws:s3:::regularmart-*/*"]
}]}usage_example.csv 5 rows
| service | meter | quantity | price_per_unit_usd |
|---|---|---|---|
| S3 | GB-month stored | 50 | 0.025 |
| S3 | 1000 GET requests | 200 | 0.0004 |
| Glue | DPU-hour | 10 | 0.44 |
| Athena | TB scanned | 0.2 | 5.0 |
| Lambda | 1M requests | 3 | 0.2 |
Task 1 🪪 First day at RegularMart. Before you touch anything, prove which AWS account your terminal is using.
💭 Hint: aws sts get-caller-identity answers “who am I?”. --query picks one field; --output text removes the quotes.
aws sts get-caller-identity --query Account aws sts get-caller-identity --query Account --output text aws sts get-caller-identity --query Arn --output text
✅ real output · AWS CLI run against moto (no real AWS)
"123456789012" 123456789012 arn:aws:sts::123456789012:user/moto
Task 2 🏙️ Your lead asks: “Which AWS regions are in India, and which availability zones does Mumbai (ap-south-1) have?”
💭 Hint: aws ec2 describe-availability-zones --region … --query "AvailabilityZones[].ZoneName"; boto3 ec2.describe_regions() lists regions.
aws ec2 describe-availability-zones --region ap-south-1 \
--query "AvailabilityZones[].ZoneName"import boto3
ec2 = boto3.client("ec2", region_name="ap-south-1")
names = [r["RegionName"] for r in ec2.describe_regions()["Regions"]]
print("India regions:", [n for n in names if n.startswith("ap-south-")])
for z in ec2.describe_availability_zones()["AvailabilityZones"]:
print(z["ZoneName"], "->", z["ZoneId"], z["State"])✅ real output · AWS CLI run against moto (no real AWS)
[
"ap-south-1a",
"ap-south-1b",
"ap-south-1c"
]✅ real output · run with moto (a local fake AWS, no real account)
India regions: ['ap-south-1', 'ap-south-2'] ap-south-1a -> aps1-az1 available ap-south-1b -> aps1-az3 available ap-south-1c -> aps1-az2 available
Task 3 🔑 Write the first boto3 script of the project: a session for ap-south-1 that prints the account and the buckets, and shows WHERE boto3 found the keys, without any key in the code.
💭 Hint: boto3.Session(region_name=...) → .client("sts") / .client("s3"); session.get_credentials().method tells the source.
import boto3
session = boto3.Session(region_name="ap-south-1")
sts = session.client("sts")
print(sts.get_caller_identity()["Account"])
s3 = session.client("s3")
for b in s3.list_buckets()["Buckets"]:
print(b["Name"])
creds = session.get_credentials()
print("keys found via:", creds.method) # env vars here; "iam-role" style on Glue / Lambda
print("client region:", s3.meta.region_name)✅ real output · run with moto (a local fake AWS, no real account)
123456789012 regularmart-raw regularmart-processed regularmart-curated regularmart-athena-results keys found via: env client region: ap-south-1
Task 4 🔍 Suresh created rm-orders-queue in Mumbai, but his script says it “does not exist”. His script uses us-east-1. Show the problem and the fix.
💭 Hint: Create the queue with an ap-south-1 client, then list queues with a us-east-1 client and with an ap-south-1 client.
import boto3
mumbai = boto3.client("sqs", region_name="ap-south-1")
mumbai.create_queue(QueueName="rm-orders-queue")
virginia = boto3.client("sqs", region_name="us-east-1")
print("us-east-1 :", virginia.list_queues().get("QueueUrls", []))
print("ap-south-1 :", mumbai.list_queues().get("QueueUrls", []))✅ real output · run with moto (a local fake AWS, no real account)
us-east-1 : [] ap-south-1 : ['https://sqs.ap-south-1.amazonaws.com/123456789012/rm-orders-queue']
Task 5 🛡️ Security is YOUR side of the shared responsibility model. Stop using the root user: create a data-engineers group that may only read and write regularmart-* buckets, and add Suresh to it.
💭 Hint: iam.create_group → put_group_policy with student_policy.json (Step 2) → create_user → add_user_to_group.
import boto3
iam = boto3.client("iam")
iam.create_group(GroupName="data-engineers")
iam.put_group_policy(GroupName="data-engineers", PolicyName="regularmart-buckets-only",
PolicyDocument=open("student_policy.json").read())
user = iam.create_user(UserName="suresh")["User"]
iam.add_user_to_group(GroupName="data-engineers", UserName="suresh")
print("user ARN :", user["Arn"])
print("groups :", [g["GroupName"] for g in iam.list_groups_for_user(UserName="suresh")["Groups"]])
print("policies :", iam.list_group_policies(GroupName="data-engineers")["PolicyNames"])✅ real output · run with moto (a local fake AWS, no real account)
user ARN : arn:aws:iam::123456789012:user/suresh groups : ['data-engineers'] policies : ['regularmart-buckets-only']
Task 6 🪪 The team keeps pasting ARNs with the wrong region. Create the alerts topic, the orders queue and the Glue job role, then split each ARN into its parts so everyone can read them.
💭 Hint: Every ARN is arn:partition:service:region:account:resource → arn.split(":", 5).
import boto3, json
topic = boto3.client("sns").create_topic(Name="rm-pipeline-alerts")["TopicArn"]
sqs = boto3.client("sqs")
q_url = sqs.create_queue(QueueName="rm-orders-queue")["QueueUrl"]
queue = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
trust = {"Version": "2012-10-17", "Statement": [{"Effect": "Allow",
"Principal": {"Service": "glue.amazonaws.com"}, "Action": "sts:AssumeRole"}]}
role = boto3.client("iam").create_role(RoleName="rm-glue-job-role",
AssumeRolePolicyDocument=json.dumps(trust))["Role"]["Arn"]
for arn in [topic, queue, role, "arn:aws:s3:::regularmart-raw"]:
_, part, service, region, account, res = arn.split(":", 5)
print(f"{service:4} | region={region or '-':10} | account={account or '-':12} | {res}")✅ real output · run with moto (a local fake AWS, no real account)
sns | region=ap-south-1 | account=123456789012 | rm-pipeline-alerts sqs | region=ap-south-1 | account=123456789012 | rm-orders-queue iam | region=- | account=123456789012 | role/rm-glue-job-role s3 | region=- | account=- | regularmart-raw
Task 7 🏷️ Finance wants the AWS bill split by project. Tag the raw bucket, the orders queue and the alerts topic with project=regularmart, env=dev, owner=suresh, then find every RegularMart resource with ONE call.
💭 Hint: Each service has its own tag call; the Resource Groups Tagging API (get_resources with TagFilters) searches across services.
import boto3
TAGS = {"project": "regularmart", "env": "dev", "owner": "suresh"}
boto3.client("s3").put_bucket_tagging(Bucket="regularmart-raw",
Tagging={"TagSet": [{"Key": k, "Value": v} for k, v in TAGS.items()]})
boto3.client("sqs").create_queue(QueueName="rm-orders-queue", tags=TAGS)
boto3.client("sns").create_topic(Name="rm-pipeline-alerts",
Tags=[{"Key": k, "Value": v} for k, v in TAGS.items()])
tagging = boto3.client("resourcegroupstaggingapi")
found = tagging.get_resources(TagFilters=[{"Key": "project", "Values": ["regularmart"]}])
for r in found["ResourceTagMappingList"]:
print(r["ResourceARN"])✅ real output · run with moto (a local fake AWS, no real account)
arn:aws:s3:::regularmart-raw arn:aws:sqs:ap-south-1:123456789012:rm-orders-queue arn:aws:sns:ap-south-1:123456789012:rm-pipeline-alerts
Task 8 💰 Before go-live, the manager asks: “Roughly what will one month cost, and which service costs the most?” Use the practice usage file (round example prices) and SQL.
💭 Hint: cost = quantity × price_per_unit; GROUP BY service; ORDER BY cost DESC. Real prices: the AWS Pricing Calculator.
SELECT service,
ROUND(SUM(quantity * price_per_unit_usd), 2) AS monthly_usd
FROM read_csv_auto('usage_example.csv')
GROUP BY service
ORDER BY monthly_usd DESC;SELECT ROUND(SUM(quantity * price_per_unit_usd), 2) AS total_usd
FROM read_csv_auto('usage_example.csv');✅ real output · duckdb on the same sample file (Athena-style SQL) · 4 rows
| service | monthly_usd |
|---|---|
| Glue | 4.4 |
| S3 | 1.33 |
| Athena | 1.0 |
| Lambda | 0.6 |
✅ real output · duckdb on the same sample file (Athena-style SQL) · 1 row
| total_usd |
|---|
| 7.33 |
Task 9 📧 You are learning on your own card. Create a 10 USD monthly cost budget that emails suresh@example.com when actual spend passes 80 %.
💭 Hint: budgets.create_budget(AccountId, Budget, NotificationsWithSubscribers=[...]); the Budgets API lives in us-east-1.
import boto3
budgets = boto3.client("budgets", region_name="us-east-1")
budgets.create_budget(AccountId="123456789012", Budget={
"BudgetName": "rm-monthly", "BudgetType": "COST", "TimeUnit": "MONTHLY",
"BudgetLimit": {"Amount": "10", "Unit": "USD"}},
NotificationsWithSubscribers=[{
"Notification": {"NotificationType": "ACTUAL", "ComparisonOperator": "GREATER_THAN",
"Threshold": 80, "ThresholdType": "PERCENTAGE"},
"Subscribers": [{"SubscriptionType": "EMAIL", "Address": "suresh@example.com"}]}])
b = budgets.describe_budget(AccountId="123456789012", BudgetName="rm-monthly")["Budget"]
print(b["BudgetName"])
print(b["BudgetLimit"]["Amount"], b["BudgetLimit"]["Unit"], "·", b["TimeUnit"])
n = budgets.describe_notifications_for_budget(AccountId="123456789012", BudgetName="rm-monthly")
print("alert at", n["Notifications"][0]["Threshold"], "% of actual spend")✅ real output · run with moto (a local fake AWS, no real account)
rm-monthly 10 USD · MONTHLY alert at 80 % of actual spend
Task 10 ⏰ Also add a CloudWatch billing alarm: when estimated charges go above 10 USD, notify an SNS topic. Remember: billing metrics live only in us-east-1.
💭 Hint: Create the topic in us-east-1, then put-metric-alarm on namespace AWS/Billing, metric EstimatedCharges, dimension Currency=USD. In a real account, first turn on “Receive Billing Alerts” in the Billing preferences.
aws sns create-topic --name rm-billing-alerts --region us-east-1
aws cloudwatch put-metric-alarm --region us-east-1 \
--alarm-name rm-bill-over-10-usd --namespace AWS/Billing \
--metric-name EstimatedCharges --dimensions Name=Currency,Value=USD \
--statistic Maximum --period 21600 --evaluation-periods 1 \
--threshold 10 --comparison-operator GreaterThanThreshold \
--alarm-actions arn:aws:sns:us-east-1:123456789012:rm-billing-alerts
aws cloudwatch describe-alarms --region us-east-1 \
--query "MetricAlarms[].[AlarmName,MetricName,Threshold,StateValue]" --output table✅ real output · AWS CLI run against moto (no real AWS)
{
"TopicArn": "arn:aws:sns:us-east-1:123456789012:rm-billing-alerts"
}
-----------------------------------------------------------
| DescribeAlarms |
+----------------------+--------------------+-------+-----+
| rm-bill-over-10-usd | EstimatedCharges | 10.0 | OK |
+----------------------+--------------------+-------+-----+aws ec2 describe-availability-zones --region ap-south-1 \
--query "AvailabilityZones[].ZoneName" --output text✅ real output · AWS CLI run against moto (no real AWS)
ap-south-1a ap-south-1b ap-south-1c
💡 Say this in the interview: “A region is a geographic area like Mumbai; an AZ is an isolated data centre group inside it. We spread across AZs for high availability and use other regions for disaster recovery.”
💡 Say this in the interview: “The cloud turns a big up-front CapEx into pay-as-you-go OpEx, scales up and down in minutes, and gives managed services so we spend time on data, not servers.”
{"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["s3:ListBucket", "s3:GetObject", "s3:PutObject"],
"Resource": ["arn:aws:s3:::regularmart-*",
"arn:aws:s3:::regularmart-*/*"]
}]}💡 Say this in the interview: “AWS secures the cloud itself; we secure what we put in it: our data, IAM permissions, encryption and configuration. With managed services like Glue, AWS takes more, but data and access stay with us.”
import boto3
creds = boto3.Session().get_credentials()
print("credentials came from:", creds.method) # 'env' here; 'iam-role' style providers on Lambda / Glue / EC2✅ real output · run with moto (a local fake AWS, no real account)
credentials came from: env
💡 Say this in the interview: “boto3 walks a credential chain: code, environment, config files, then the role of the service. In our pipelines every job has an IAM role, so there are no access keys anywhere in code.”
for arn in ["arn:aws:sns:ap-south-1:123456789012:rm-pipeline-alerts",
"arn:aws:s3:::regularmart-raw",
"arn:aws:iam::123456789012:role/rm-glue-job-role"]:
print(arn.split(":", 5)[2:])✅ real output · run with moto (a local fake AWS, no real account)
['sns', 'ap-south-1', '123456789012', 'rm-pipeline-alerts'] ['s3', '', '', 'regularmart-raw'] ['iam', '', '123456789012', 'role/rm-glue-job-role']
💡 Say this in the interview: “An ARN is the unique name of a resource: service, region, account, resource. S3 buckets are global, so their ARN has no region or account. We use ARNs in policies and targets, and tags to split cost by project.”
Your first task as the data engineer: one script that prints the account and region, the Mumbai AZs, tags all four regularmart-* buckets with project=regularmart, creates the rm-pipeline-alerts topic (tagged), creates a 10 USD monthly budget, and finally lists every resource tagged project=regularmart with its service and region read from the ARN.
💭 Hint: Reuse Tasks 2, 3, 6, 7 and 9. The tagging API returns ARNs; split them with arn.split(":", 5).
import boto3
s = boto3.Session(region_name="ap-south-1")
print("account:", s.client("sts").get_caller_identity()["Account"], "| region:", s.region_name)
print("AZs:", [z["ZoneName"] for z in s.client("ec2").describe_availability_zones()["AvailabilityZones"]])
TAGS = [{"Key": "project", "Value": "regularmart"}, {"Key": "env", "Value": "dev"}]
s3 = s.client("s3")
for b in s3.list_buckets()["Buckets"]:
s3.put_bucket_tagging(Bucket=b["Name"], Tagging={"TagSet": TAGS})
s.client("sns").create_topic(Name="rm-pipeline-alerts", Tags=TAGS)
s.client("budgets", region_name="us-east-1").create_budget(AccountId="123456789012", Budget={
"BudgetName": "rm-monthly", "BudgetType": "COST", "TimeUnit": "MONTHLY",
"BudgetLimit": {"Amount": "10", "Unit": "USD"}})
found = s.client("resourcegroupstaggingapi").get_resources(
TagFilters=[{"Key": "project", "Values": ["regularmart"]}])["ResourceTagMappingList"]
for r in found:
_, _, service, region, account, name = r["ResourceARN"].split(":", 5)
print(f"{service:3} {region or 'global':10} {name}")
print("budget:", s.client("budgets", region_name="us-east-1").describe_budgets(
AccountId="123456789012")["Budgets"][0]["BudgetName"])✅ real output · run with moto (a local fake AWS, no real account)
account: 123456789012 | region: ap-south-1 AZs: ['ap-south-1a', 'ap-south-1b', 'ap-south-1c'] s3 global regularmart-raw s3 global regularmart-processed s3 global regularmart-curated s3 global regularmart-athena-results sns ap-south-1 rm-pipeline-alerts budget: rm-monthly