agent: |
iWxwb6VLMy7vCwQEvueYFilter Out Unused AWS Lambda Functions
Filter Out Unused AWS Lambda Functions
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.
This task involves identifying and listing AWS Lambda functions that are potentially unused based on specific criteria such as no associated CloudWatch events, no recent invocations, and absence of scheduled triggers. The aim is to help optimize AWS resources by pinpointing functions that may no longer be needed or are idle, allowing for better management and potential cost savings.
inputs
outputs
import boto3
from datetime import datetime, timedelta
creds = _get_creds(cred_label)['creds']
access_key = creds['username']
secret_key = creds['password']
def get_cloudwatch_events(lambda_arn, region):
"""Check if a Lambda function is triggered by any CloudWatch event."""
events_client = boto3.client('events', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name=region)
try:
rules = events_client.list_rules()
for rule in rules['Rules']:
targets = events_client.list_targets_by_rule(Rule=rule['Name'])
for target in targets['Targets']:
if target['Arn'] == lambda_arn:
return True
except Exception as e:
print(f"Error checking CloudWatch events for {lambda_arn}: {e}")
return False
def get_lambda_invocations(func_name, region, days_threshold):
"""Check for Lambda invocations in the last specified number of days."""
cloudwatch_client = boto3.client('cloudwatch', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name=region)
end_time = datetime.now()
start_time = end_time - timedelta(days=days_threshold)
try:
metrics = cloudwatch_client.get_metric_statistics(
Namespace='AWS/Lambda',
MetricName='Invocations',
Dimensions=[{'Name': 'FunctionName', 'Value': func_name}],
StartTime=start_time,
EndTime=end_time,
Period=86400,
Statistics=['Sum']
)
total_invocations = sum(data_point['Sum'] for data_point in metrics['Datapoints'])
return total_invocations == 0
except Exception as e:
print(f"Error retrieving invocations for {func_name}: {e}")
return False
def filter_unused_lambda_functions(functions, days_threshold):
unused_functions = []
for func in functions:
region = func['Region']
if not get_cloudwatch_events(func['FunctionArn'], region) and get_lambda_invocations(func['FunctionName'], region, days_threshold):
last_modified = datetime.strptime(func['LastModified'], '%Y-%m-%dT%H:%M:%S.%f%z')
details = {
'FunctionName': func['FunctionName'],
'Region': region,
'LastModified': last_modified.strftime('%Y-%m-%d %H:%M:%S'),
'Runtime': func['Runtime'],
'MemorySize': func['MemorySize']
}
unused_functions.append(details)
return unused_functions
def display_lambda_details(data):
"""Display all unused Lambda functions in a formatted table."""
table = context.newtable()
table.title = "Unused AWS Lambda Functions"
table.num_cols = 5
table.num_rows = 1
table.has_header_row = True
headers = ["Function Name", "Region", "Memory Size", "Runtime", "Last Modified"]
for col_num, header in enumerate(headers):
table.setval(0, col_num, header)
for row_num, func in enumerate(data, start=1):
table.num_rows += 1
values = [
func['FunctionName'],
func['Region'],
f"{func['MemorySize']} MB",
func['Runtime'],
func['LastModified']
]
for col_num, value in enumerate(values):
table.setval(row_num, col_num, value)
# Example usage
#last_accessed_threshold_days = 90 # Modify as needed
#all_functions = [{'FunctionName': 'exampleFunction', 'Region': 'us-east-1', 'LastModified': '2023-01-01T00:00:00.000Z', 'Runtime': 'python3.8', 'MemorySize': 128}] # Placeholder data
unused_functions = filter_unused_lambda_functions(all_functions, last_accessed_threshold_days)
if unused_functions:
display_lambda_details(unused_functions)
else:
print("No unused Lambda functions found.")
context.skip_sub_tasks = True
copied
- 1Qb6YD4ENCAkJIgLiOsnZDelete AWS Lambda Functions
1
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.This task involves safely removing unused or redundant Lambda functions from an AWS account to streamline operations and reduce costs.
inputsoutputsimport boto3 from datetime import datetime, timedelta # Assuming credentials are securely fetched and stored creds = _get_creds(cred_label)['creds'] access_key = creds['username'] secret_key = creds['password'] def get_lambda_client(region): """Create a Lambda client for a specific region using provided credentials.""" return boto3.client( 'lambda', region_name=region, aws_access_key_id=access_key, aws_secret_access_key=secret_key ) def delete_lambda_function(function_name, region): """Delete a specific Lambda function in a specified region.""" lambda_client = get_lambda_client(region) try: response = lambda_client.delete_function(FunctionName=function_name) print(f"Successfully deleted {function_name} in {region}.") return response except Exception as e: print(f"Failed to delete {function_name} in {region}: {e}") def delete_unused_lambda_functions(unused_functions): """Delete unused Lambda functions from a list of function details.""" for func in unused_functions: delete_lambda_function(func['FunctionName'], func['Region']) # Example usage delete_unused_lambda_functions(unused_functions)copied1