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

  1. Creates a DynamoDB table named Users with UserID as the primary key.

    • dynamodb.create_table(..., TableName='Users', KeySchema=[{'AttributeName': 'UserID', 'KeyType': 'HASH'}])
  2. Defines UserID as a string-based primary key.

    • AttributeDefinitions=[{'AttributeName': 'UserID', 'AttributeType': 'S'}]
  3. Sets read and write throughput to 1 unit each.

    • ProvisionedThroughput={'ReadCapacityUnits': 1, 'WriteCapacityUnits': 1}
  4. 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

  1. Gets a reference to the Users table.

    • table = dynamodb.Table('Users')
  2. Inserts a UserID with a name value.

    • table.put_item(Item={'UserID': '123', 'Name': 'Alice'})
  3. Fetches the inserted record using the UserID key.

    • response = table.get_item(Key={'UserID': '123'})
  4. 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

  1. The function starts by importing json for data formatting.

    • import json
  2. Defines the AWS Lambda function that will be triggered.

    • def lambda_handler(event, context):
  3. Returns a 200 HTTP status with a response message.

    • return {'statusCode': 200, 'body': json.dumps('Hello from Lambda!')}
  4. 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

  1. Connects AWS Lambda to DynamoDB using boto3.

    • dynamodb = boto3.resource('dynamodb')
  2. Fetches data from the Users table based on UserID.

    • user = table.get_item(Key={'UserID': event['UserID']})
  3. Retrieves the user's details if available.

    • return {'statusCode': 200, 'body': user.get('Item', 'User not found')}
  4. 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

  1. The step function starts execution at FirstStep.

    • "StartAt": "FirstStep"
  2. FirstStep passes execution to the next step.

    • "Type": "Pass", "Next": "SecondStep"
  3. SecondStep marks execution as successful.

    • "Type": "Succeed"
  4. 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

  1. Step Functions invoke a Lambda function.

    • "Type": "Task", "Resource": "arn:aws:lambda:us-east-1:123456789012:function:MyLambda"
  2. The process starts at CallLambda.

    • "StartAt": "CallLambda"
  3. Executes the Lambda function and ends the workflow.

    • "End": true
  4. 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

  1. Uses AWS CLI to create a CodeCommit repository.

    • aws codecommit create-repository --repository-name MyRepo
  2. Adds a description for clarity.

    • --repository-description "My first repo"
  3. The repository is now available in AWS CodeCommit.

    • "repositoryName": "MyRepo"
  4. 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

  1. Clones the AWS CodeCommit repository locally.

  2. Uses HTTPS authentication for security.

  3. The repo is now available on the local machine.

    • MyRepo
  4. 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

  1. Creates a CloudWatch log group for logs.

    • aws logs create-log-group --log-group-name MyLogGroup
  2. Groups multiple logs together.

    • "logGroupName": "MyLogGroup"
  3. Used to store logs from Lambda, EC2, etc.

    • CloudWatch
  4. 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

  1. Creates an alarm for CPU usage.

    • --alarm-name CPUHigh
  2. Monitors CPU utilization exceeding 80%.

    • --threshold 80
  3. Can trigger alerts or auto-scaling.

    • CloudWatch
  4. Helps in AWS infrastructure monitoring.

    • put-metric-alarm