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 RDS for PostgreSQL database by using Serverless Devs. Python 3 is used in this topic

Prerequisites

  • Create an ApsaraDB RDS for PostgreSQL instance
    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?.

  • Create a table named COMPANY and insert the ID, NAME, AGE, ADDRESS, and SALARY columns into the table.

    In this example, you can use the s init command to insert a data record into the COMPANY table, in which the ID, NAME, AGE, ADDRESS, and SALARY columns are inserted. You must create the table and the columns in advance.

  • Install Serverless Devs and Docker
  • Configure Serverless Devs
  • Create a security group

    Create a default security group in the VPC where the database instance is deployed. If you want to use an existing security group, make sure that the security group allows outbound traffic to the ports and private CIDR blocks of the database instance. By default, the security group allows all outbound traffic.

Configure an IP address whitelist for a database

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

  1. Log on to the ApsaraDB RDS console.
  2. In the left-side navigation pane, click Instances.
  3. In the top navigation bar, select a region.
  4. On the Instances page, find the desired instance and click the instance ID.
  5. In the left-side navigation pane, click Data Security.
  6. On the Whitelist Settings tab that appears, find the default whitelist group and click Modify.
  7. In the Edit Whitelist dialog box, configure IP Addresses 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.

Deploy and invoke a function

  1. Initialize a project.
    s init start-fc-postgresql-python -d start-fc-postgresql-python
  2. Access the project.
    cd start-fc-postgresql-python
  3. Edit the s.yaml file.

    The following sample code provides a configuration example:

    edition: 1.0.0         
    name: fcDeployApp       
    access: "default"  
    
    services:
      fc-db-postgresql-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: postgresql
            description: visit postgresql
            runtime: python3
            codeUri: ./code
            handler: index.handler
            memorySize: 256
            timeout: 30
            environmentVariables:
              DATABASE: post**** # The name of the database. 
              HOST: pgm-bp1n6g63x0xdb7oy16****.pg.rds.aliyuncs.com # The endpoint of the database. 
              PORT: 19** # The port of the database. 
              USER: ni**** # The username of the database. 
              PASSWORD: Hang**** # The password of the database. 
  4. Run the following command to build the project:
    s build --use-docker
  5. Run the following command to deploy the project:
    s deploy -y
  6. Run the following command to invoke a function:
    s invoke -e "{}"

    Expected command output:

    [2021-09-23T11:03:17.792] [INFO ] [S-CLI] - Start ...
    ========= FC invoke Logs begin =========
    FC Invoke Start RequestId: 7e6657d4-504a-4faa-8f59-5464df73aa65
    FC Invoke End RequestId: 7e6657d4-504a-4faa-8f59-5464df73aa65
    
    Duration: 101.87 ms, Billed Duration: 102 ms, Memory Size: 256 MB, Max Memory Used: 35.08 MB
    ========= FC invoke Logs end =========
    
    FC Invoke Result:
    successfully
    
    
    End of method: invoke