Schedule Lamda function writing to a DynamoDB

Now that we have a working bot and error logging in Slack. We want to be able to record daily information in a database to compare it with the previous month to see if there is an increase or not.

How to trigger a lambda at a specific time?

Create a new lambda function, and click on trigger. This time we will pick EventBridge (CloudWatch Events). For testing, I’m going to run this event every 5 minutes, but once that is done I’ll switch it to daily.

Next, we’ll want to create a DynamoDB as there will be little to no cost for us to use one as long as we don’t hit it often or add too much data. We will use an On-Demand as we will only pay for what we use.

We have a DB now, but we can’t write to it until we give the lambda function permission. AWS has an article explaining how to provide lambda access to write to a database.

Our lambda function is going to have the same Python functions as the one we created previously. Instead of returning the data to Slack, we will be writing in as a row in a DynamoDB.

def lambda_handler(event, context):
    print(f"Received event:\n{event}\nWith context:\n{context}")
    total_cost, actions_cost, storage_cost, copilot_cost = generate_billing()
    dynamodb = boto3.client('dynamodb')
    key_dic = {'date': {'S': get_today_date()},
               'cost': {'N': str(total_cost)},
               'actions': {'N': str(actions_cost)},
               'storage': {'N': str(storage_cost)},
               'copilot': {'N': str(copilot_cost)}}
    dynamodb.put_item(TableName='github_billing', Item=key_dic)

Leave a comment

Blog at WordPress.com.

Up ↑