Saturday 10 February 2018

AWS Lambda Function With RDS MySQL

How To Use AWS Lambda Function With AWS RDS MySQL

If you ever want to have small service that access database and returns some result then you should go for AWS Lambda as it costs you only when it gets invoked. So You will be paying less then an ec2 instance.

Let's go ahead and see how we can create a lambda function which will interact with a database build on AWS RDS MySQL. You can choose your own database like postgresql hosted on an ec2 instance, but here for the sake of simplicity we will be using RDS MySQL.

First get your database Instance Up and running. You will need to have its endpoint, username, password and database name.
  • Get the repository from my github.
  • Create a database instance.
  • Fill in the databases instance details in main.py
  • Make sure you have correct security group settings in place.

Below is the main sample code (main.py):

# A lambda function to interact with AWS RDS MySQL

import pymysql
import sys

REGION = 'us-east-1'

rds_host  = "appychip.c7hugt6dv8dv.ap-south-1.rds.amazonaws.com"
name = "appychip"
password = "appychippassword"
db_name = "appychip"

def save_events(event):
    """
    This function fetches content from mysql RDS instance
    """
    result = []
    conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name, connect_timeout=5)
    with conn.cursor() as cur:
        cur.execute("""insert into test (id, name) values( %s, '%s')""" % (event['id'], event['name']))
        cur.execute("""select * from test""")
        conn.commit()
        cur.close()
        for row in cur:
            result.append(list(row))
        print "Data from RDS..."
        print result

def main(event, context):
    save_events(event)
        


# event = {
#   "id": 777,
#   "name": "appychip"
# }
# context = ""
# main(event, context)


The point here to note is that we are using pymysql library which we need to install in our current working directory where our main.py file is present. To install it you can run the following command:

pip install pymysql -t .

Now, since we have the required library in place, we need to create the zip of our code and upload it on the lambda function. To make a zip run the following command:

zip -r lambdaRDS.zip `ls`

Save the lambda function and go ahead running the script by passing a test event to the function which looks like below:

{
  "id": "1",
  "name": "appychip"
}

Now go ahead running the lambda function. On successful execution, this will insert a record into mysql.

Hurray!!! you just created a lambda function which interacts with database. To create an API endpoint to your lambda function, checkout our tutorial Scalable architecture using AWS API Gateway, lambda function and dynamodb.

18 comments:

  1. Thanks for the great code examples. if I have a mysql instance on a LAMP instance in AWS, could I access it with this code by pointing to the IP address ?

    ReplyDelete
    Replies
    1. I do understand this is for RDS but wondering about a nonRDS instance. The ports seem to be the same, so it seems possible...

      Delete
  2. Could you explain what you mean by "Make sure you have correct security group settings in place"? On the RDS instance or on the lambda? And what kind of security group?

    Did you create the RDS instance with public internet access? And then are you accessing the RDS instance from your lambda through the public internet access?

    Thanks

    ReplyDelete
  3. Your company is the crucial data warehouse solution provider , offered me easy access to complex data.

    ReplyDelete
  4. Hi. Can you use IAM and not put credentials in the code?

    ReplyDelete
  5. Hello, Appreciate your article on this subject.
    I have a query. Is it possible use AWS lambda to scale up a RDS instance ? Like from a db.t3.xlarge to db.m5.2xlarge ?
    Please let me know if you have a solution. Thanks in advance.

    ReplyDelete
  6. Thumbs up guys your doing a really good job Kesari Yoruba movie

    ReplyDelete
  7. Very informative post, really help me.
    Naresh IT is The Best Software Training Institute, It Provides AWS Online Training, From this AWS Online Course you will be able to learn all the Concepts of AWS with real-time Industry Exports, Having the combined experience of more than 10+ yrs in the industry.

    ReplyDelete

  8. Nice to see this BLOG..keep updating More infromation Digital Lync offers one of the best Full Stack training in Hyderabad with a comprehensive course curriculum with Continuous Integration, Delivery, and Testing. Elevate your practical knowledge with quizzes, assignments, Competitions, and Hackathons to give a boost to your confidence with our hands-on Full Stack Training.
    DevOps Training Institute
    Python Training Institute
    AWS Training Institute
    Online Full Stack Developer Course Hyderabad
    Python Course Hyderabad
    Online AWS Training Course Hyderabad
    devops training in hyderabad
    angular training in hyderabad

    ReplyDelete
  9. Genexbd is capable of storing a large number of records efficiently. New data can be calculated easily and older data can be updated or deleted. With a database, one can search and retrieve information quickly. The role of data in marketing, business, government, etc., has become increasingly important.
    https://genexdbs.com/

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. A React course is a training program that teaches you how to use React, a JavaScript library for building user interfaces. React is one of the most popular JavaScript libraries in the world, and it is used by many large companies, such as Facebook, Airbnb, and Netflix.

    A React course typically covers the following topics:

    The basics of React, including components, state, and props
    Advanced React topics, such as routing, Redux, and testing
    How to build real-world applications with React
    React training in Hyderabad

    ReplyDelete
  12. Are you looking to enhance your skills in cloud computing? Join our Google Cloud Platform Online training in Hyderabad and unlock a world of opportunities in the tech industry. With our comprehensive curriculum and expert instructors, you'll gain in-depth knowledge of the Google Cloud Platform and its various services. From cloud storage and databases to machine learning and big data analytics, our training covers it all. Be equipped with the skills to design, deploy, and manage applications and infrastructure on the Google Cloud Platform. Enroll now and take your career to new heights!
    Google Cloud Platform Online training in Hyderabad

    ReplyDelete
  13. Elevate your educational journey with F1 Visa Consultants in Hyderabad. Our expert team offers tailored guidance, ensuring a smooth path to obtaining your student visa for the USA. Trust our experience for a successful transition to American universities and a bright academic future.
    F1 Visa Consultants in Hyderabad

    ReplyDelete
  14. nice blog
    thanks for sheering information

    Flutter Training in Hyderabad

    ReplyDelete
  15. Thank you for sharing such valuable information.

    The detailed comparison of various training platforms and courses has given a clear roadmap to kickstart your journey with AWS Course

    ReplyDelete

 

Copyright @ 2013 Appychip.

Designed by Appychip & YouTube Channel