DEV Community

Sameer Imtiaz
Sameer Imtiaz

Posted on

Kick Procrastination to the Curb: Master Serverless Computing with AWS Lambda Now

Discover how to implement a practical EC2 auto-tagging solution using AWS Lambda while grasping essential serverless principles.

Diving into Serverless Computing

What’s in store for this article?

I’ll walk you through the core concepts of AWS Lambda and demonstrate its application with a hands-on, real-world project.

Understanding AWS Lambda Functions

AWS Lambda is a compute service offered by Amazon Web Services that executes your code without requiring you to manage the underlying infrastructure.

You might wonder why everyone raves about Lambda’s “no infrastructure management” benefit. What’s so tough about handling servers anyway?

Managing infrastructure, like an EC2 instance, comes with its own set of hurdles:

  • Keeping the operating system and software updated, while addressing new vulnerabilities through regular patching.
  • Securing the EC2 instance by closing unnecessary ports, managing SSH keys, and ensuring robust access controls.
  • Setting up high availability, autoscaling, SSL certificates, and covering costs for components like Application Load Balancers, NAT gateways, and public IPs.
  • Hiring skilled personnel to manage all this, as automation alone (even AI) isn’t quite there yet. Opting for a managed service like AWS Lambda can save you from these complexities compared to provisioning EC2 servers.

Key Features of AWS Lambda

  • Write code in your preferred programming language.
  • Operates on an event-driven model, executing code in response to specific triggers.
  • Integrates effortlessly with various AWS services and third-party SDKs.
  • Automatically scales based on event volume, offering built-in fault tolerance and high availability.
  • Provides granular access control via AWS Identity and Access Management (IAM).
  • Charges only for the compute time your code consumes, billed per millisecond.

When Should You Use AWS Lambda (And When Shouldn’t You)?

AWS Lambda shines in these scenarios:

  • Event-driven tasks: Perfect for executing code in response to events like file uploads to S3, DynamoDB updates, HTTP requests through API Gateway, or messages from SQS.
  • Short-lived, stateless functions: With a 15-minute execution limit, Lambda is ideal for processing discrete tasks.
  • Microservices architecture: Well-suited for building individual microservices in a distributed system.
  • Integration with AWS ecosystem: Seamlessly works with services like S3, DynamoDB, and SNS to create serverless workflows.

However, Lambda isn’t the best fit for:

  • Long-running processes: Its 15-minute runtime cap makes it unsuitable for extended tasks.
  • High CPU/memory demands: Applications needing significant resources are better served by EC2 or container services like ECS/EKS.
  • Complex dependencies: If your app requires intricate dependencies or custom runtimes, Lambda may not be ideal.
  • Predictable, steady workloads: Provisioned EC2 instances are often more cost-effective for consistent traffic.
  • Legacy systems: Reworking legacy applications for serverless can be impractical due to extensive refactoring.

Events That Trigger Lambda Functions

Lambda functions can be invoked in three ways:

  1. Synchronous Invocation

    The function runs and returns a response immediately. There are no automatic retries. Services like Amazon API Gateway, Cognito, CloudFormation, and Alexa use this method.

  2. Asynchronous Invocation

    Events are queued, and the requester doesn’t wait for completion. Responses can be sent to other services via destinations. This is ideal when immediate feedback isn’t needed. Services like Amazon SNS, S3, and EventBridge support this.

  3. Polling Invocation

    Lambda actively polls streaming or queue-based services (e.g., Kinesis, SQS, DynamoDB Streams) to retrieve events and trigger functions.

With the fundamentals covered, let’s roll up our sleeves and build something practical with Lambda.

Hands-On AWS Lambda Project: Auto-Tagging EC2 Instances

Scenario: Imagine you’re an AWS account admin managing an environment where multiple users create EC2 instances. You want to automatically tag each instance with the creator’s identity for better tracking.

Here’s the plan:

  • Use AWS EventBridge to trigger a Lambda function whenever an EC2 instance is launched.
  • Leverage AWS CloudTrail to log API calls, filter for EC2 creation events, and pass them to EventBridge.
  • Write a Lambda function in Python to extract the instance ID and owner details, then tag the instance with the owner’s name.

Let’s get started!

Step 1: Set Up AWS CloudTrail

  • Navigate to the AWS Console and access the CloudTrail service.
  • Create a new trail and configure a new S3 bucket to store the logs.
  • Enable CloudWatch Logs and create a dedicated log group for this trail.
  • Select “Management Events” as the event type and enable both “Read” and “Write” API activities.
  • Review your settings and create the trail.

Step 2: Create the Lambda Function

  • Set up a new Lambda function using the Python runtime.

Step 3: Configure Amazon EventBridge

  • Create an EventBridge rule with the event source set to “AWS events.”
  • Define the event pattern:
    • Event source: AWS services
    • Service: EC2
    • Event type: AWS API Call via CloudTrail
    • Specific operation: RunInstances (the event triggered when an EC2 instance is launched)
  • Set the target as the Lambda function you created (e.g., ec2-tag-lambda).

Step 4: Grant Permissions to Lambda

  • Lambda needs permission to tag EC2 instances.
  • Attach a policy to the Lambda execution role by adding the following statement:
{
  "Sid": "ec2tag",
  "Effect": "Allow",
  "Action": "ec2:CreateTags",
  "Resource": "*"
}
Enter fullscreen mode Exit fullscreen mode

If you’re new to AWS, you can attach an existing managed policy for simplicity.

Step 5: Write the Python Code

The Lambda function will use the boto3 Python library to tag EC2 instances with the creator’s username. Here’s the code:

import boto3

def lambda_handler(event, context):
    # Extract the owner's username from the event
    try:
        owner = event["detail"]["userIdentity"]["userName"]  # For IAM users
    except Exception:
        owner = event["detail"]["userIdentity"]["arn"].split(":")[-1]  # For root users

    # Extract the EC2 instance ID
    instance_id = event["detail"]["responseElements"]["instancesSet"]["items"][0]["instanceId"]

    # Initialize EC2 client
    ec2 = boto3.client("ec2")

    # Tag the EC2 instance
    ec2.create_tags(
        Resources=[instance_id],
        Tags=[{"Key": "OWNER", "Value": owner}]
    )
Enter fullscreen mode Exit fullscreen mode

Step 6: Deploy and Test

  • Deploy the Lambda function.
  • Launch an EC2 instance to test the setup.
  • Verify that the Lambda function tags the instance with the owner’s name (e.g., root or IAM username).

Test Result: When I launched an EC2 instance as the root user, the Lambda function successfully tagged it with the owner’s name.

Top comments (0)