|
| 1 | +title: Monitoring Python 3.6 Functions on AWS Lambda |
| 2 | +slug: monitor-python-3-6-example-code-aws-lambda-rollbar |
| 3 | +meta: Monitor your Python 3.6 application code on Amazon Web Services (AWS) Lambda functions using Rollbar. |
| 4 | +category: post |
| 5 | +date: 2018-04-20 |
| 6 | +modified: 2018-04-20 |
| 7 | +newsletter: False |
| 8 | +headerimage: /img/180420-monitor-aws-lambda/header.jpg |
| 9 | +headeralt: Python, AWS Lambda and Rollbar logos are copyright their respective owners. |
| 10 | + |
| 11 | + |
| 12 | +[Amazon Web Services (AWS) Lambda](/aws-lambda.html) is a usage-based |
| 13 | +execution environment that can run Python 3.6 code. If you have never |
| 14 | +previously used AWS Lambda then you can read |
| 15 | +[How to Create Your First Python 3.6 AWS Lambda Function](/blog/aws-lambda-python-3-6.html). |
| 16 | +However, this tutorial will give you every step to follow even if you |
| 17 | +are completely new to AWS. |
| 18 | + |
| 19 | +In this post we are going to monitor Python code that is running on AWS |
| 20 | +Lambda by using a hosted [monitoring](/monitoring.html) service, |
| 21 | +[Rollbar](/rollbar.html). |
| 22 | + |
| 23 | + |
| 24 | +## Required Tools and Code |
| 25 | +A local [development environment](/development-environments.html) is not |
| 26 | +required to follow this tutorial. All the work will happen in a web |
| 27 | +browser through the [AWS Console](https://console.aws.amazon.com/console/). |
| 28 | + |
| 29 | +The example code can be copy and pasted from this blog post or you |
| 30 | +can access it on GitHub under the |
| 31 | +[Full Stack Python blog-post-examples](https://github.com/fullstackpython/blog-code-examples) |
| 32 | +repository within the |
| 33 | +[monitor-aws-lambda-python-3-6 directory](https://github.com/fullstackpython/blog-code-examples/monitor-aws-lambda-python-3-6). |
| 34 | + |
| 35 | + |
| 36 | +## Accessing the AWS Lambda Service |
| 37 | +[Sign into your existing AWS account](https://aws.amazon.com/console) |
| 38 | +or sign up for a [new account](https://aws.amazon.com/). AWS Lambda |
| 39 | +comes with a free tier so you can test code and execute basic |
| 40 | +applications without cost. |
| 41 | + |
| 42 | +<img src="/img/180420-monitor-aws-lambda/aws-amazon-com.jpg" width="100%" class="shot rnd outl" alt="AWS Lambda landing page."> |
| 43 | + |
| 44 | +AWS has a boatload of services so use the search box to enter |
| 45 | +"lambda" and select "Lambda" when it appears to get to the appropriate |
| 46 | +starting page. |
| 47 | + |
| 48 | +<img src="/img/180420-monitor-aws-lambda/search-for-lambda.jpg" width="100%" class="shot rnd outl" alt="Search for lambda in the dashboard text box."> |
| 49 | + |
| 50 | +Click "Create a Lambda function" and the "Select Blueprint" page should |
| 51 | +appear. |
| 52 | + |
| 53 | +<img src="/img/180420-monitor-aws-lambda/select-blueprint.jpg" width="100%" class="shot rnd outl" alt="The Select Blueprint Lambda screen."> |
| 54 | + |
| 55 | +Select "Blank Function". The "Configure triggers" page should appear next. |
| 56 | +A trigger is how the Lambda function typically knows |
| 57 | +when to execute based on an event from another AWS service like |
| 58 | +[Cloudwatch](https://aws.amazon.com/cloudwatch/) or |
| 59 | +[API Gateway](https://aws.amazon.com/api-gateway/). |
| 60 | + |
| 61 | +<img src="/img/180420-monitor-aws-lambda/configure-triggers.jpg" width="100%" class="shot rnd outl" alt="Screen for configuring the AWS Lambda trigger."> |
| 62 | + |
| 63 | +You do not need to configure a trigger to move to the next screen so |
| 64 | +we will not configure a trigger for this function. We can manually |
| 65 | +kick off the Lambda to test it when we are done with configuring it. Leave |
| 66 | +the trigger icon blank and click "Next" to continue. |
| 67 | + |
| 68 | +<img src="/img/180420-monitor-aws-lambda/blank-lambda.jpg" width="100%" class="shot rnd outl" alt="Blank AWS Lambda function."> |
| 69 | + |
| 70 | +Ok, finally we arrive at the "Configure function" screen where we can write |
| 71 | +our code. |
| 72 | + |
| 73 | + |
| 74 | +## Lambda Function Python Example Code |
| 75 | +Enter a name for the Lambda function, such as "python_3_6_lambda_test", |
| 76 | +as well as a description. A description is optional but it is useful |
| 77 | +when you have a dozens or hundreds of different Lambda functions and |
| 78 | +need to keep them straight. In the Runtime drop-down, select Python 3.6 for |
| 79 | +the programming language. |
| 80 | + |
| 81 | +<img src="/img/170429-aws-lambda-python-3-6/python-3-6-lambda.jpg" width="100%" class="technical-diagram img-rounded bordered" alt="Enter a name, description and use Python 3.6 for the Lambda."> |
| 82 | + |
| 83 | +Beneath the Runtime drop-down there is a large text box for code, |
| 84 | +prepopulated with a `lambda_handler` function definition. The |
| 85 | +"Code entry type" drop-down can also be changed to allow uploading a ZIP |
| 86 | +file or inputing a file from an S3 bucket. For our simple first |
| 87 | +Lambda function we will stick to the "Edit code inline" option. Copy or type |
| 88 | +in the following code, replacing what is already in the text box. This |
| 89 | +code is also available on [this open source GitHub repository](https://github.com/fullstackpython/blog-code-examples/blob/master/aws-lambda-python-3-6/). |
| 90 | + |
| 91 | + |
| 92 | +```python |
| 93 | +import os |
| 94 | + |
| 95 | + |
| 96 | +def lambda_handler(event, context): |
| 97 | + what_to_print = os.environ.get("what_to_print") |
| 98 | + how_many_times = int(os.environ.get("how_many_times")) |
| 99 | + |
| 100 | + # make sure what_to_print and how_many_times values exist |
| 101 | + if what_to_print and how_many_times > 0: |
| 102 | + for i in range(0, how_many_times): |
| 103 | + # formatted string literals are new in Python 3.6 |
| 104 | + print(f"what_to_print: {what_to_print}.") |
| 105 | + return what_to_print |
| 106 | + return None |
| 107 | +``` |
| 108 | + |
| 109 | +The code above contains a required `lambda_handler` function, which is |
| 110 | +AWS Lambda's defined hook so it knows where to begin execution. Think of |
| 111 | +`lambda_handler` as a `main` function, like the |
| 112 | +`if __name__ == "__main__":` conditional line commonly used in Python files |
| 113 | +to ensure a block of code is executed when a script is run from the |
| 114 | +command line. |
| 115 | + |
| 116 | +The Python code expects two environment variables that are read by the |
| 117 | +`os` module with the `environ.get` function. With the `what_to_print` and |
| 118 | +`how_many_times` variables set by the environment variables, our code then |
| 119 | +then prints a message zero or more times, based on the amount defined in |
| 120 | +the `how_many_times` variable. If a message is printed at least once then |
| 121 | +the function returns the `what_to_print` string, if nothing is printed |
| 122 | +then `None` is returned. |
| 123 | + |
| 124 | +Below the code input text box on this function configuration screen there |
| 125 | +is a section to set environment variable key-value pairs. |
| 126 | + |
| 127 | +Enter the keys named `what_to_print` and `how_many_times` then enter their |
| 128 | +values. Use a string message for `what_to_print`'s value and an integer |
| 129 | +whole number above 0 for `how_many_times`. Our Python code's error handling |
| 130 | +is not very robust so a value other than a number in the `how_many_times` |
| 131 | +variable will cause the script to throw an error when it is executed due |
| 132 | +to the forced casting of `how_many_times` via the `int()` function. |
| 133 | + |
| 134 | +<img src="/img/170429-aws-lambda-python-3-6/environment-variables.jpg" width="100%" class="technical-diagram img-rounded bordered" alt="Section to set environment variables for the Lambda function."> |
| 135 | + |
| 136 | +The Python 3.6 code and the environment variables are now in place. We |
| 137 | +just need to handle a few more AWS-specific settings before we can test the |
| 138 | +Lambda function. |
| 139 | + |
| 140 | + |
| 141 | +## Executing our Lambda Function |
| 142 | +Scroll past the environment variables to the |
| 143 | +"Lambda function handler and role" section, which contains a few more |
| 144 | +required function configuration items. |
| 145 | + |
| 146 | +Keep the default handler set to `lambda_function.lambda_handler`. Select |
| 147 | +"Create a new Role from template(s)" from the drop-down then for the |
| 148 | +"Role name" field enter "dynamodb_access". Under "Policy templates" |
| 149 | +select the "Simple Microservice permissions". |
| 150 | + |
| 151 | +The "Simple Microservice permissions" allows our Lambda to access |
| 152 | +[AWS DynamoDB](https://aws.amazon.com/dynamodb/). We will not use DynamoDB in |
| 153 | +this tutorial but the service is commonly used either as permanent or |
| 154 | +temporary storage for Lambda functions. |
| 155 | + |
| 156 | +<img src="/img/170429-aws-lambda-python-3-6/lambda-handler-and-role.jpg" width="100%" class="technical-diagram img-rounded bordered" alt="For the final configuration, keep the default handler, create a new role from a template for Simple Microservice permissions and save it with a unique name."> |
| 157 | + |
| 158 | +Our code and configuration is in place so click the "Next" button |
| 159 | +at the bottom right corner of the page. |
| 160 | + |
| 161 | +<img src="/img/170429-aws-lambda-python-3-6/review-lambda.jpg" width="100%" class="technical-diagram img-rounded bordered" alt="Review Lambda configuration."> |
| 162 | + |
| 163 | +The review screen shows us our configuration settings to make sure we |
| 164 | +selected the appropriate values for our new Lambda function. Scroll down |
| 165 | +press "Create function". |
| 166 | + |
| 167 | +<img src="/img/170429-aws-lambda-python-3-6/create-function.jpg" width="100%" class="technical-diagram img-rounded bordered" alt="Click the create function button to continue."> |
| 168 | + |
| 169 | +Success message should appear on the next page below the "Test" button. |
| 170 | + |
| 171 | +<img src="/img/170429-aws-lambda-python-3-6/test.jpg" width="100%" class="technical-diagram img-rounded bordered" alt="Test button on the execution screen."> |
| 172 | + |
| 173 | +Click the "Test" button to execute the Lambda. Lambda will prompt us for |
| 174 | +some data to simulate an event that would kick off our function. Select |
| 175 | +the "Hello World" sample event template, which contains some keys but our |
| 176 | +Lambda will not use that in its execution. Click the "Save and test" button |
| 177 | +at the bottom of the modal. |
| 178 | + |
| 179 | +<img src="/img/170429-aws-lambda-python-3-6/sample-event-template.jpg" width="100%" class="technical-diagram img-rounded bordered" alt="Sample event template for Lambda execution."> |
| 180 | + |
| 181 | +Scroll down to the "Execution result" section where we can see our output. |
| 182 | + |
| 183 | +<img src="/img/170429-aws-lambda-python-3-6/execution-results.jpg" width="100%" class="technical-diagram img-rounded bordered" alt="Results from executing our new Lambda function."> |
| 184 | + |
| 185 | +The log output shows us the return value of our function, which in this |
| 186 | +execution was the string message from `what_to_print`. We can also see |
| 187 | +our print function produced output five times as expected based on the |
| 188 | +amount set in the `how_many_times` environment variable. |
| 189 | + |
| 190 | + |
| 191 | +## What's Next? |
| 192 | +We just wrote and executed a Python 3.6 function on AWS Lambda then |
| 193 | +captured the exception message into our Rollbar logs. Now you can |
| 194 | +continue building out your Python code knowing that when something |
| 195 | +goes wrong you will have full visibility on what happened. |
| 196 | + |
| 197 | +Check out the [AWS Lambda section](/aws-lambda.html) for |
| 198 | +more tutorials by other developers. |
| 199 | + |
| 200 | +Further questions? Contact me on Twitter |
| 201 | +[@fullstackpython](https://twitter.com/fullstackpython) |
| 202 | +or [@mattmakai](https://twitter.com/mattmakai). I am also on GitHub with |
| 203 | +the username [mattmakai](https://github.com/mattmakai). |
| 204 | + |
| 205 | +Something wrong with this post? Fork |
| 206 | +[this page's source on GitHub](https://github.com/mattmakai/fullstackpython.com/blob/master/content/posts/180420-monitor-aws-lambda-python-3-6.markdown) |
| 207 | +and submit a pull request. |
0 commit comments