This topic describes how to create an HTTPS listener for a Server Load Balancer (SLB) instance and update the server certificate that the HTTPS listener uses by using the Alibaba Cloud SDK for Python.

Prerequisites

Make sure that you have created two ECS instances in the China North 3 (Zhangjiakou) region and the two instances are in the Running state.

Background information

In this topic, the process for creating an HTTPS listener and then updating the server certificate is as follows:
  1. Create an SLB instance in China North 3 (Zhangjiakou), set its name to SLB1, set the primary zone to cn-zhangjiakou-a, set the backup zone to cn-zhangjiakou-b, set the billing method to Pay-As-You-Go, and set the specification to slb.s1.small. Use the default values for other parameters.
  2. Add the two ECS instances to the default server group of the created SLB instance and set the weight of both to 100.
  3. Upload the server certificate.
  4. Create an HTTPS listener. Set the frontend port to 80, set the backend port for receiving requests to 443, disable health checks and persistent sessions, and set the peak bandwidth to 6 Mbit/s. Use the default values for other parameters.
  5. Upload a new server certificate.
  6. Update the server certificate used by the created HTTPS listener.
  7. Delete the SLB instance.

Procedure

  1. From the downloaded SDK package, open the folder $aliyun-openapi-python-sdk-examples\sdk_examples\examples\slb.
  2. Open upload_server_certificate.py by using an editor. Set the user authentication parameter ACS_CLIENT and other parameters as needed, save the file, and exit.
    Note Because the identity of a user must be authenticated by the SDK, you can also set the AcsClient parameter in the constants file and call the constants file when needed.
    
    #encoding=utf-8
    """
    Create an SLB instance->Upload the server certificate->Create an HTTPS listener->Upload a new server certificate
    ->Modify the configurations of the HTTPS listener recursively
    """
    import sys
    import json
    import uuid
    
    #Call the AcsClient parameter for authentication.
    from aliyunsdkcore.client import AcsClient
    #Use the exception handling module of the Alibaba Cloud SDK.
    from aliyunsdkcore.acs_exception.exceptions import ServerException, ClientException
    #Call the API used to upload certificates.
    from aliyunsdkslb.request.v20140515 import UploadServerCertificateRequest
    #Call the API used to create an SLB instance.  
    from aliyunsdkslb.request.v20140515 import CreateLoadBalancerRequest
    #Call the API used to add a default server group.
    from aliyunsdkslb.request.v20140515 import AddBackendServersRequest
    #Call the API used to create an HTTPS listener.
    from aliyunsdkslb.request.v20140515 import CreateLoadBalancerHTTPSListenerRequest
    #Call the API used to modify the HTTPS listener.
    from aliyunsdkslb.request.v20140515 import SetLoadBalancerHTTPSListenerAttributeRequest
    #Call the API used to delete an SLB instance. 
    from aliyunsdkslb.request.v20140515 import DeleteLoadBalancerRequest
    #Handle exceptions.
    from sdk_lib.exception import ExceptionHandler
    #Redirect command line output.
    from sdk_lib.common_util import CommonUtil
    
    #Set the user authentication parameter.
    ACS_CLIENT = AcsClient(
        'your-access-key-id',     #your-access-key-id
        'your-access-key-secret',   #your-access-key-secret
        'cn-zhangjiakou',     #your-region-id
    )
    #The maximum number of retry times after a failture.
    TRY_TIME = 3
    
    def create_load_balancer(params):
        '''
        create_load_balancer:Create an SLB instance.
        For more information about APIs, go to https://www.alibabacloud.com/help/doc-detail/27577.htm?spm=a2c63.p38356.b99.137.1aad1093fJoHIT.
        '''
        try:
            #Set the API parameters for creating an SLB instance.
            request = CreateLoadBalancerRequest.CreateLoadBalancerRequest() 
            request.set_MasterZoneId(params["master_zone_id"]) 
            request.set_SlaveZoneId(params["slave_zone_id"]) 
            request.set_LoadBalancerName(params["load_balancer_name"]) 
            request.set_PayType(params["pay_balancer_type"])
            request.set_ClientToken(str(uuid.uuid1()))
            #Send the request and receive the response.
            response = ACS_CLIENT.do_action_with_exception(request)
            response_json = json.loads(response)
            #Return results.   
            return response_json
        except ServerException as e:
            ExceptionHandler.server_exception(e)
        except ClientException as e:
            ExceptionHandler.client_exception(e)
            
    def add_backend_servers(params):
        '''
        add_backend_servers:Add backend servers.
        For more information about APIs, go to https://www.alibabacloud.com/help/doc-detail/27632.htm?spm=a2c63.p38356.b99.168.585610938i4uFp.
        '''
        counter = 0
        while counter < TRY_TIME:
            try:
                #Set the API parameters for adding a default server group.
                request = AddBackendServersRequest.AddBackendServersRequest()
                #The ID of the SLB instance
                request.set_LoadBalancerId(params["load_balancer_id"])
                #A list of the backend servers to be added
                request.set_BackendServers(params["backend_servers"])
                request.set_ClientToken(str(uuid.uuid1()))
                #Send the request and receive the response.
                response = ACS_CLIENT.do_action_with_exception(request)
                response_json = json.loads(response)
                #Return results.
                return response_json
            except ServerException as e:
                if ExceptionHandler.server_exception(e):
                    return e
            except ClientException as e:
                if ExceptionHandler.client_exception(e):
                    return e
            finally:
                counter += 1
    
    def upload_server_certificate(params):
        '''
        upload_server_certificate:Upload the sever certificate.
        For more information about APIs, go to https://www.alibabacloud.com/help/doc-detail/34181.htm?spm=a2c63.p38356.b99.187.34b444c7BIGlRP.
        '''
        counter = 0
        while counter < TRY_TIME:
            try:
                request = UploadServerCertificateRequest.UploadServerCertificateRequest()
                #The public key certificte to be uploaded
                request.set_ServerCertificate(params["server_certificate"])
                #The private key to be uploaded
                request.set_PrivateKey(params["private_key"])
                #Send the API request and receive the response.
                response = ACS_CLIENT.do_action_with_exception(request)
                response_json = json.loads(response)
                #Return results.
                return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
            finally:
                counter += 1
    
    def create_https_listener(params):
        '''
        create_https_listener:Create an HTTPS listener.
        For more information about APIs, go to https://www.alibabacloud.com/help/doc-detail/27593.htm?spm=a2c63.p38356.b99.160.6b1035bekEoFQT.
        '''
        counter = 0
        while counter < TRY_TIME:
            try:
                request = CreateLoadBalancerHTTPSListenerRequest.CreateLoadBalancerHTTPSListenerRequest()
                #The ID of the SLB instance
                request.set_LoadBalancerId(params["load_balancer_id"])
                #The peak bandwidth of the listener
                request.set_Bandwidth(params["bandwidth"])
                #The frontend port of the SLB instance
                request.set_ListenerPort(params["listener_port"])
                #Whether to enable health checks
                request.set_HealthCheck(params["health_check"])
                #Whether to enable persistent sessions
                request.set_StickySession(params["sticky_session"])
                #The backend port of the SLB instance
                request.set_BackendServerPort(params["backend_server_port"])
                #The ID of the server certificate
                request.set_ServerCertificateId(params["server_certificate_id"])
                #Send the request and receive the response.
                response = ACS_CLIENT.do_action_with_exception(request)
                response_json = json.loads(response)
                #Return results.
                return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
            finally:
                counter += 1
    
    def set_https_listener_attribute(params):
        '''
        set_https_listener_attribute:Modify the configurations of the HTTPS listener.
        For more information about APIs, go to https://www.alibabacloud.com/help/doc-detail/27603.htm?spm=a2c63.p38356.b99.162.552914f5Cv076R.
        '''
        counter = 0
        while counter < TRY_TIME:
            try:
                request = SetLoadBalancerHTTPSListenerAttributeRequest.SetLoadBalancerHTTPSListenerAttributeRequest()
                #The ID of the SLB instance
                request.set_LoadBalancerId(params["load_balancer_id"])
                #The peak bandwidth of the listener
                request.set_Bandwidth(params["bandwidth"])
                #The frontend port of the SLB instance
                request.set_ListenerPort(params["listener_port"])
                #Whether to enable health checks
                request.set_HealthCheck(params["health_check"])
                #Whether to enable persistent sessions
                request.set_StickySession(params["sticky_session"])
                #The ID of the server certificate
                request.set_ServerCertificateId(params["server_certificate_id"])
                #Send the request and receive the response.
                response = ACS_CLIENT.do_action_with_exception(request)
                response_json = json.loads(response)
                #Return results.
                return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
            finally:
                counter += 1
                
    def delete_load_balancer(load_balancer_id):
        '''
        delete_load_balancer:Delete an SLB instance.
        For more information about APIs, go to https://www.alibabacloud.com/help/doc-detail/27579.htm?spm=a2c63.p38356.b99.138.50d5108bUbTddH.
        '''
        try:
            #Set the API parameters for deleting an SLB instance.
            request = DeleteLoadBalancerRequest.DeleteLoadBalancerRequest()
            #The ID of the SLB instance
            request.set_LoadBalancerId(load_balancer_id)
            #Send the request and receive the response.
            response = ACS_CLIENT.do_action_with_exception(request)
            response_json = json.loads(response)
            #Return results.
            return response_json
        except ServerException as e:
            ExceptionHandler.server_exception(e)
        except ClientException as e:
            ExceptionHandler.client_exception(e)
    
    def main():
        params = {}
        #Set parameters for the SLB instance.
        #Set the primary zone of the SLB instance to cn-zhangjiakou-a. 
        params["master_zone_id"] = "cn-zhangjiakou-a" 
        #Set the backup zone of the SLB instance to cn-zhangjiakou-b. 
        params["slave_zone_id"] = "cn-zhangjiakou-b" 
        #Set the name of the SLB instance to SLB1. 
        params["load_balancer_name"] = "SLB1"
        #Set the billing method of the SLB instance to Pay-As-You-Go.
        params["pay_balancer_type"] = "PayOnDemand"
    
        #Set IDs and weights of the ECS instances added to the default server group.
        params["backend_servers"] = [{"ServerId":"i-8vbe8yixxxxxxxxxxxxxw","Weight":"100"},{"ServerId":"i-8vbe8yxxxxxxxxxxxxxj9v","Weight":"100"}]
        
        #Set parameters for the uploaded server certificate.
        
        #Set parameters for the HTTPS listener.
        #Disable health checks.
        params["health_check"] = "off"
        #Set the peak bandwidth of the listener.
        params["bandwidth"] = 6
        #The frontend port of the SLB instance
        params["listener_port"] = 80
        #The backend port of the SLB instance
        params["backend_server_port"] = 443
        #Disable persistent sessions.
        params["sticky_session"] = "off"
    
        #Create an SLB instance.
        #Obtain the returned value of create_load_balancer. "load_balancer_json" is the returned value in json format.
        load_balancer_json = create_load_balancer(params)
        #Print the returned value of load_balancer_json, where "create_load_balancer" is the name of the json string.
        CommonUtil.log("create_load_balancer", load_balancer_json)
        
        #Upload the server certificate.
        #The public key certificate to be uploaded
        params["server_certificate"] = "-----BEGIN CERTIFICATE-----xxxxxxx-----END CERTIFICATE-----"
        params["private_key"] = "-----BEGIN RSA PRIVATE KEY-----xxxxxxxxxxx-----END RSA PRIVATE KEY----"
        result_json = upload_server_certificate(params)
        CommonUtil.log("upload_server_certificate", result_json)
        params["server_certificate_id"] = result_json["ServerCertificateId"]
    
        #The ID of the SLB instance
        params["load_balancer_id"] = load_balancer_json["LoadBalancerId"]
        
        #Create an HTTPS listener.
        result_json = create_https_listener(params)
        CommonUtil.log("create_https_listener", result_json)
    
        #Upload a new server certificate.
        #The new public key certificate to be uploaded
        params["server_certificate"] = "-----BEGIN CERTIFICATE-----xxxxxxx-----END CERTIFICATE-----"
        params["private_key"] = "-----BEGIN RSA PRIVATE KEY-----xxxxxxxxxxx-----END RSA PRIVATE KEY-----"
        result_json = upload_server_certificate(params)
        CommonUtil.log("upload_server_certificate", result_json)
        #
        params["server_certificate_id"] = result_json["ServerCertificateId"]
    
        #Modiy the configurations of the HTTPS listener.
        result_json = set_https_listener_attribute(params)
        CommonUtil.log("set_https_listener_attribute", result_json)
    
        #Delete an SLB instance.
        #Delete the SLB instance that the returned LoadBalancerId indicates.
        load_balancer_json = delete_load_balancer(load_balancer_json["LoadBalancerId"])
        #Print the returned value of load_balancer_json.
        CommonUtil.log("delete_load_balancer", load_balancer_json)
    
    if __name__ == "__main__":
        sys.exit(main())
  3. Go to the upload_server_certificate.py directory and run the following command to update the HTTPS certificate.
    python upload_server_certificate.py
    If the following output is displayed, the HTTPS certificate is updated and the SLB instance is deleted:
    ---------------------------create_load_balancer---------------------------
    {
      "VpcId": "",
      "AddressIPVersion": "ipv4",
      "LoadBalancerName": "SLB1",
      "ResourceGroupId": "rg-axxxxxxxxxxxy",
      "VSwitchId": "",
      "RequestId": "1DEF72EE-CA5C-449D-9E97-2CE460DE7F7A",
      "Address": "39.98.97.8",
      "NetworkType": "classic",
      "LoadBalancerId": "lb-8vxxxxxxxxxxxf"
    }
    
    ---------------------------upload_server_certificate---------------------------
    {
      "ExpireTimeStamp": 1732169065000,
      "RegionIdAlias": "cn-zhangjiakou",
      "AliCloudCertificateName": "",
      "RegionId": "cn-zhangjiakou",
      "CommonName": "test",
      "ServerCertificateName": "test",
      "ExpireTime": "2024-11-21T06:04:25Z",
      "ResourceGroupId": "rg-axxxxxxxxxxxyy",
      "RequestId": "D6FB8B7C-B0EA-43E7-AD8F-E0201A9E1A13",
      "Fingerprint": "cd:90:1b:7b:49:4d:1d:90:f6:01:de:9a:81:7d:31:a7:38:1d:84:8d",
    
      "AliCloudCertificateId": "",
      "IsAliCloudCertificate": 0,
      "ServerCertificateId": "12xxxxxxxxxxxx3_16xxxxxxxxxx6_-1xxxxxxxx13_-1xxxxxx72"
    }
    
    ---------------------------create_https_listener---------------------------
    {
      "RequestId": "FC70EDC8-06EC-4E1C-97BE-D81571DA23B4"
    }
    
    ---------------------------upload_server_certificate---------------------------
    {
      "ExpireTimeStamp": 1567857600000,
      "RegionIdAlias": "cn-zhangjiakou",
      "AliCloudCertificateName": "",
      "RegionId": "cn-zhangjiakou",
      "CommonName": "doc.aliyun-slb.top",
      "ServerCertificateName": "doc.aliyun-slb.top",
      "ExpireTime": "2019-09-07T12:00:00Z",
      "ResourceGroupId": "rg-acxxxxxxxxxxxxy",
      "RequestId": "913E991F-BCC9-4A3D-9802-19084E2CE271",
      "Fingerprint": "8c:47:1b:a7:8f:02:27:3a:35:7c:e3:47:4a:5f:55:02:ed:e3:57:1e",
    
      "SubjectAlternativeNames": {
        "SubjectAlternativeName": [
          "doc.aliyun-slb.top"
        ]
      },
      "AliCloudCertificateId": "",
      "IsAliCloudCertificate": 0,
      "ServerCertificateId": "12xxxxxxxxxxxx3_16xxxxxxx716_4xxxxxxx4_-14xxxxxxxxxx9"
    }
    
    ---------------------------set_https_listener_attribute-------------------------
    --
    {
      "RequestId": "14275D2B-20F2-4D96-9FC8-7BB2B110155C"
    }
    
    ---------------------------delete_load_balancer---------------------------
    {
      "RequestId": "2A1DF87C-842A-4C1E-AA61-23EB365EB86F"
    }