AWS Lambda Inventory: How to List and Analyze Lambda Functions and CloudWatch Metrics with AWS SDK
Tags: python, aws, cloud, serverless
Published: 2023-12-18 15:39:47


**Introduction:**
AWS Lambda has revolutionized serverless computing, providing unparalleled scalability and flexibility. However, efficient management and monitoring of Lambda functions are paramount for optimizing performance. In this blog post, we'll explore a Python script leveraging Boto3 and CloudWatch to create a detailed inventory of Lambda functions, including their runtimes and invocation statistics over the last month.

**Prerequisites:**
1. AWS account with Lambda functions deployed.
2. Basic knowledge of AWS Lambda, CloudWatch, and Python.

**Creating a Lambda Inventory:**
The Python script utilizes Boto3, the AWS SDK for Python, to interact with AWS Lambda and CloudWatch. Let's break down the key components:

**Listing Lambda Functions:**
```python
lambda_client = boto3.client('lambda')

def list_lambda_functions():
    response = lambda_client.list_functions()
    return response['Functions']
```
The `list_lambda_functions` function retrieves a list of Lambda functions using the `list_functions` API call.

**Checking Lambda Invocations:**
```python
cloudwatch_client = boto3.client('cloudwatch')

def check_lambda_invocations(function_name):
    end_time = datetime.utcnow()
    start_time = end_time - timedelta(days=30)  # 1 month
    
    response = cloudwatch_client.get_metric_statistics(
        Namespace='AWS/Lambda',
        MetricName='Invocations',
        Dimensions=[{'Name': 'FunctionName', 'Value': function_name}],
        StartTime=start_time,
        EndTime=end_time,
        Period=2592000, 
        Statistics=['Sum']
    )
    return response['Datapoints'][0]['Sum'] if response['Datapoints'] else 0
```
The `check_lambda_invocations` function queries CloudWatch for invocation statistics for a specified Lambda function over the last month.

**Generating the Inventory CSV:**
```python
csv_file = 'lambda_inventory.csv'

with open(csv_file, mode='w', newline='') as file:
    writer = csv.writer(file)
    # Write header row
    writer.writerow(['FunctionName', 'Runtime', 'Invocations'])

    # List Lambda functions and write details to the CSV file
    lambda_functions = list_lambda_functions()
    for function in lambda_functions:
        function_name = function['FunctionName']
        runtime = function['Runtime']
        invocations = check_lambda_invocations(function_name)
        writer.writerow([function_name, runtime, invocations])
```
The script opens a CSV file, writes a header row, lists Lambda functions, checks their invocations, and writes the details to the CSV file.

For more information on CloudWatch API and Lambda API calls, check out the API references for [Lambda](https://docs.aws.amazon.com/lambda/latest/dg/API_Reference.html) and [CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/Welcome.html). 

**Conclusion:**
With this Python script, you can effortlessly generate a comprehensive inventory of your AWS Lambda functions, including runtime details and invocation statistics over the last month. This inventory is invaluable for performance optimization, resource allocation, and understanding the usage patterns of your serverless architecture. Consider integrating this script into your regular monitoring routine for enhanced AWS Lambda management.

Thank you for making it this far! Kindly comment and review.