Help Center/ Cloud Certificate Manager/ Best Practices/ Best Practices for SSL Certificate Manager/ Using FunctionGraph to Automatically Obtain and Update ECS Server Certificates
Updated on 2023-11-21 GMT+08:00

Using FunctionGraph to Automatically Obtain and Update ECS Server Certificates

Scenario

This topic illustrates how to use FunctionGraph to automatically obtain and update an ECS server certificate. For server information, see Table 1. This approach helps you update new certificates issued upon renewals for your ECSs. The entire process requires no manual operations.

Table 1 Example

Server Type

Nginx

Programming Language

Python 3.9

Notes and Constraints

  • You have enabled an Elastic Cloud Server (ECS) and installed an SSL certificate on the ECS.
  • Your SSL certificate has been purchased and renewed through CCM.

Step 1: Creating an Agency

To use FunctionGraph to update the ECS server certificate, you need to grant the SCM FullAccess and IAM ReadOnlyAccess permissions to FunctionGraph.

  1. Log in to the management console.
  2. Click in the upper left corner of the page and choose Management & Governance > Identity and Access Management.
  3. In the navigation pane on the left, choose Agencies. In the upper right corner of the Agencies page, click Create Agency.
  4. On the Create Agency page, set the agency information by referring to Table 2.

    Figure 1 Create Agency
    Table 2 Parameters for creating an agency

    Parameter

    Description

    Agency Name

    User-defined agency name.

    Agency Type

    Select Cloud service.

    Cloud Service

    Choose FunctionGraph.

    Validity Period

    Select Unlimited.

    Description

    This parameter is optional. You can customize the required information.

  5. Click Next.
  6. Select the SCM FullAccess and IAM ReadOnlyAccess permissions you want to grant to FunctionGraph.

    Figure 2 Selecting permissions

  7. Click Next to set the permission scope.
  8. Click OK.

Step 2. Create a Function from Scratch

  1. Log in to the management console.
  2. Click in the upper left corner of the page and choose Compute > FunctionGraph.
  3. Click Create in the upper right corner of the Functions area.
  4. Create a function by referring to Table 3.

    Figure 3 Creating a function from scratch
    Table 3 Parameters for creating a function from scratch

    Parameter

    Description

    Function Type

    Select Event Function.

    Region

    Select a region where you will deploy your code.

    Function Name

    Name of the custom function.

    Agency

    Select the agency you created in Step 1: Creating an Agency.

    Enterprise Project

    If you have enabled the enterprise project function, select the enterprise project to which you want to add a function.

    If you have not enabled the enterprise project function yet, the parameter will not be displayed. You can enable this function by referring to Enabling the Enterprise Project Function if necessary.

    Runtime

    Select a language for the function. In this example, Python 3.9 is selected.

  5. Click Create. The Functions page is displayed, and an empty function is created.

Step 3: Create a Timer Trigger

Create a timer trigger to trigger a function at a fixed interval.

  1. On the displayed page, choose Configuration > Triggers.
  2. Click Create Trigger and set the parameters by referring to Table 4.

    Figure 4 Create Trigger
    Table 4 Parameters for setting a timer trigger

    Parameter

    Description

    Trigger Type

    Select Timer.

    Timer Name

    Customize a name.

    Rule

    Select Fixed rate and set a value to it based on your needs.

    Enable Trigger

    Additional Information

    This parameter is optional. You can enter anything for the trigger.

  3. Click OK.

Step 4: Create and Configure a Function Dependency

The function code for deploying a certificate to an ECS depends on paramiko. You need to create and configure the paramiko dependency for the function.

This section uses Python 3.9 as an example to describe how to create and configure a dependency for a function. For details about how to create a dependency package in other languages, see How Do I Create Dependencies?

