All Products
Search
Document Center

Function Compute:Access an ApsaraDB for MongoDB database

Last Updated:Jun 18, 2024

This topic provides guidance on implementing access to an ApsaraDB for MongoDB database from Function Compute over a virtual private cloud (VPC). Specifically, you can configure VPC-related settings in a function and a whitelist in the database to access the ApsaraDB for MongoDB database and perform related operations. In this topic, Serverless Devs is used to deploy a function to access an ApsaraDB for MongoDB database in the Python 3 runtime.

Before you start

Procedure

  1. Install Serverless Devs and Docker and configure the AccessKey information.

  2. Run the following command to initialize a project.

    sudo s init

    In the CLI, specify Alibaba Cloud as the vendor, specify the quick start mode, and select a built-in Python runtime. Configure the project name and the region where the project is deployed. In this example, the start-fc-mongodb-python project is deployed in the China (Hangzhou) region.

  3. Run the following command to go to the project directory.

    cd start-fc-mongodb-python
  4. Modify the directory file based on your own business requirements.

    • Edit the s.yaml file. Example:

      edition: 3.0.0
      name: hello-world-app
      access: "default"
      
      vars: # The global variables.
        region: "cn-hangzhou"
      
      resources:
        hello_world:
          component: fc3 # The component name.
          # actions:       # The custom execution logic. For more information about actions, visit https://docs.serverless-devs.com/serverless-devs/yaml#%E8%A1%8C%E4%B8%BA%E6%8F%8F%E8%BF%B0actions.
          props:
            region: ${vars.region}              # For information about how to use variables, visit https://docs.serverless-devs.com/serverless-devs/yaml#%E5%8F%98%E9%87%8F%E8%B5%8B%E5%80%BC.
            functionName: "start-python-xbk4"
            description: 'hello world by serverless devs'
            runtime: "python3.9"
            code: ./code
            handler: index.handler
            memorySize: 128
            timeout: 30
            internetAccess: true
            vpcConfig:
             vpcId: vpc-bp11y195luy47h8cm**** # The ID of the VPC in which the database instance resides.
             securityGroupId: sg-bp1el3hto8hhkdup**** # The ID of the security group.
             vSwitchIds: 
              - vsw-bp18vwna9x79koh3q**** # Make sure that the CIDR block of the vSwitch is added to the whitelist of the database instance. 
            environmentVariables:      
             MONGO_DATABASE: test-db # The name of the database.
             MONGO_URL: mongodb://username:password@d-bp1b05cac9df0dd****.mongodb.rds.aliyuncs.com:37**  # The endpoint of the database. In the code, username and password indicate the username and password of the account that is used to connect to the database. If the username and password contain special characters, you must escape them in accordance with RFC 3986.
             
      Important

      Make sure that the CIDR block of the vSwitch that you configure for the function is added to the whitelist of the database instance. For more information, see Configure an IP address whitelist for the database.

    • Edit the index.py file. The following code provides an example. The code logic is to insert a piece of document data into the fc-col collection of the test-db database.

      # -*- coding: utf-8 -*-
      import os
      from pymongo import MongoClient   # You need to install the pymongo library first.
      
      
      def handler(event, context):
          dbName = os.environ['MONGO_DATABASE']
          url = os.environ['MONGO_URL']
      
          client = MongoClient(url)
      
          col = client[dbName]['fc_col']
          col.insert_one(dict(DEMO="FC", MSG="Hello FunctionCompute For MongoDB"))
          doc = col.find_one(dict(DEMO="FC"))
          print('find documents:' + str(doc))
          return str(doc)
  5. Run the following command to build a project.

    sudo s build --use-docker
  6. Run the following command to deploy the project.

    sudo s deploy -y
  7. Run the following command to invoke the function.

    sudo s invoke -e "{}"

    The following code snippet shows the expected output. The returned result indicates that a data record has been successfully inserted into the ApsaraDB for MongoDB database.

    ========= FC invoke Logs begin =========
    FC Invoke Start RequestId: 1-65d30578-1586adb3-4d0f099c1ada
    find documents:{'_id': ObjectId('65d2faef467c916ed6401a73'), 'DEMO': 'FC', 'MSG': 'Hello FunctionCompute For MongoDB'}
    FC Invoke End RequestId: 1-65d30578-1586adb3-4d0f099c1ada
    
    Duration: 161.75 ms, Billed Duration: 162 ms, Memory Size: 256 MB, Max Memory Used: 34.44 MB
    ========= FC invoke Logs end =========
    
    FC Invoke instanceId: c-65d304d7-15f440b6-20443f00e921
    
    FC Invoke Result:
    {'_id': ObjectId('65d2faef467c916ed6401a73'), 'DEMO': 'FC', 'MSG': 'Hello FunctionCompute For MongoDB'}
    
    
    End of method: invoke

Configure an IP address whitelist for the database

Important

Use an IP address whitelist to authorize functions to access the database. Do not use the security group mode. Otherwise, functions may occasionally fail to connect to the database, which affects the businesses.

A sharded cluster instance is used as an example.

  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 desired whitelist group, click the 更多 icon in the Actions column. In the drop-down menu, choose Manually Modify.

  7. In 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.

More information