百度智能云

All Product Document

          Virtual Private Cloud

          Subnet

          Initialization

          Confirm Endpoint

          When confirming the Endpoint configured when you use the SDK, you can first read the section on Subnet Access Domain Name in the Developer Guide to understand the Endpoint concept. Baidu AI Cloud currently supports multi-regions. Please see Region Selection Instructions.

          Currently, the six regions are supported: "North China - Beijing", "South China- Guangzhou", "East China - Suzhou", "Hong Kong", "Finance Central China - Wuhan" and "North China - Baoding". The corresponding information is:

          Access region Corresponding Endpoint Protocol
          BJ bcc.bj.baidubce.com HTTP and HTTPS
          GZ bcc.gz.baidubce.com HTTP and HTTPS
          SU bcc.su.baidubce.com HTTP and HTTPS
          HKG bcc.hkg.baidubce.com HTTP and HTTPS
          FWH bcc.fwh.baidubce.com HTTP and HTTPS
          BD bcc.bd.baidubce.com HTTP and HTTPS

          Get the key

          To use Baidu AI Cloud Subnet, you need to have a valid AK (Access Key ID) and SK (Secret Access Key) for signature authentication. AK/SK is assigned to users by the system and is a string to identify users and verify signatures for accessing subnet.

          You can obtain and understand your AK/SK information through the following steps:

          Register Baidu AI Cloud Account

          Create AK/SK

          Create a Subnet Client

          Subnet Client is the client of subnet service, which provides a series of methods for the developer to interact with subnet service.

          Create a Subnet Client with AK/SK

          Access subnet via AK/SK, and users can create a Subnet Client by reference to the following codes:

          import ( 
          	 "github.com/baidubce/bce-sdk-go/services/vpc" 
          ) 
          
          func main() { 
          	 // Access Key ID and Secret Access Key of users 
          	 ACCESS_KEY_ID, SECRET_ACCESS_KEY := <your-access-key-id>, <your-secret-access-key> 
          
          	 // User specified Endpoint 
          	 ENDPOINT := <domain-name> 
          
          	 // Initialize a subnetClient 
          	 subnetClient, err := vpc.NewClient(AK, SK, ENDPOINT) 
          } 

          In the above code, ACCESS_KEY_ID corresponds to the "Access Key ID" in the console, and SECRET_ACCESS_KEY corresponds to the "Access Key Secret" in the console. For how to obtain it, please see How to Get AKSK in the Operation Guide . The third parameter “ENDPOINT” supports the domain name specified by the users themselves, and if it is set as a null string, default domain name is used as the service address of Subnet.

          Note ENDPOINT needs to be defined with the domain name of specified region. For example, if the service region is Beijing, the domain name is http://bcc.bj.baidubce.com.

          Create Subnet Client with STS

          Apply for STS token

          Subnet can implement temporary authorized access by a third party through the STS mechanism. STS (Security Token Service) is a temporary authorization service provided by Baidu Cloud. With STS, you can issue a third-party user with a custom time-based and privileged access credential. The third-party user can use the access credential to directly call API or SDK of Baidu AI Cloud to access its resources.

          To access to subnet via STS, you need to apply for an authentication string via client of STS, for the application method.

          Create a subnet Client with STS token

          After STS is applied, STS Token can be configured in Subnet Client to create Subnet Client via STS Token.

          Code example

          GO SDK realizes the interface of STS service, and users can refer to the following complete code to apply for STS Token and create Subnet Client object.

          import ( 
          	 "fmt" 
          
          	 "github.com/baidubce/bce-sdk-go/auth"         // Import authentication module 
          	 "github.com/baidubce/bce-sdk-go/services/vpc" // Import VPC service module 
          	 "github.com/baidubce/bce-sdk-go/services/sts" // Import STS service module 
          ) 
          
          func main() { 
          	 // Create the Client object of STS service, with Endpoint of default value 
          	 AK, SK := <your-access-key-id>, <your-secret-access-key> 
          	 stsClient, err := sts.NewClient(AK, SK) 
          	 if err != nil { 
          	 	 fmt.Println("create sts client object :", err) 
          	 	 return 
          	 } 
          
          	 // Obtain a temporary authentication token, with a valid period of 60 sec, and ACL null 
          	 stsObj, err := stsClient.GetSessionToken(60, "") 
          	 if err != nil { 
          	 	 fmt.Println("get session token failed:", err) 
          	 	 return 
              } 
          	 fmt.Println("GetSessionToken result:") 
          	 fmt.Println("  accessKeyId:", stsObj.AccessKeyId) 
          	 fmt.Println("  secretAccessKey:", stsObj.SecretAccessKey) 
          	 fmt.Println("  sessionToken:", stsObj.SessionToken) 
          	 fmt.Println("  createTime:", stsObj.CreateTime) 
          	 fmt.Println("  expiration:", stsObj.Expiration) 
          	 fmt.Println("  userId:", stsObj.UserId) 
          
          	 // Create the Client object of VPC service with the temporary STS applied, with Endpoint of default value. 
          	 subnetClient, err := vpc.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "bcc.bj.baidubce.com") 
          	 if err != nil { 
          	 	 fmt.Println("create vpc client failed:", err) 
          	 	 return 
          	 } 
          	 stsCredential, err := auth.NewSessionBceCredentials( 
          	 	 stsObj.AccessKeyId, 
          	 	 stsObj.SecretAccessKey, 
          	 	 stsObj.SessionToken) 
          	 if err != nil { 
          	 	 fmt.Println("create sts credential object failed:", err) 
          	 	 return 
          	 } 
          	 subnetClient.Config.Credentials = stsCredential 
          } 

          Note: Currently, when STS is used to configure Subnet Client, wherever the Endpoint corresponding to subnet service is, the Endpoint of STS needs to be configured as http://sts.bj.baidubce.com. This default value is used to create STS object in the code above.

          Configure HTTPS to Access Subnet

          Subnet supports HTTPS, and you can use HTTPS to access Subnet service in Subnet GO SDK by indicating the mode of HTTPS in the Endpoint specified during creation of subnet Client object.

          // import "github.com/baidubce/bce-sdk-go/services/vpc" 
          
          ENDPOINT := "https://bcc.bj.baidubce.com" // Indicate the use of HTTPS 
          AK, SK := <your-access-key-id>, <your-secret-access-key> 
          subnetClient, _ := vpc.NewClient(AK, SK, ENDPOINT) 

          Configure Subnet Client

          To configure parameters of some details of Subnet Client, you can use the export field Config of Subnet Client object for custom configuration after creating that object, and can configure agent, maximum connections, etc. for the client.

          Use agent

          The following codes enable client to use agent to access subnet service:

          // import "github.com/baidubce/bce-sdk-go/services/vpc" 
          
          // Create Subnet Client object 
          AK, SK := <your-access-key-id>, <your-secret-access-key> 
          ENDPOINT := "bcc.bj.baidubce.com" 
          client, _ := vpc.NewClient(AK, SK, ENDPOINT) 
          
          // The agent uses the local 8080 port 
          client.Config.ProxyUrl = "127.0.0.1:8080"

          Set network parameters

          Users can set the network parameters with the following sample code:

          // import "github.com/baidubce/bce-sdk-go/services/vpc" 
          
          AK, SK := <your-access-key-id>, <your-secret-access-key> 
          ENDPOINT := "bcc.bj.baidubce.com" 
          client, _ := vpc.NewClient(AK, SK, ENDPOINT) 
          
          // Configuration is not retried, and the default is Back Off retry 
          client.Config.Retry = bce.NewNoRetryPolicy() 
          
          // Configure the connection time-out period as 30sec 
          client.Config.ConnectionTimeoutInMillis = 30 * 1000

          Configure generation of signature string option

          // import "github.com/baidubce/bce-sdk-go/services/vpc" 
          
          AK, SK := <your-access-key-id>, <your-secret-access-key> 
          ENDPOINT := "bcc.bj.baidubce.com" 
          client, _ := vpc.NewClient(AK, SK, ENDPOINT) 
          
          // Configure the HTTPS request header for signature as `Host` 
          headersToSign := map[string]struct{}{"Host": struct{}{}} 
          client.Config.SignOption.HeadersToSign = HeadersToSign 
          
          // Configure the valid period of signature as 30sec 
          client.Config.SignOption.ExpireSeconds = 30

          Parameter description

          When users use GO SDK to access subnet, the Config field of Subnet Client object created supports all parameters in the table below:

          Name of configuration item Type Meaning
          Endpoint string Domain name of request service
          ProxyUrl string Agent address of client request
          Region string Region of request resources
          UserAgent string User name, User-Agent header of HTTP request
          Credentials *auth.BceCredentials Authentication object of request is classified into ordinary AK/SK and STS
          SignOption *auth.SignOptions Signature option of authentication string
          Retry RetryPolicy Connection retry policy
          ConnectionTimeoutInMillis int Connection time-out period, in msec, and the default is 20min

          Description:

          1.Credentials field is created with auth.NewBceCredentials and auth.NewSessionBceCredentials functions, with the former as the default, and the latter used for STS authentication; for details, please see the subsection “Create Subnet Client with STS”.

          2.SignOption field is the option to generate signature string, for more information, please see the explanation in the table below:

          Name Type Meaning
          HeadersToSign map[string]struct{} HTTP header used to generate signature string
          Timestamp int64 The time stamp used to generate signature string is the value when the request is sent by default.
          ExpireSeconds int Valid period of signature string
           Where the default values of HeadersToSign are `Host`, `Content-Type`, `Content-Length` and `Content- MD5`; TimeStamp is generally zero, indicating the time stamp when call is used to generate string, and generally the value of that field should not be specified expressly; the default value of ExpireSeconds is 1,800sec, i.e. 30min. 

          3.Retry field specifies the retry strategy, and support 2 retry strategies currently: NoRetryPolicy and BackOffRetryPolicy. By default, the latter is used, and this retry strategy specifies the maximum number of retry, longest time of retry and retry base. Retry is performed by multiplying the retry base by exponential growth of 2 until the maximum retry test or the maximum retry time is reached.

          Subnet Management

          A subnet is a user-definable range of IP addresses within a VPC. Depending on business needs, CIDR (Classless Inter-Domain Routing) can specify different address spaces and IP segments. In the future, users can use the subnet as a unit to define Internet access permissions, routing rules, and security policies.

          Create subnet

          The following code can create a subnet in the specified VPC.

          //import "github.com/baidubce/bce-sdk-go/services/vpc" 
          
          args := &vpc.CreateSubnetArgs{ 
          	 // Set the name of the subnet 
              Name:        "TestSDK-Subnet", 
              // Set the zone name of the subnet 
              ZoneName:    "cn-bj-a", 
              // Set the cidr of the subnet 
              Cidr:        "192.168.1.0/24", 
              // Set Id of vpc to which the subnet belongs 
              VpcId:       "vpc-4njbqurm0uag", 
              // Set the type of subnet, including "BCC", "BCC_NAT" and "BBC" 
              SubnetType:  vpc.SUBNET_TYPE_BCC, 
              // Set the description of the subnet 
              Description: "test subnet", 
              // Set the tag key-value pair list of the subnet 
              Tags: []model.TagModel{ 
                  { 
                      TagKey:   "tagK", 
                      TagValue: "tagV", 
                  }, 
              }, 
          } 
          result, err := client.CreateSubnet(args) 
          if err != nil { 
              fmt.Println("create subnet error: ", err) 
              return 
          } 
          
          fmt.Println("create subnet success, subnet id: ", result.SubnetId) 

          Note:

          • The subnet name cannot take the "default" value, with the length not exceeding 65 characters, and can be composed by numbers, characters and underlines.
          • For the name of available zone, refer to Query Available Zone List

          Query of the subnet list

          Use the following code to query the list of eligible subnets.

          //import "github.com/baidubce/bce-sdk-go/services/vpc" 
          
          args := &vpc.ListSubnetArgs{ 
          	 // The starting location of query for batch acquisition of lists, and is one string generated by the system. 
          	 Marker:     marker, 
          	 // Set the maximum number contained in each page, generally not exceeding 1000. The default value is 1000. 
          	 MaxKeys:    maxKeys, 
          	 // Set Id of vpc belongs 
              VpcId:      vpcId, 
              // Set name of the available zone affiliated 
              ZoneName:   zoneName, 
              // Set subnet type 
              SubnetType: vpc.SUBNET_TYPE_BCC, 
          } 
          result, err := client.ListSubnets(args) 
          if err != nil { 
              fmt.Println("list subnets error: ", err) 
              return 
          } 
          
          // Return to the starting position of the mark query 
          fmt.Println("subnet list marker: ", result.Marker) 
          // True means there are additional data in the following pages and false means the current page is the last page. 
          fmt.Println("subnet list isTruncated: ", result.IsTruncated) 
          // The marker value requiring to be passed in order to acquire the next page. The domain doesn't appear when isTruncated is false. 
          fmt.Println("subnet list nextMarker: ", result.NextMarker) 
          // Maximum number contained in each page. 
          fmt.Println("subnet list maxKeys: ", result.MaxKeys) 
          // Get specific information about subnet 
          for _, sub := range result.Subnets { 
              fmt.Println("subnet id: ", sub.SubnetId) 
              fmt.Println("subnet name: ", sub.Name) 
              fmt.Println("subnet zoneName: ", sub.ZoneName) 
              fmt.Println("subnet cidr: ", sub.Cidr) 
              fmt.Println("subnet vpcId: ", sub.VPCId) 
              fmt.Println("subnet subnetType: ", sub.SubnetType) 
              fmt.Println("subnet description: ", sub.Description) 
              fmt.Println("subnet availableIp: ", sub.AvailableIp) 
              fmt.Println("subnet tags: ", sub.Tags) 
          } 

          According to this API, the list of subnets that meet the requirements can be queried based on conditions such as vpcId, zoneName, and subnetType.

          Query of the specified subnet

          According to the following code, you can query the detailed information of the specified subnet.

          //import "github.com/baidubce/bce-sdk-go/services/vpc" 
          
          result, err := client.GetSubnetDetail(subnetId) 
          if err != nil { 
              fmt.Println("get subnet detail error: ", err) 
              return 
          } 
          
          // Query to get the id of the subnet 
          fmt.Println("subnet id: ", result.Subnet.SubnetId) 
          // Query to get the name of the subnet 
          fmt.Println("subnet name: ", result.Subnet.Name) 
          // Query to get the name of the zone to which the subnet belongs 
          fmt.Println("subnet zoneName: ", result.Subnet.ZoneName) 
          // Query to get the cidr of the subnet 
          fmt.Println("subnet cidr: ", result.Subnet.Cidr) 
          // Query to get the id of the vpc to which the subnet belongs 
          fmt.Println("subnet vpcId: ", result.Subnet.VPCId) 
          // Query to get the type of subnet 
          fmt.Println("subnet subnetType: ", result.Subnet.SubnetType) 
          // Query to get the description of the subnet 
          fmt.Println("subnet description: ", result.Subnet.Description) 
          // Query to get the number of available IPs in the subnet 
          fmt.Println("subnet availableIp: ", result.Subnet.AvailableIp) 
          // Query to get the list of tags bound to the subnet 
          fmt.Println("subnet tags: ", result.Subnet.Tags) 

          Through this interface, you can get information such as the name, available zone, cidr, type, description, number of available ips, and tag list of the subnet.

          Note: The subnet types include "BCC", "BCC_NAT", and "BBC".

          Delete subnet

          The specified subnet can be deleted by the following code.

          //import "github.com/baidubce/bce-sdk-go/services/vpc" 
          
          if err := client.DeleteSubnet(subnetId, clientToken); err != nil { 
              fmt.Println("delete subnet error: ", err) 
              return 
          } 
          
          fmt.Printf("delete subnet %s success.", subnetId) 

          Note: The clientToken in the parameter represents an idempotent token, which is an ASCII string no more than 64 bits in length. For details, see ClientToken idempotence

          Update subnet

          Use the following code to update the subnet information.

          //import "github.com/baidubce/bce-sdk-go/services/vpc" 
          
          args := &vpc.UpdateSubnetArgs{ 
          	 // Set the idempotent token used for update operations 
              ClientToken: clientToken, 
              // Set the updated subnet name 
              Name:        "TestSDK-Subnet-update", 
              // Set the updated subnet description 
              Description: "subnet update", 
          } 
          if err := client.UpdateSubnet(subnetId, args); err != nil { 
              fmt.Println("update subnet error: ", err) 
              return 
          } 
          
          fmt.Printf("update subnet %s success.", subnetId) 

          Use this interface to update the subnet name and description information.

          Previous
          Exception Handling
          Next
          Route