Search code examples
amazon-web-servicesaws-lambdaamazon-sqs

How get the content of SQS Message using Lambda in AWS?


everyone.

I'm interested in get the content of SQS Message using Lambda. Let me explain my infrastructure: I have an EC2 instance that has a script like that bellow. So, it script will send to SQS the message containing instance ID.

#!/bin/bash
INSTANCE_ID=$(curl http://*.*.*.*/latest/meta-data/instance-id)
REGION=$(curl http://*.*.*.*/latest/meta-data/placement/availability-zone | sed '$s/.$//')
QUEUE-URL=$(...)

aws sqs send-message --queue-url "${QUEUE-URL}" --message-body "${INSTANCE_ID}" --region "${REGION}"

The ideia is: when the SQS recieve the message, I would like to trigger a Lambda Function to modificate this instance. But, for that, I need the instance ID. I have searching a lot and unfortunately, I couldn't understand very well how I could get the instance ID, using AWS Lambda, from the SQS Message mentioned above.

I've been trying to solve this problem, but as I don't understand Lambda so much, I searched for many solutions and tested then. Unfortunately, I had no success. So, I interested to learn more about this service.

If someone's could help me with that, I'd be very greateful.


Solution

  • The AWS Lambda function can be configured with the Amazon SQS queue as a 'trigger'.

    When a message is sent to the SQS queue, the Lambda function will be invoked. The message both will be available in the Lambda function body.

    The code would look something like:

    def lambda_handler(event, context):
        for record in event['Records']:
          body = record['body']
          print("From SQS: " + body)
    

    It is possible that multiple messages are passed to the Lambda function, so it first loops through each Record, then extracts the passed-in information in the body parameter.

    The print() will show the contents of the message body in CloudWatch Logs. Check to make sure it contains what you expect. Then, add code that uses that value.

    There is no need for your Lambda function to specifically call SQS -- this is handled automatically by the AWS Lambda service, which will then delete the message from the queue after your Lambda function successfully completes.