Ken Yip
Ken Yip

Reputation: 761

How to enable lambda function to access APIs on EC2 instance over nginx

I have create a server that provide APIs using nodejs program and using nginx for reverse proxy. I have set the inbound rules so that only specific ip addresses can access the APIs.

Now, I wish to create a lambda function which can access the APIs on that ec2 instance. I have assigned them into same VPC and security group. However, I got HTTP 502 response when I call the lambda function even though I have used try-catch block for the error.

const axios = require('axios');
const serializeError = require('serialize-error');

module.exports.translate = async (event, context) => {
    try {
        const response = await axios.post("http://EC2-DOMAIN")
        return { statusCode: 200 };
    } catch( error ){
        console.log(JSON.stringify(serializeError(error), null, 4));
        return { statusCode: 400 };
    }
};

Is there any mistake I have made? Thank you!

Upvotes: 1

Views: 1048

Answers (2)

semipermeable
semipermeable

Reputation: 91

If I understand your config correctly, you may just need to add a rule in your security group allowing traffic on 80 (or whichever port you are running your api), referencing itself as the source.

Here's a link to the documentation explaining this behavior.

Resources are in the same security group cannot talk to each other unless there's a rule allowing them to do so. To make it less confusing, you may want to think about creating a security group for your lambda functions, and adding a rule to your instance SG that allows traffic from your lambda SG on your api port.

Upvotes: 2

Nishant Singh
Nishant Singh

Reputation: 3209

The way you should approach this problem is :

  1. See if lambda has permissions to talk to EC2 service, See this.

  2. Next you should try to see if you are actually able to hit the API via lambda function by trying to log that call , a simple way would be to see if you are able to hit the ec2 via lambda on the Nginx port.

  3. The above 2 steps will help you debug the issue if you have some permission or wrong setting somewhere. Let me know if till this you are able to do

Upvotes: 1

Related Questions