For the second part, Steps 8-10 and 13 of the Cloud Resume Challenge. The learner is introduced to important components that will enhance the functionality and automation of their cloud resume. Goal 1: Get your Lambda function talking to the database (Step 8), Goal 2: Trigger your Lambda function from the outside world (Step 9), Trigger your Lambda function from your static site (Step 10), and set up source control for efficient development (Step 13).
GETTING THE LAMBDA FUNCTION TO TALK TO THE DATABASE. (step 8)
In the Cloud Resume Challenge, each step presents a valuable opportunity to enhance my web development skills. Step 8 focuses on a critical aspect of my resume website: incorporating a visitor counter powered by Amazon DynamoDB. DynamoDB, an AWS fully managed NoSQL database service, provides an efficient solution for storing and updating visitor counts on our website. By leveraging DynamoDB, I can ensure accurate and up-to-date analytics for my web presence. Let’s delve into the steps involved in implementing this essential feature:
- Setting up a Python Lambda Function:
- Using the AWS web console, to create a Python-based Lambda function.
- Configuring a DynamoDB Table:
- Within the AWS console, the learner will set up a DynamoDB table. This process involves straightforward point-and-click operations, allowing you to define the table’s structure and properties.
- Writing Python Code in the Lambda Function:
- In the Lambda function’s code, focus on crafting the Python logic responsible for saving values to the DynamoDB table.
Why DynamoDB?
In order to create a dynamic and engaging web experience, for my cloud resume, accurate website analytics play a pivotal role. To meet this need, I turned to DynamoDB, a scalable, highly available, and performant database solution that perfectly suited my visitor counter requirements. By leveraging the power of DynamoDB, I could effortlessly store and retrieve visitor count data, ensuring that my website analytics remained accurate and up-to-date. Setting up DynamoDB and connecting it to my Lambda function proved to be a straightforward process. With just a few clicks within the AWS console, I was able to configure the necessary tables and define the required attributes. The main objective was to create an ‘Item’ in DynamoDB, specifically named ‘Views,’ which would be continuously updated whenever visitors accessed my website and triggered the Lambda function.
By seamlessly integrating DynamoDB into my website, I gained the ability to capture and track visitor activity, providing valuable insights into the popularity and usage of my website. The power of DynamoDB lies not only in its ease of setup but also in its ability to scale effortlessly as my website attracts more visitors. This ensures that I have a robust and reliable system in place to accurately measure and analyze the impact of my web presence.
With DynamoDB acting as the backbone of my visitor counter, I can now gather meaningful data about user engagement, identify trends, and make informed decisions to improve the overall user experience. DynamoDB’s versatility and seamless integration with Lambda have proven invaluable, enabling me to focus on creating captivating content while letting the database handle the heavy lifting of data storage and retrieval. Lambda enables us to run serverless functions in response to events, making it an ideal choice for updating the visitor count whenever someone accesses our website. By creating a Lambda function, we can establish a connection between my website and DynamoDB, ensuring seamless data retrieval and updates. Below is a step-by-step guide on how to connect Amazon DynamoDB to a Lambda Function.
Here’s a step-by-step guide on how to connect Amazon DynamoDB to an AWS Lambda function:
Step 1: Set Up DynamoDB Table
- Access the AWS Management Console and navigate to the DynamoDB service.
- Click on “Create table” to set up a new table.
- Provide a suitable table name and define the primary key attribute.
- Configure any additional settings, such as read/write capacity modes, as per your requirements.
- Create the table to proceed to the next step.
Step 2: Create an AWS Lambda Function
- Go to the AWS Management Console and open the Lambda service.
- Click on “Create function” to start creating a new Lambda function.
- Provide a unique name for your function and choose the appropriate runtime, such as Python, Node.js, or Java. For the challenge, you would pick the latest version of Python.
- Under “Permissions,” choose an existing or create a new execution role with the necessary permissions to access DynamoDB.
- Click on “Create function” to proceed.
Step 10: Python
With the Lambda function set up for implementation, the next step in the process was to write the necessary Python code. Completing this portion of the challenge proved to be by far the hardest part for me, especially since I didn’t have a background in coding or extensive coding knowledge. Understanding the concept of Python and its applications was initially difficult. I ran into issues several times. One of the issues that I encountered a lot was syntax errors. Missing closed parentheses, indentation errors along with invalid keywords LOL, I experienced it all. However, I was determined to overcome this obstacle and successfully complete this part of the challenge. Despite the initial challenges, I approached this opportunity as a chance to learn and grow. Below is a sample of the Python code that I wrote to trigger the Lambda function.
import json
import boto3
def update_website_views():
# Connect to DynamoDB
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('your_table_name')
# Get current views count from DynamoDB
response = table.get_item(Key={'id': '1'})
if 'Item' in response:
views = response['Item'].get('views', 0)
views += 1
print(f"The website has been viewed {views} times.")
else:
views = 1
print(f"The website has been viewed {views} time.")
# Update views count in DynamoDB
response = table.put_item(Item={'id': '1', 'views': views})
return views
def lambda_handler(event, context):
# Update website views count
views = update_website_views()
# Return the updated views count as the response
return {
'statusCode': 200,
'body': json.dumps({'views': views})
}
The provided code is a Python script written for an AWS Lambda function that interacts with DynamoDB. Here’s a breakdown of what my code does:
- It imports the necessary modules,
json
andboto3
, which are used for working with JSON data and interacting with AWS services, respectively. - It creates a DynamoDB resource object using the
boto3.resource()
method and specifies the resource type asdynamodb
. - It assigns the DynamoDB table named “‘your_table_name'” to the
table
variable using thedynamodb.Table()
method. (Note) be sure sure to replace ‘your_table_name’ with the name of your table. - The
lambda_handler
the function is defined, which is the entry point for the Lambda function. It takes two parameters,event
andcontext
, which represents the event data and context information for the Lambda function. - Inside the
lambda_handler
function, it calls theget_item
method on thetable
object to retrieve an item from the DynamoDB table. It uses a specific key,id
, with the value of ‘1’. - It checks if the response from the
get_item
operation contains an ‘Item’ key, indicating that the item was found in the table. - If the ‘Item’ key is present, it retrieves the ‘views’ attribute value from the item using the
response['Item'].get('views', 0)
code. If the ‘views’ attribute doesn’t exist, it defaults to 0. - It increments the ‘views’ count by 1.
- It prints a message indicating the number of times the website has been viewed, using f-string formatting to insert the ‘views’ count into the message.
- It calls the
put_item
method on thetable
object to update the item in the DynamoDB table with the new ‘views’ count. - If the ‘Item’ key is not present in the response, it means that the item doesn’t exist in the table. In this case, it initializes the ‘views’ count to 1 and prints a message indicating that the website has been viewed once.
- Finally, it returns the ‘views’ count from the Lambda function.
Step 9: API
For this particular step of the challenge, the focus is on creating an API that facilitates communication between the web app and the database. Initially, my plan was to utilize the AWS API Gateway and set up a POST HTTP method. This method is commonly used when updating API resources and invoking the associated lambda function. However, during my research, I discovered a new functionality introduced by AWS that allows direct access to the lambda function through a Function URL. This convenient method can be found in the Configuration tab of your lambda function settings.
By leveraging the Function URL, I could simplify the architecture and streamline the communication process between the web app and the database. Rather than relying on an intermediate API Gateway, the Function URL provides a direct path to invoke the lambda function. This not only reduces the complexity of the setup but also enhances the overall efficiency of the system.
To access the Function URL, navigate to the Configuration tab within the lambda function settings. Here, you will find the option to enable the Function URL and configure its properties. Once enabled, the Function URL can be utilized by the web app to directly interact with the lambda function and perform database operations.
By leveraging this new functionality, I was able to optimize the communication between the web app and the database, simplifying the architecture and reducing potential points of failure. The direct invocation of the lambda function through the Function URL proved to be a valuable addition to my solution, enhancing the overall performance and reliability of my website.
Step 13: Source Control
In Step 13 of the challenge, one of the most important aspects is introduced. Source Control ensures that updates to both the front-end and back-end websites occur automatically when code changes are made, eliminating the need for manual intervention by the user. By adopting source control to my website, I can streamline the code management process and enable efficient continuous integration and deployment (CI/CD) practices.
To implement CI/CD, the first step is to create a GitHub repository specifically for your back-end code. GitHub provides a robust and widely adopted platform for version control and collaboration. By leveraging its features, you can easily manage and track code changes, enable collaboration with team members, and automate deployment processes.
For me, this step was fairly easy. Creating a GitHub repository was a straightforward process. You can simply sign in to GitHub (or create an account if you don’t have one), navigate to the repository creation page, and follow the prompts to set up a new repository. Provide an appropriate name and description for your code repository, and select the desired settings to customize its behavior. Once created, you will have a centralized location to store and manage your code, ensuring version control and enabling seamless integration with CI/CD pipelines. Below is a step-by-step guide to setting up Source Control with Github.
A step-by-step guide to setting up source control in GitHub:
- Create a GitHub account: Visit github.com and sign up for a new account if you don’t have one already. It’s free for individual users and offers various plans for organizations.
- Create a new repository: Once you’re logged in, click on the “New” button on the repository page to create a new repository. Give it a descriptive name, choose whether it will be public or private, and initialize it with a README file.
- Clone the repository: On your local machine, open a terminal or command prompt and navigate to the directory where you want to store your project. Use the
git clone
command followed by the repository URL to create a local copy of the repository. For example:git clone https://github.com/your-username/your-repository.git
- Add your project files: Copy or move your project files into the cloned repository directory. These files will be tracked by Git, the version control system used by GitHub.
- Stage and commit changes: In the terminal, navigate to the repository directory. Use the
git status
command to see the changes you’ve made. To stage the changes for commit, use thegit add
command followed by the file or directory names. For example:git add .
to stage all changes. Then, use thegit commit
command with a descriptive message to commit the changes. For example:git commit -m "Initial commit"
. - Push changes to GitHub: Use the
git push
command to upload your committed changes to the GitHub repository. For example:git push origin main
if your main branch is named “main”. You’ll be prompted to enter your GitHub credentials. - Explore branches and collaboration: GitHub supports branching, allowing you to work on different features or experiments independently. You can create branches, switch between them, and merge them back into the main branch when ready. Additionally, you can collaborate with others by adding them as collaborators to your repository or by forking and submitting pull requests to contribute to other projects.
Using GitHub for your code repository offers several advantages in software development. It enables you to implement key practices such as branch management, code reviews, and automated deployment. By leveraging these practices, I learned that you can foster collaboration, maintain high code quality, and ensure seamless updates to your front-end and back-end codes whenever changes are made to them.
Final thoughts
Chunk 2 of the Cloud Resume Challenge presented its fair share of challenges, but I embraced them and gained invaluable knowledge. My journey began with learning how to code with Python, this allowed me to create a website counter. I then transformed that code into a lambda function, which significantly improved the functionality, scalability, and maintainability of my cloud resume. By incorporating a database, API, Lambda functions, and source control, the development process of my website became more dynamic and automated. This section of the Cloud Resume Challenge was an exceptional learning experience, equipping me with the necessary tools and knowledge to build a resume website that is truly dynamic, scalable, and automated.