AWS. Lessson 1.
Here’s a structured AWS tutorial covering DynamoDB, Lambda, Step Functions, CodeCommit, CloudWatch, and Cognito, with two code examples per topic.
1. DynamoDB
Example 1: Create a Table and Insert an Item
import boto3
# Create a DynamoDB resource
dynamodb = boto3.resource('dynamodb')
# Create a table
table = dynamodb.create_table(
TableName='Users',
KeySchema=[{'AttributeName': 'UserID', 'KeyType': 'HASH'}],
AttributeDefinitions=[{'AttributeName': 'UserID', 'AttributeType': 'S'}],
ProvisionedThroughput={'ReadCapacityUnits': 1, 'WriteCapacityUnits': 1}
)
print("Table created successfully")
Explanation
Creates a DynamoDB table named Users with UserID as the primary key.
dynamodb.create_table(..., TableName='Users', KeySchema=[{'AttributeName': 'UserID', 'KeyType': 'HASH'}])
Defines UserID as a string-based primary key.
AttributeDefinitions=[{'AttributeName': 'UserID', 'AttributeType': 'S'}]
Sets read and write throughput to 1 unit each.
ProvisionedThroughput={'ReadCapacityUnits': 1, 'WriteCapacityUnits': 1}
Prints confirmation after the table is created.
print("Table created successfully")
Example 2: Insert and Fetch Data
table = dynamodb.Table('Users')
# Insert an item
table.put_item(Item={'UserID': '123', 'Name': 'Alice'})
# Fetch an item
response = table.get_item(Key={'UserID': '123'})
print(response['Item'])
Explanation
Gets a reference to the Users table.
table = dynamodb.Table('Users')
Inserts a UserID with a name value.
table.put_item(Item={'UserID': '123', 'Name': 'Alice'})
Fetches the inserted record using the UserID key.
response = table.get_item(Key={'UserID': '123'})
Prints the retrieved user data.
print(response['Item'])
2. Lambda
Example 1: Basic Lambda Function
import json
def lambda_handler(event, context):
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
Explanation
The function starts by importing json for data formatting.
import json
Defines the AWS Lambda function that will be triggered.
def lambda_handler(event, context):
Returns a 200 HTTP status with a response message.
return {'statusCode': 200, 'body': json.dumps('Hello from Lambda!')}
AWS executes this function when triggered by an event.
lambda_handler(event, context)
Example 2: Read from DynamoDB in Lambda
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Users')
def lambda_handler(event, context):
user = table.get_item(Key={'UserID': event['UserID']})
return {'statusCode': 200, 'body': user.get('Item', 'User not found')}
Explanation
Connects AWS Lambda to DynamoDB using boto3.
dynamodb = boto3.resource('dynamodb')
Fetches data from the Users table based on UserID.
user = table.get_item(Key={'UserID': event['UserID']})
Retrieves the user's details if available.
return {'statusCode': 200, 'body': user.get('Item', 'User not found')}
Can be triggered via API Gateway to return user data.
lambda_handler(event, context)
3. Step Functions
Example 1: Define a Simple Step Function
{
"StartAt": "FirstStep",
"States": {
"FirstStep": {
"Type": "Pass",
"Next": "SecondStep"
},
"SecondStep": {
"Type": "Succeed"
}
}
}
Explanation
The step function starts execution at FirstStep.
"StartAt": "FirstStep"
FirstStep passes execution to the next step.
"Type": "Pass", "Next": "SecondStep"
SecondStep marks execution as successful.
"Type": "Succeed"
The process is sequential and automatic.
"Next": "SecondStep"
Example 2: Step Function with Lambda Invocation
{
"StartAt": "CallLambda",
"States": {
"CallLambda": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:MyLambda",
"End": true
}
}
}
Explanation
Step Functions invoke a Lambda function.
"Type": "Task", "Resource": "arn:aws:lambda:us-east-1:123456789012:function:MyLambda"
The process starts at CallLambda.
"StartAt": "CallLambda"
Executes the Lambda function and ends the workflow.
"End": true
Can be used for serverless orchestration.
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:MyLambda"
4. CodeCommit
Example 1: Create a Repository
aws codecommit create-repository --repository-name MyRepo --repository-description "My first repo"
Explanation
Uses AWS CLI to create a CodeCommit repository.
aws codecommit create-repository --repository-name MyRepo
Adds a description for clarity.
--repository-description "My first repo"
The repository is now available in AWS CodeCommit.
"repositoryName": "MyRepo"
Used for Git-based version control.
CodeCommit
Example 2: Clone a CodeCommit Repository
git clone https://git-codecommit.us-east-1.amazonaws.com/v1/repos/MyRepo
Explanation
Clones the AWS CodeCommit repository locally.
Uses HTTPS authentication for security.
The repo is now available on the local machine.
MyRepo
Supports Git workflows like push and pull.
git clone
5. CloudWatch
Example 1: Create a Log Group
aws logs create-log-group --log-group-name MyLogGroup
Explanation
Creates a CloudWatch log group for logs.
aws logs create-log-group --log-group-name MyLogGroup
Groups multiple logs together.
"logGroupName": "MyLogGroup"
Used to store logs from Lambda, EC2, etc.
CloudWatch
Helps in monitoring AWS applications.
CloudWatch
Example 2: Create a Metric Alarm
aws cloudwatch put-metric-alarm --alarm-name CPUHigh --metric-name CPUUtilization --threshold 80
Explanation
Creates an alarm for CPU usage.
--alarm-name CPUHigh
Monitors CPU utilization exceeding 80%.
--threshold 80
Can trigger alerts or auto-scaling.
CloudWatch
Helps in AWS infrastructure monitoring.
put-metric-alarm