Step 2.1: Create the deployment package
Currently the example code for the Lambda function is only supplied in Python.
Python
The following example Python code reads and writes an item to your ElastiCache cluster.
Copy the code and save it into a file named app.py
. Be sure to replace the elasticache_config_endpoint
value in
the code with the endpoint address you copied in step 1.
import uuid import ssl from pymemcache.client.base import Client elasticache_config_endpoint = "
serverlesscacheforlambda-ces85m.serverless.use1.cache.amazonaws.com
" target_port = 11211 context = ssl.create_default_context() memcached_client = Client((elasticache_config_endpoint, target_port), tls_context=context) def lambda_handler(event, context): # create a random UUID - this will be the sample element we add to the cache uuid_in = uuid.uuid4().hex # put the UUID to the cache memcached_client.set("uuid", uuid_in, expire=500, noreply=False) # get the item (UUID) from the cache result = memcached_client.get("uuid") decoded_result = result.decode("utf-8") # check the retrieved item matches the item added to the cache and print # the results if decoded_result == uuid_in: print(f"Success: Inserted {uuid_in}. Fetched {decoded_result} from Memcached.") else: raise Exception(f"Bad value retrieved. Expected {uuid_in}, got {decoded_result}") return "Fetched value from Memcached"
This code uses the Python pymemcache
pymemcache
, carry out the following
steps.
-
In your project directory containing the
app.py
source code file, create a folderpackage
to install thepymemacache
library into.mkdir package
-
Install
pymemcache
using pip.pip install --target ./package pymemcache
-
Create a .zip file containing the
pymemcache
library. In Linux and macOS, run the following command. In Windows, use your preferred zip utility to create a .zip file with thepymemache
library at the root.cd package zip -r ../my_deployment_package.zip .
-
Add your function code to the .zip file. In Linux and macOS, run the following command. In Windows, use your preferred zip utility to add
app.py
to the root of your .zip file.cd .. zip my_deployment_package.zip app.py
Next Step
Step 2.2: Create the IAM role (execution role)