Creating a Dependency for a Python Function

  1. The Python version in the environment must be the same as the runtime version of the corresponding function.

    For example, Python 3.9.0 or later is recommended for Python 3.9, Python 2.7.12 or later is recommended for Python 2.7, and Python 3.6.3 or later is recommended for Python 3.6.

  2. Install the paramiko dependency package for Python 3.9 and specify the local installation path of the dependency package to /tmp/paramiko:

    pip install paramiko --root /tmp/paramiko

  3. Switch to the /tmp/paramiko directory:

    cd /tmp/paramiko/

  4. Go to the site-packages directory (generally, usr/lib64/python3.9/site-packages/) and then run the following command:

    zip -rq paramiko.zip *

    The generated package is the required dependency package.

    To install the local wheel installation package, run the following command:

    pip install piexif-1.1.0b0-py2.py3-none-any.whl --root /tmp/piexif
    //Replace piexif-1.1.0b0-py2.py3-none-any.whl with the actual installation package name.

Configuring the Dependency Package

  1. Log in to the management console.
  2. Click in the upper left corner of the page and choose Compute > FunctionGraph.
  3. In the navigation pane on the left, choose Functions > Dependencies.
  4. Click Create Dependency. In the Create Dependency pane sliding out from the left, set details by referring to Configuring a dependency package.

    Table 5 Configuring a dependency package

    Parameter

    Description

    Name

    Dependency name, which is used to identify different packages.

    Code Entry Mode

    Select Upload ZIP.

    Upload File

    Select the dependency .zip file.

    Runtime

    Select the function language. In this example, Python 3.9 is selected.

    Description

    Description of the dependency. This parameter is optional.

  5. Click OK.
  6. In the navigation pane on the left, choose Functions > Function List.
  7. Click the name of the desired function.
  8. On the displayed function details page, click the Code tab, click Add in the Dependencies area.
  9. Select the private dependency package created in 8 and click OK.

Step 5: Configure a Code Source in a Function

