0%
AWS Lambda and Serverless: A Beginner's Guide

AWS Lambda and Serverless: A Beginner's Guide

Learn the concept of serverless and how to use AWS Lambda.

I

InSkillCoach

· min

AWS Lambda and Serverless: A Beginner’s Guide

Learn the concept of serverless and how to use AWS Lambda.

1. What Is Serverless?

Simple Definition

  • Serverless = No servers to manage
  • Benefits:
    • No infrastructure management
    • Pay-per-use pricing
    • Automatic scaling

Comparison with EC2

# Example of EC2 vs. Lambda costs
def compare_costs():
    # EC2: Pay per hour
    ec2_cost = {
        't2.micro': 0.0116,  # per hour
        't2.small': 0.023,   # per hour
        't2.medium': 0.0464  # per hour
    }
    
    # Lambda: Pay per request
    lambda_cost = {
        'requests': 0.0000002,  # per request
        'duration': 0.00001667  # per 100ms
    }
    
    return {
        'ec2': ec2_cost,
        'lambda': lambda_cost
    }

2. AWS Lambda in Practice

Creating a Simple Function

# Example of a Lambda function
def lambda_handler(event, context):
    # Simple function that returns a message
    return {
        'statusCode': 200,
        'body': 'Bonjour depuis Lambda !'
    }

Function Configuration

# Example of Lambda configuration
def setup_lambda():
    lambda_client = boto3.client('lambda')
    
    # Creating a function
    function = lambda_client.create_function(
        FunctionName='MaFonction',
        Runtime='python3.9',
        Handler='index.lambda_handler',
        Code={
            'ZipFile': open('mon-code.zip', 'rb').read()
        },
        Role='arn:aws:iam::account:role/lambda-role',
        Timeout=30,
        MemorySize=128
    )
    
    return function['FunctionArn']

3. Integration with Other Services

S3 Trigger

# Example of an S3 trigger
def s3_trigger_handler(event, context):
    # Processing a file uploaded to S3
    for record in event['Records']:
        bucket = record['s3']['bucket']['name']
        key = record['s3']['object']['key']
        
        # Read the file
        s3 = boto3.client('s3')
        response = s3.get_object(Bucket=bucket, Key=key)
        content = response['Body'].read().decode('utf-8')
        
        # Process the content
        return {
            'statusCode': 200,
            'body': f'Fichier traité : {key}'
        }

API Gateway

# Example of an API Gateway integration
def api_handler(event, context):
    # Handling an HTTP request
    http_method = event['httpMethod']
    
    if http_method == 'GET':
        return {
            'statusCode': 200,
            'body': 'GET request réussie'
        }
    elif http_method == 'POST':
        body = json.loads(event['body'])
        return {
            'statusCode': 200,
            'body': f'Données reçues : {body}'
        }

4. Best Practices

Dependency Management

# Example of dependency management
def create_lambda_package():
    # Create a virtual environment
    os.system('python -m venv venv')
    
    # Install dependencies
    os.system('pip install -r requirements.txt -t ./package')
    
    # Create the ZIP
    shutil.make_archive('lambda-package', 'zip', './package')
    
    return 'lambda-package.zip'

Memory Configuration

# Example of memory optimization
def optimize_memory():
    lambda_client = boto3.client('lambda')
    
    # Updating the configuration
    lambda_client.update_function_configuration(
        FunctionName='MaFonction',
        MemorySize=256,  # Increase memory
        Timeout=60,      # Increase timeout
        Environment={
            'Variables': {
                'ENV': 'production',
                'DEBUG': 'false'
            }
        }
    )

5. Monitoring and Logs

CloudWatch Logs

# Example of logging
def lambda_with_logging(event, context):
    # Simple logging
    print('Démarrage de la fonction')
    
    try:
        # Function code
        result = process_data(event)
        
        print('Traitement réussi')
        return result
    except Exception as e:
        print(f'Erreur : {str(e)}')
        raise

Metrics

# Example of custom metrics
def custom_metrics():
    cloudwatch = boto3.client('cloudwatch')
    
    # Send a metric
    cloudwatch.put_metric_data(
        Namespace='MonApplication',
        MetricData=[
            {
                'MetricName': 'TempsExecution',
                'Value': 1.5,
                'Unit': 'Seconds',
                'Dimensions': [
                    {
                        'Name': 'Fonction',
                        'Value': 'MaFonction'
                    }
                ]
            }
        ]
    )

6. Security

Environment Variables

# Example of secrets management
def secure_lambda():
    lambda_client = boto3.client('lambda')
    
    # Configuring environment variables
    lambda_client.update_function_configuration(
        FunctionName='MaFonction',
        Environment={
            'Variables': {
                'API_KEY': 'mon-api-key',
                'DB_PASSWORD': 'mon-mot-de-passe'
            }
        }
    )

IAM Roles

# Example of IAM configuration
def setup_iam_role():
    iam = boto3.client('iam')
    
    # Creating the role
    role = iam.create_role(
        RoleName='lambda-role',
        AssumeRolePolicyDocument=json.dumps({
            'Version': '2012-10-17',
            'Statement': [
                {
                    'Effect': 'Allow',
                    'Principal': {
                        'Service': 'lambda.amazonaws.com'
                    },
                    'Action': 'sts:AssumeRole'
                }
            ]
        })
    )
    
    return role['Role']['Arn']

Conclusion

Key takeaways:

  • Serverless = no infrastructure management
  • Lambda = functions executed on demand
  • You pay only for what you use
  • Easy integration with other services
  • Automatic scaling

Recommendations:

  • Start with simple functions
  • Monitor costs
  • Use logs for debugging
  • Secure your functions
  • Optimize performance
InSkillCoach

About InSkillCoach

Training and technology expert

Coach specializing in advanced technologies and AI, backed by GNeurone Inc.

Certifications:

  • AWS Certified Solutions Architect – Professional
  • Google Cloud certifications
  • Microsoft Certified: DevOps Engineer Expert
  • Certified Kubernetes Administrator (CKA)
  • CompTIA Security+
901
183

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!