Tuesday, October 29, 2019

How To Create A Lambda Function On AWS With Python That Creates An SQS Every Morning And Deletes It Every Night

First of all, go to Lambda service page on AWS, then create a function with a role having AmazonSQSFullAccess policy:


Afterward, inject the following code into the function:

import boto3

sqs = boto3.client('sqs')

def lambda_handler(event, context):
    if 'morning' in event['resources'][0]:
        # Create queue if morning event
        sqs.create_queue(
            QueueName='testEnvQueue',
        )
        print('Creating queue')
    if 'night' in event['resources'][0]:
        # Delete queue if night event
        QUEUE_URL = sqs.get_queue_url(
            QueueName='testEnvQueue'
        )['QueueUrl']
        sqs.delete_queue(
            QueueUrl=QUEUE_URL
        )
        print('deleting queue')

Next, at the top of the page hit Add trigger button:


And select CloudWatch Events, then select Create a new rule. In the Rule name field, make sure your name contains 'morning' and in the Schedule expression field enter something like rate(2 minutes) which will create an SQS queue named 'testEnvQueue' every 2 minutes just for the purpose of testing:


 Finally, add another CloudWatch event to simulate night to delete the created queue.

No comments:

Post a Comment