The following shows how to configure function code online. For more details, see Creating a Deployment Package.

  1. In the navigation pane on the left, choose Functions > Function List.
  2. Click the name of the desired function.
  3. Choose Configuration > Environment Variables.
  4. Click Add and configure variables endpoint and region, as shown in Figure 5.

    Figure 5 Setting Environment Variables
    Environment variable 1:
    • Key: endpoint
    • Value: scm.ap-southeast-1.myhuaweicloud.com

    Environment variable 2:

    • Key: region
    • Value: ap-southeast-1

  5. Click Save and click the Code tab.
  6. On the Code tab page, integrate the following two pieces of code and add them to a code source file.

    Figure 6 Adding code

    The following is an example of the application code for obtaining the SSL certificate of the current account:

    import json
    import requests
    import datetime
    import time
    
    def getCertHeaders(context):
        return {
            'Content-Type': 'application/json',
            'region': context.getUserData("region"),
            'X-Language': 'en-us',
            'X-Auth-Token': context.getToken()
        }
    
    def isValidCert(cert):
    # TODO can be customized based on service scenarios. The following is only an example.
        certDomain = cert.get('domain')
    
    # Check whether the certificate is a renewal certificate used for the corresponding domain name.
        if (certDomain != 'XXXX'):
            return False
    
    # The following instance sorts the certificates that were issued yesterday and whose domain names meet the requirements.
        currentTime = time.localtime()
        currentTimeStr = str(currentTime[0]) + ',' + str(currentTime[1]) + ','  + str(currentTime[2])
    
        certTime = datetime.datetime.strptime(cert.get('expire_time'), '%Y-%m-%d %H:%M:%S.%f')
    
    # Obtain the certificate issuing time.
        certTimeStr = str(certTime.year - int(cert.get('validity_period')/12)) + ',' + str(certTime.month) + ','  + str(certTime.day - 1)
        return currentTimeStr == certTimeStr
    
    def getCertList(context):
        preUrl = 'https://' + context.getUserData("endpoint")
        url = preUrl + '/v3/scm/certificates?order_status=ISSUED&content=&sort_key=certUpdateTime&sort_dir=DESC&limit=&enterprise_project_id='
        certHeaders = getCertHeaders(context)
    
        rep = requests.get(url, headers = certHeaders)
        totalCount = json.loads(rep.text).get('total_count')
        discuss = int(totalCount/10)
        reminder = totalCount-discuss*10
        rep = []
        for i in range(discuss):
            tempUrl = url + '&offset=' + str(10*i)
            tempRep = requests.get(tempUrl, headers = certHeaders)
            for cert in json.loads(tempRep.text).get('certificates'):
                if(isValidCert(cert)):
                    rep.append(cert)
        if reminder > 0:
            tempUrl = url + '&offset=' + str(totalCount-reminder)
            tempRep = requests.get(tempUrl, headers = certHeaders)
            for cert in json.loads(tempRep.text).get('certificates'):
                if(isValidCert(cert)):
                    rep.append(cert)     
        return json.dumps(rep)
    
    
    def exportCert(context, certId):
        preUrl = 'https://' + context.getUserData("endpoint")
        url = '/v3/scm/certificates/'+ certId + '/export'
        rep = requests.post(preUrl + url, headers = getCertHeaders(context))
        os.makedirs("/tmp/" + certId)
        entireCertificate = json.loads(rep.text).get('entire_certificate')
        entireCertFileName = '/tmp/' + certId + '/certificate.pem'
        certFile = open(entireCertFileName,'w')
        certFile.write(entireCertificate)
        privateKey = json.loads(rep.text).get('private_key')
        privateKeyFileName = '/tmp/' + certId + '/privateKey.key'
        keyFile = open(privateKeyFileName,'w')
        keyFile.write(privateKey)
    
    
    def handler (event, context):
    # TODO needs to be invoked by the function based on the service background. The following example is for reference only.
        totalRep = getCertList(context)
        certList = json.loads(totalRep)
        certIdList = []
        for cert in certList:
            exportCert(context, cert.get("id"))
            certIdList.append(cert.get("id"))
        for cert in certList:
            deploy('**.***.*', 22, 'root', '*.', '/tmp', '/tmp', certIdList)

    The following is an example of the application code for deploying an SSL certificate to an ECS (Nginx):

    import os
    import paramiko
    import time
    
    def isExists(path, function):
        path = path.replace("\\","/")
        try:
            function(path)
        except Exception as error:
            return False
        else:
            return True
    
    
    def copy(ssh, sftp, local, remote):
        if isExists(remote, function=sftp.chdir):
            filename = os.path.basename(os.path.normpath(local))
            remote = os.path.join(remote, filename).replace("\\","/")
        if os.path.isdir(local):
            isExists(remote, function=sftp.mkdir)
            for file in os.listdir(local):
                localfile = os.path.join(local, file).replace("\\","/")
                copy(ssh=ssh, sftp=sftp, local=localfile, remote=remote)
        if os.path.isfile(local):
            try:
                ssh.exec_command("rm -rf %s"%(remote))
                sftp.put(local,remote)
            except Exception as error:
                print('put:', local, "==>",remote, 'FAILED')
            else:
                print('put:', local, "==>",remote, 'success')
    
    def deploy(ip, port, username, password, local, remote, certIdList):
        transport = paramiko.Transport((ip,port))
        transport.connect(username=username, password=password)
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh._transport = transport
        ftp_client = paramiko.SFTPClient.from_transport(transport)
    
        for certId in certIdList:
            copy(ssh=ssh, sftp=ftp_client, local=local + '/' + certId, remote=remote)
    
    #The prerequisite is that the certificate location has been written into the nginx.conf file.
        cmd="/usr/local/nginx/sbin/nginx -s reload"
        stdin,stdout,stderr = ssh.exec_command(cmd)
        ssh.close()
    • The preceding two pieces of code are examples. Modify them based on site requirements. XXXX in the code indicates the domain name. Replace it with the actual domain name.
    • The following functions involved in the example code need to be edited based on your service background. They must be placed at the end of the code source file:
      def handler (event, context):
      # TODO needs to be invoked by the function based on the service background.

  7. Click Test to test the function.

    For details, see Test Management.

  8. After the code source is added and tested, the function runs based on the triggering rule set by the timer trigger. If a renewal certificate is issued, the function automatically obtains the certificate and updates it to the ECS.
  9. On the function details page, choose Monitoring > Metrics to view the function running status.

    You can view metrics such as the Invocations, Duration, Errors, and Throttles. For details, see Function Monitoring.