Deploy a Function Compute function that connects to a Tair (Redis OSS-compatible) instance over a virtual private cloud (VPC). This guide uses Serverless Devs to deploy a Python 3 function that reads and increments a counter stored in Tair.
Prerequisites
Before you begin, make sure that you have:
An Alibaba Cloud account with Function Compute activated
Serverless Devs and Docker installed, with your AccessKey pair configured
A Tair (Redis OSS-compatible) instance created and running
A VPC with at least one vSwitch and one security group
The Tair instance and the Function Compute function must be in the same region. Create the Tair instance in a zone that Function Compute supports. If the instance is in an unsupported zone, create a vSwitch in a supported zone within the same VPC. vSwitches in the same VPC can communicate over the private network, so Function Compute can still reach the instance. For details, see How can I resolve the "vSwitch is in unsupported zone" error?
Configure an IP address whitelist
Before you deploy the function, add the vSwitch CIDR block to the Tair instance whitelist so that Function Compute can access the instance.
Use an IP address whitelist to authorize Function Compute to access the Tair instance. Do not use the security group mode. The security group mode may cause intermittent connection failures.
Log on to the Tair console.
In the top navigation bar, select the region where the instance is deployed.
On the Instances page, find the instance and click its ID.
In the left-side navigation pane, click Whitelist Settings. On the Whitelist Settings tab, find the whitelist to modify and click Modify in the Actions column.
In the Modify Whitelist panel, enter the CIDR block of the vSwitch in the Whitelist field and click OK.
Procedure
Step 1: Initialize the project
Run the following command to initialize a project:
sudo s initIn the CLI prompts:
Select Alibaba Cloud as the vendor.
Choose the quick start mode.
Select a built-in Python runtime.
Specify the project name and region. This guide uses the
start-fc-redis-pythonproject in the China (Hangzhou) region.
Navigate to the project directory:
cd start-fc-redis-pythonStep 2: Configure the project files
Edit s.yaml
Edit the s.yaml file with the following configuration. Update the placeholder values with your actual VPC, security group, vSwitch, and Tair instance details.
edition: 1.0.0
name: fcDeployApp
access: "default"
services:
fc-db-redis-python:
component: devsapp/fc
props:
region: cn-hangzhou
service:
name: fc-db-demo
description: 'demo for fc visit db'
internetAccess: true
vpcConfig:
vpcId: vpc-bp1oeg1fwxzuxcliq**** # VPC ID where the Tair instance resides
securityGroupId: sg-bp164seaxj7wc4d0**** # Security group ID
vswitchIds:
- vsw-bp1192npo1ziqzw4**** # vSwitch ID (add its CIDR block to the Tair whitelist)
function:
name: redis
description: visit redis
runtime: python3
codeUri: ./code
handler: index.handler
memorySize: 256
timeout: 30
initializationTimeout: 60
initializer: index.initializer
environmentVariables:
REDIS_HOST: r-bp1h2g53l3thqg****.redis.rds.aliyuncs.com # Private endpoint of the Tair instance
REDIS_PASSWORD: **** # Tair instance password
REDIS_PORT: 63** # Private port of the Tair instanceReplace the following placeholders with your actual values:
| Placeholder | Description | Example |
|---|---|---|
vpc-bp1oeg1fwxzuxcliq**** | VPC ID where the Tair instance resides | vpc-bp1oeg1fwxzuxcliq1234 |
sg-bp164seaxj7wc4d0**** | Security group ID | sg-bp164seaxj7wc4d01234 |
vsw-bp1192npo1ziqzw4**** | vSwitch ID | vsw-bp1192npo1ziqzw41234 |
r-bp1h2g53l3thqg****.redis.rds.aliyuncs.com | Private endpoint of the Tair instance | r-bp1h2g53l3thqg1234.redis.rds.aliyuncs.com |
**** (REDIS_PASSWORD) | Password for the Tair instance | Your password |
63** | Private port of the Tair instance | 6379 |
Edit the index.py code file
The function reads the counter key from the Tair instance, increments it by 1, writes the new value back, and returns the previous value.
# -*- coding: utf-8 -*-
import os
import redis
# Global connection pool, reused across function invocations to reduce latency
conn_pool = None
def initializer(context):
"""Initialize a Redis connection pool using environment variables."""
global conn_pool
conn_pool = redis.ConnectionPool(
host=os.environ['REDIS_HOST'],
password=os.environ['REDIS_PASSWORD'],
port=os.environ['REDIS_PORT'],
db=1,
decode_responses=True
)
def handler(event, context):
"""Read, increment, and write back a counter value in Tair."""
global conn_pool
r = redis.Redis(connection_pool=conn_pool)
counter = r.get('counter')
if counter is None:
counter = 0
else:
counter = int(counter)
print('counter: ' + str(counter))
r.set('counter', str(counter + 1))
return counterThe redis Python library is a third-party dependency. Build the project with Docker in the next step to bundle it automatically. For other dependency management options, see Install a third-party dependency for a function.
Step 3: Build and deploy
Build the project:
sudo s build --use-dockerDeploy the project:
sudo s deploy -yStep 4: Invoke and verify the function
sudo s invoke -e "{}"Expected output:
[2021-09-14T17:08:50.875] [INFO ] [S-CLI] - Start ...
========= FC invoke Logs begin =========
FC Initialize Start RequestId: ccd73383-048d-4c8d-834e-93da59b86a21
FC Initialize End RequestId: ccd73383-048d-4c8d-834e-93da59b86a21
FC Invoke Start RequestId: eccafc0a-493e-4f3e-9afa-45c0b84a2c0f
counter: 0
FC Invoke End RequestId: eccafc0a-493e-4f3e-9afa-45c0b84a2c0f
Duration: 27.51 ms, Billed Duration: 28 ms, Memory Size: 256 MB, Max Memory Used: 34.05 MB
========= FC invoke Logs end =========
FC Invoke Result:
0
End of method: invokeThe returned value starts at 0 and increments with each invocation, confirming that the function reads and writes the counter key in the Tair instance. Run the invoke command multiple times to verify that the counter increments correctly: 0, 1, 2, and so on.
Troubleshooting
Connection timeout
Symptom: The function times out without returning a result.
Causes and solutions:
VPC misconfiguration: Verify that the
vpcId,securityGroupId, andvswitchIdsins.yamlare correct and belong to the same VPC as the Tair instance.Whitelist not configured: Confirm that the vSwitch CIDR block is added to the Tair instance whitelist. See Configure an IP address whitelist.
vSwitch in an unsupported zone: Create a vSwitch in a zone that Function Compute supports. See How can I resolve the "vSwitch is in unsupported zone" error?
Authentication failure
Symptom: The function returns a NOAUTH Authentication required, ERR invalid password, or WRONGPASS invalid username-password pair error.
Causes and solutions:
Incorrect password: Check the
REDIS_PASSWORDenvironment variable ins.yaml.Incorrect host or port: Verify that
REDIS_HOSTandREDIS_PORTmatch the private endpoint and port shown in the Tair console.
Dependency errors
Symptom: The function returns a ModuleNotFoundError: No module named 'redis' error.
Solution: Build the project with Docker before deploying:
sudo s build --use-docker
sudo s deploy -yFor more troubleshooting guidance, see Common errors and troubleshooting and How to troubleshoot database access failures?
Clean up resources
To avoid ongoing charges, delete the resources created in this guide:
Remove the deployed function and service:
sudo s remove -yIf the Tair instance was created for this tutorial only, release it in the Tair console.
If the VPC, vSwitch, or security group was created for this tutorial only, delete them in the VPC console.
References
Configure network settings -- view vSwitch details and CIDR blocks for Function Compute