In Function Compute, you can use a function to call the ApsaraDB for MongoDB API to perform operations such as insert and query on an ApsaraDB for MongoDB instance. In normal cases, states cannot be shared among different execution environments in Function Compute. You can persist structured data in a database so that states can be shared. This topic describes how to use FunCraft to deploy a function to access an ApsaraDB for MongoDB database.


  1. You have created a virtual private cloud (VPC) and a VSwitch.

    The VSwitch must belong to a zone supported by Function Compute. For more information about the zones supported by Function Compute, see VPC access.

  2. An ApsaraDB for MongoDB instance that meets your business needs has been created.

    You have created a database instance in same VPC as Function Compute. You do not need to create the VSwitch in the same zone as Function Compute. VSwitches under the same VPC can communicate with each other even when they are in different zones.

  3. A whitelist has been configured.

    If you need to control access to databases by using an IP address whitelist, ensure that you have entered the internal Classless Inter-Domain Routing (CIDR) blocks of the target VPCs in the IP field. To find the CIDR block of a VPC, log on to the VPC console and view the VPC Details page.

  4. Create a security group

    You have configured the security group to allow outbound traffic from the internal CIDR block and port of the database.

Write a function

The following section describes how to use Funcraft to write a function that accesses a database. The sample code is written in Python 3.

  1. On the local machine, create a directory to store code and dependent modules. In the directory, create the template.yml file. In this example, the /tmp/code/template.yml file is created and contains the following content:
    ROSTemplateFormatVersion: '2015-09-01'
    Transform: 'Aliyun::Serverless-2018-04-03'
        Type: 'Aliyun::Serverless::Service'
          Description: This is MongoDB service
            - AliyunECSNetworkInterfaceManagementAccess
            VpcId: vpc-XXXX
              - vsw-XXX
            SecurityGroupId: sg-XXXX
          InternetAccess: true
          Type: 'Aliyun::Serverless::Function'
            Handler: 'index.handler'
            Runtime: python3
            Timeout: 10
            MemorySize: 128
            CodeUri: '. /'     

    The following list describes the main parameters:

    • A service named service is declared.
      • Policies: grants Function Compute permission to manage elastic network interfaces (ENIs) attached to Elastic Compute Service (ECS) instances. Function Compute can then access resources in the VPC.
      • VpcConfig: binds the VPC to the service. You must replace the following values with the information for your VPC.
        • VpcId: the ID of the VPC.
        • VSwitchId: the ID of the VSwitch.
        • SecurityGroupId: the ID of the security group.
    • A service named service is declared.
      • Initializer: the initializer function. For more information, see Initializer function.
      • Handler: the function handler. For more information, see Function entry point.
      • Runtime: the runtime environment of the function.
      • CodeUri: the directory where the code package is located.

        During function deployment, Funcraft packages and uploads the specified folders or files under the CodeUri directory.

  2. In the directory that contains the template.yml file, create the Funfile file. In this example, the new file contains the following sample content:
    RUNTIME python3
    RUN fun-install pip install pymongo                    
  3. Run the fun install command to install dependencies.
    fun install
    When the code editor shows the following content, the dependencies have been installed.
    Install Success
  4. In the directory that contains the template.yml file, create a Python file. In this example, the /tmp/code/ file is created and contains the following sample content:
        # -*- coding: utf-8 -*-
    import uuid
    from pymongo import MongoClient
    def handler(event, context):
            CONN_ADDR1 = ''
            CONN_ADDR2 = ''
            REPLICAT_SET = 'XXX'
            username = 'XXX'
            password = 'XXXX'
            # Obtain the MongoClient.
            client = MongoClient([CONN_ADDR1, CONN_ADDR2], replicaSet=REPLICAT_SET)
            # Grant the user the administrator permissions to access the database.
            client.admin.authenticate(username, password)
            # Use the collection:testColl of the test database as an example. Insert doc and search for documents based on the demo name.
            demo_name = 'python-' + str(uuid.uuid1())
            print ('demo_name:'+ demo_name)
            doc = dict(DEMO=demo_name, MESG="Hello ApsaraDB For MongoDB")
            doc_id = client.test.testColl.insert(doc)
            for d in client.test.testColl.find(dict(DEMO=demo_name)):
                print ('find documents:'+ str(d))
            return 'success'
  5. Run the following command to deploy the function to Function Compute by using Funcraft:
    fun deploy
    When the code editor shows the following content, the function has been deployed.
            function <function-name> deploy success
    service <service-name> deploy success

    After the deployment is complete, log on to the Function Compute console and click Service/Function. On the page that appears, you can see the newly deployed service and function.

Debug the function

After the function is deployed, you can debug the function in the Function Compute console.

  1. Log on to the Function Compute console.
  2. In the top navigation bar, select your region.
  3. In the left-side navigation pane, click Service/Function.
  4. Find the target function in the target service and click the name of the function.
  5. On the page that appears, click the Code tab. On this tab, click Invoke.
    After the execution is complete, you can view the execution results and logs. DB-log