简体   繁体   中英

Obtain EC2 instance IP from AWS lambda function and use requests library

I am writing a lambda function on Amazon AWS Lambda. It accesses the URL of an EC2 instance, on which I am running a web REST API. The lambda function is triggered by Alexa and is coded in the Python language (python3.x).

Currently, I have hard coded the URL of the EC2 instance in the lambda function and successfully ran the Alexa skill.

I want the lambda function to automatically obtain the IP from the EC2 instance, which keeps changing whenever I start the instance. This would ensure that I don't have to go the code and hard code the URL each time I start the EC2 instance.

I stumbled upon a similar question on SO, but it was unanswered. However, there was a reply which indicated updating IAM roles. I have already created IAM roles for other purposes before, but I am still not used to it. Is this possible? Will it require managing of security groups of the EC2 instance? Do I need to set some permissions/configurations/settings? How can the lambda code achieve this?

Additionally, I pip installed the requests library on my system, and I tried uploading a '.zip' file with the structure :

  • REST.zip/
    • requests library folder
    • index.py

I am currently using the urllib library

When I use zip files for my code upload (I currently edit code inline), it can't even accesse index.py file to run the code

You could do it using boto3 , but I would advise against that architecture. A better approach would be to use a load balancer (even if you only have one instance), and then use the CNAME record of the load balancer in your application (this will not change for as long as the LB exists).

An even better way, if you have access to your own domain name, would be to create a CNAME record and point it to the address of the load balancer. Then you can happily use the DNS name in your Lambda function without fear that it would ever change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM