|
| 1 | +title: How to Create Your First Python 3.6 AWS Lambda Function |
| 2 | +slug: aws-lambda-python-3-6 |
| 3 | +meta: Code, create and execute your first Amazon Web Services (AWS) Lambda function with Python 3.6. |
| 4 | +category: post |
| 5 | +date: 2017-04-29 |
| 6 | +modified: 2017-04-29 |
| 7 | +headerimage: /img/170429-aws-lambda-python-3-6/header.jpg |
| 8 | +headeralt: AWS, AWS Lambda and Python logos are copyright their respective owners. |
| 9 | + |
| 10 | + |
| 11 | +[Amazon Web Services (AWS) Lambda](/aws-lambda.html) |
| 12 | +provides a usage-based compute service for running Python code in response |
| 13 | +to developer-defined events. For example, if an inbound HTTP POST |
| 14 | +comes in to API Gateway or a new file is uploaded to |
| 15 | +[AWS S3](https://aws.amazon.com/s3/) then AWS Lambda can execute a function |
| 16 | +to respond to that API call or manipulate the file on S3. |
| 17 | + |
| 18 | +AWS Lambda is not related in any way to Python's `lambda` syntax. The |
| 19 | +`lambda` keyword in Python is used to create anonymous functions within the |
| 20 | +programming language and AWS Lambda's name just happens to collide with |
| 21 | +the existing Python feature. |
| 22 | + |
| 23 | +Let's learn how to quickly write and run a Lambda function to execute |
| 24 | +basic Python 3.6 code which uses environment variables as input. |
| 25 | +This code, which is also [available on GitHub under the blog-post-examples repository](https://github.com/fullstackpython/blog-code-examples) can be |
| 26 | +changed so that you can build much more complicated Python programs. |
| 27 | + |
| 28 | + |
| 29 | +## Our Tools |
| 30 | +No local [development environment](/development-environments.html) tools |
| 31 | +are required for this tutorial, other than a web browser. All the work will |
| 32 | +happen on AWS via their Console. All of these steps can also be completed |
| 33 | +from the command line via the [boto3](https://boto3.readthedocs.io/en/latest/) |
| 34 | +library, but we won't cover that in this post. |
| 35 | + |
| 36 | +Sign up for a new [Amazon Web Services account](https://aws.amazon.com/) |
| 37 | +(which provides a generous free tier), or use your existing AWS account. |
| 38 | + |
| 39 | + |
| 40 | +## First Steps with AWS Lambda |
| 41 | +In your web browser go to the |
| 42 | +[AWS Lambda landing page](https://aws.amazon.com/lambda/). |
| 43 | +Log in to your account, or sign up for a new account which |
| 44 | +comes with a free tier so you don't have to pay. |
| 45 | + |
| 46 | +<img src="/img/170429-aws-lambda-python-3-6/aws-amazon-com.jpg" width="100%" class="technical-diagram img-rounded" alt="AWS Lambda landing and sign in screen."> |
| 47 | + |
| 48 | +After signing up a few tutorials may pop up, but skip past them and |
| 49 | +go to the main Console. AWS has tons of services, with more being added |
| 50 | +every month, so using the search box is the best way to get around. |
| 51 | +Select the search text box, enter "lambda" and select "Lambda" to get to |
| 52 | +the right starting page. |
| 53 | + |
| 54 | +<img src="/img/170429-aws-lambda-python-3-6/search-for-lambda.jpg" width="100%" class="technical-diagram img-rounded bordered" alt="Search for lambda in the dashboard text box."> |
| 55 | + |
| 56 | +Click the "Create a Lambda function" button. The "Select Blueprint" page |
| 57 | +will appear. |
| 58 | + |
| 59 | +<img src="/img/170429-aws-lambda-python-3-6/select-blueprint.jpg" width="100%" class="technical-diagram img-rounded bordered" alt="The Select Blueprint Lambda screen."> |
| 60 | + |
| 61 | +Select "Blank Function" and the "Configure triggers" page will come up. |
| 62 | +It's non-obvious at first, but you don't actually need to configure a |
| 63 | +trigger to move on. A trigger is how the Lambda function typically knows |
| 64 | +when to execute based on an event from another AWS service such as API |
| 65 | +Gateway or Cloudwatch. |
| 66 | + |
| 67 | +<img src="/img/170429-aws-lambda-python-3-6/configure-triggers.jpg" width="100%" class="technical-diagram img-rounded bordered" alt="Configure Lambda trigger screen."> |
| 68 | + |
| 69 | +We won't configure a trigger for this function because we can manually |
| 70 | +kick off the Lambda later to test it. Leave the trigger icon blank and |
| 71 | +click the "Next" button to move along. |
| 72 | + |
| 73 | +<img src="/img/170429-aws-lambda-python-3-6/blank-lambda.jpg" width="100%" class="technical-diagram img-rounded bordered" alt="The Lambda configuration screen."> |
| 74 | + |
| 75 | +Next we get to the "Configure function" screen where we can finally write |
| 76 | +some code! |
| 77 | + |
| 78 | + |
| 79 | +## Python Code for Our Lambda Function |
| 80 | +Enter a name for the Lambda function, such as "python_3_6_lambda_test", |
| 81 | +as well as a description. A description is optional but it is useful |
| 82 | +when you have a dozens or hundreds of different Lambda functions and |
| 83 | +need to keep them straight. In the Runtime drop-down, select Python 3.6 for |
| 84 | +the programming language. |
| 85 | + |
| 86 | +<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."> |
| 87 | + |
| 88 | +Beneath the Runtime drop-down there is a large text box for code, |
| 89 | +prepopulated with a `lambda_handler` function definition. The |
| 90 | +"Code entry type" drop-down can also be changed to allow uploading a ZIP |
| 91 | +file or inputing a file from an S3 bucket. For our simple first |
| 92 | +Lambda function we will stick to the "Edit code inline" option. Copy or type |
| 93 | +in the following code, replacing what is already in the text box. This |
| 94 | +code is also available on [this open source GitHub repository](https://github.com/fullstackpython/blog-code-examples/blob/master/aws-lambda-python-3-6/). |
| 95 | + |
| 96 | + |
| 97 | +```python |
| 98 | +import os |
| 99 | + |
| 100 | + |
| 101 | +def lambda_handler(event, context): |
| 102 | + what_to_print = os.environ.get("what_to_print") |
| 103 | + how_many_times = int(os.environ.get("how_many_times")) |
| 104 | + |
| 105 | + # make sure what_to_print and how_many_times values exist |
| 106 | + if what_to_print and how_many_times > 0: |
| 107 | + for i in range(0, how_many_times): |
| 108 | + # formatted string literals are new in Python 3.6 |
| 109 | + print(f"what_to_print: {what_to_print}.") |
| 110 | + return what_to_print |
| 111 | + return None |
| 112 | +``` |
| 113 | + |
| 114 | +The code above contains a required `lambda_handler` function, which is |
| 115 | +AWS Lambda's defined hook so it knows where to begin execution. Think of |
| 116 | +`lambda_handler` as a `main` function, like the |
| 117 | +`if __name__ == "__main__":` conditional line commonly used in Python files |
| 118 | +to ensure a block of code is executed when a script is run from the |
| 119 | +command line. |
| 120 | + |
| 121 | +The Python code expects two environment variables that are read by the |
| 122 | +`os` module with the `environ.get` function. With the `what_to_print` and |
| 123 | +`how_many_times` variables set by the environment variables, our code then |
| 124 | +then prints a message zero or more times, based on the amount defined in |
| 125 | +the `how_many_times` variable. If a message is printed at least once then |
| 126 | +the function returns the `what_to_print` string, if nothing is printed |
| 127 | +then `None` is returned. |
| 128 | + |
| 129 | +Below the code input text box on this function configuration screen there |
| 130 | +is a section to set environment variable key-value pairs. |
| 131 | + |
| 132 | +Enter the keys named `what_to_print` and `how_many_times` then enter their |
| 133 | +values. Use a string message for `what_to_print`'s value and an integer |
| 134 | +whole number above 0 for `how_many_times`. Our Python code's error handling |
| 135 | +is not very robust so a value other than a number in the `how_many_times` |
| 136 | +variable will cause the script to throw an error when it is executed. |
| 137 | + |
| 138 | +<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."> |
| 139 | + |
| 140 | +The Python 3.6 code and the environment variables are now in place. We |
| 141 | +just need to handle a few more AWS-specific settings before we can test the |
| 142 | +Lambda function. |
| 143 | + |
| 144 | + |
| 145 | +## Executing our Lambda Function |
| 146 | +Scroll past the environment variables to the |
| 147 | +"Lambda function handler and role" section, which contains a few more |
| 148 | +required function configuration items. |
| 149 | + |
| 150 | +Keep the default handler set to `lambda_function.lambda_handler`. Select |
| 151 | +"Create a new Role from template(s)" from the drop-down then for the |
| 152 | +"Role name" field enter "dynamodb_permissions". Under "Policy templates" |
| 153 | +select the "Simple Microservice permissions". |
| 154 | + |
| 155 | +The "Simple Microservice permissions" allows our Lambda to access |
| 156 | +[AWS DynamoDB](https://aws.amazon.com/dynamodb/). We will not use DynamoDB in |
| 157 | +this tutorial but the service is commonly used either as permanent or |
| 158 | +temporary storage for Lambda functions. |
| 159 | + |
| 160 | +<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."> |
| 161 | + |
| 162 | +Now that our code and configuration is in place, click the "Next" button |
| 163 | +at the bottom right corner of the page. |
| 164 | + |
| 165 | +<img src="/img/170428-aws-lambda-python-2-7/review-lambda.jpg" width="100%" class="technical-diagram img-rounded bordered" alt="We can review the values set during our configuration."> |
| 166 | + |
| 167 | +The review screen will show us our configuration settings. Scroll down |
| 168 | +to the bottom and click the "Create function" button to continue. |
| 169 | + |
| 170 | +<img src="/img/170428-aws-lambda-python-2-7/create-function.jpg" width="100%" class="technical-diagram img-rounded bordered" alt="Click the create function button to continue."> |
| 171 | + |
| 172 | +We should see a success message on the next page just below the |
| 173 | +"Save and test" button. |
| 174 | + |
| 175 | +<img src="/img/170428-aws-lambda-python-2-7/save-and-test.jpg" width="100%" class="technical-diagram img-rounded bordered" alt="Save and test button."> |
| 176 | + |
| 177 | +Click that "Save and test" button to execute the Lambda. At first it |
| 178 | +may appear that nothing happened but scroll down to the "Execution result" |
| 179 | +section where we can see our output. |
| 180 | + |
| 181 | +<img src="/img/170428-aws-lambda-python-2-7/execution-results.jpg" width="100%" class="technical-diagram img-rounded bordered" alt="Execution results from running our Lambda function."> |
| 182 | + |
| 183 | +We get the log output that shows us the return value of our function. In |
| 184 | +this case it is the string message from `what_to_print`. We can also see |
| 185 | +down below that our print function produced output five times. |
| 186 | + |
| 187 | + |
| 188 | +## Next Steps |
| 189 | +Awesome, you just configured, wrote and executed your first Python 3.6 |
| 190 | +code on AWS Lambda! The real power of Lambda comes in when you connect a |
| 191 | +trigger to it so your code executes based on events. We'll take a look |
| 192 | +at that in the next tutorial. |
| 193 | + |
| 194 | +What else can you do with Python and Lambda? Take a look at the |
| 195 | +[AWS Lambda](/aws-lambda.html) page for more examples and tutorials. |
| 196 | + |
| 197 | +Questions? Contact me via Twitter |
| 198 | +[@fullstackpython](https://twitter.com/fullstackpython) |
| 199 | +or [@mattmakai](https://twitter.com/mattmakai). I am also on GitHub with |
| 200 | +the username [mattmakai](https://github.com/mattmakai). |
| 201 | + |
| 202 | +Something wrong with this post? Fork |
| 203 | +[this page's source on GitHub](https://github.com/mattmakai/fullstackpython.com/blob/master/content/posts/170428-python-2-7-aws-lambda.markdown). |
| 204 | + |
0 commit comments