In Function Compute, you can use a function to call database APIs to insert or query data. In most cases, instance status is not shared among different execution environments in Function Compute. If you want to share instance status, you need to store structured data in a database. This topic describes how to deploy a function to access an ApsaraDB for MongoDB database by using Serverless Devs. Python 3 is used in this topic.

Prerequisites

  • An ApsaraDB for MongoDB database instance is created.
    Important
    • Make sure that the database instance that you create is in the same region as the function that needs to access the database instance.

    • We recommend that you create the database instance in a zone that Function Compute supports. For more information about the message routing feature, see Zones where Function Compute is available.

      If your database instance is not deployed in a zone that is supported by Function Compute, create a vSwitch in your VPC. The vSwitch must be in the same zone as Function Compute. In addition, you must specify the vSwitch ID in the VPC configuration of the specified service in Function Compute. vSwitches in the same VPC can communicate with each other over the private network. Therefore, Function Compute can use the vSwitch to access resources in VPCs that reside in other zones. For more information, see How can I resolve the "vSwitch is in unsupported zone" error?.

  • A database named test-db and a database collection named fc_col are created.

    In this example, the s init command is used to insert a document data entry into the fc-col collection of the test-db database. The value of the MONGO_DATABASE parameter is test-db.

Step 1: Configure the IP address whitelist for the database

We recommend that you use an IP address whitelist, instead of a security group, for secure access. Otherwise, the function connection may be unstable, which affects your business.

Note In this topic, a sharded cluster instance is used. For information about how to add an IP address to the whitelist, see Configure a whitelist or an ECS security group for an ApsaraDB for MongoDB instance.
  1. Log on to the ApsaraDB for MongoDB console.
  2. In the top navigation bar, select a region.
  3. In the left-side navigation pane, click Sharded Cluster Instances.
  4. On the Sharded Cluster Instances page, click the name of the desired cluster.
  5. In the left-side navigation pane, choose Data Security > Whitelist Settings.
  6. On the Whitelist Settings page, find the whitelist group, click the More icon in the Actions column, and select Manually Modify from the drop-down list.
  7. On the Manually Modify panel, enter an IP address and click OK.
    Important You must specify an IP address that belongs to the CIDR block of the vSwitch that you add when you configure the network for Function Compute.

Step 2: Deploy and debug the function

  1. Install Serverless Devs and Docker and add a key.
    For more information, see Install Serverless Devs and Docker and Add a key.
  2. Initialize a project.
    s init start-fc-mongodb-python -d start-fc-mongodb-python
  3. Access the project.
    cd start-fc-mongodb-python
  4. Edit the s.yaml file.

    The following sample code provides a configuration example:

    edition: 1.0.0
    name: fcDeployApp
    access: "default"
    
    services:
      fc-db-mongodb-python:
        component: devsapp/fc
        props:
          region: cn-hangzhou
          service:
            name: fc-db-demo
            description: 'demo for fc visit db'
            internetAccess: true
            vpcConfig:
              vpcId: vpc-bp1hcg467ekqsv0zr**** # The ID of the virtual private cloud (VPC) in which the database instance resides. 
              securityGroupId: sg-bp1j6knvj40yjn0g**** # The ID of the security group. 
              vswitchIds:
                - vsw-bp1lgecrqfslgji9b**** # Make sure that the CIDR block of the vSwitch is added to the whitelist of the database instance. 
          function:
            name: mongodb
            description: visit mongodb
            runtime: python3
            codeUri: ./code
            handler: index.handler
            memorySize: 256
            timeout: 60
            environmentVariables:
              MONGO_DATABASE: test-db # The name of the database. 
              MONGO_URL: mongodb://m****:Hang****@s-bp1a2d6c391e****.mongodb.rds.aliyuncs.com:37** # The endpoint of the database. 
  5. Run the following command to build the project:
    s build --use-docker
  6. Run the following command to deploy the project:
    s deploy -y
  7. Run the following command to invoke a function:
    s invoke -e "{}"

    Expected command output:

    [2021-09-22T22:25:58.139] [INFO ] [S-CLI] - Start ...
    ========= FC invoke Logs begin =========
    FC Invoke Start RequestId: b361814a-0a70-4511-8212-6739389d3ca4
    find documents:{'_id': ObjectId('614b3ccea90d5fbfc262e918'), 'DEMO': 'FC', 'MSG': 'Hello FunctionCompute For MongoDB'}
    FC Invoke End RequestId: b361814a-0a70-4511-8212-6739389d3ca4
    
    Duration: 61.27 ms, Billed Duration: 62 ms, Memory Size: 256 MB, Max Memory Used: 51.21 MB
    ========= FC invoke Logs end =========
    
    FC Invoke Result:
    {'_id': ObjectId('614b3ccea90d5fbfc262e918'), 'DEMO': 'FC', 'MSG': 'Hello FunctionCompute For MongoDB'}
    
    
    End of method: invoke

Sample code

Access a MongoDB database in a Python runtime of Function Compute