Subnet
Initialization
Confirm Endpoint
Before configuring the endpoint for SDK usage, please refer to the developer guide section on Subnet Domains to understand endpoint-related concepts. Baidu AI Cloud currently supports multiple regions. Please refer to Region Selection Guide.
Currently supported regions are: "North China-Beijing," "South China-Guangzhou," "East China-Suzhou," "Hong Kong," "Central Finance-Wuhan," and "North China-Baoding." Corresponding details:
| Access region | 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 |
Retrieve access key
To utilize Baidu AI Cloud's subnet, users need a valid AK (Access Key ID) and SK (Secret Access Key) for signature authentication. The AK/SK pairs are system-generated identifiers used for authentication and subnet access.
Your AK/SK information can be obtained and understood through the following steps:
Register a Baidu AI Cloud account
Create subnet client
The subnet client is the interface for the subnet service, offering developers a set of methods to interact with the subnet service.
Create a new subnet client with AK/SK
Users can refer to the following code to create a new subnet client to access subnet with AK/SK:
1import (
2 "github.com/baidubce/bce-sdk-go/services/vpc"
3)
4func main() {
5 // User’s Access Key ID and Secret Access Key
6 ACCESS_KEY_ID, SECRET_ACCESS_KEY := <your-access-key-id>, <your-secret-access-key>
7 // User-specified Endpoint
8 ENDPOINT := <domain-name>
9 // Initialize a subnet client
10 subnetClient, err := vpc.NewClient(AK, SK, ENDPOINT)
11}
In the code above, ACCESS_KEY_ID corresponds to “Access Key ID” in the console. SECRET_ACCESS_KEY corresponds to “Access Key Secret” in the console. Refer to the Guide - How to Retrieve AKSK. The third parameter ENDPOINT is a user-specified domain name. If left empty, the default domain name will be used as the subnet service address.
Note:
The endpointparameter must be defined with the domain name of the specified region. For example, if the service is located in Beijing, the endpoint will behttp://bcc.bj.baidubce.com.
Create a subnet client with STS
Request STS Token
The subnet service supports temporary third-party access authorization using the STS mechanism. STS (Security Token Service) is a temporary authorization service provided by Baidu AI Cloud. With STS, you can grant temporary access credentials with defined validity periods and permissions to third-party users. These users can then use these credentials to directly call Baidu AI Cloud APIs or SDKs to access your cloud resources.
To interact with a subnet via STS, users first need to request a certification string through the STS client.
Create subnet client with STS Token
Once the STS token is obtained, configure it in the subnet client to enable subnet client creation using the STS token.
Code example
The GO SDK implements the STS service API. Below is a complete example for requesting an STS token and creating a subnet client object:
1import (
2 "fmt"
3 "github.com/baidubce/bce-sdk-go/auth" //Import the authentication module
4 "github.com/baidubce/bce-sdk-go/services/vpc" //Import VPC service module
5 "github.com/baidubce/bce-sdk-go/services/sts" //Import the Baige service module
6)
7func main() {
8 //Create a Client object for the STS service, using the default Endpoint
9 AK, SK := <your-access-key-id>, <your-secret-access-key>
10 stsClient, err := sts.NewClient(AK, SK)
11 if err != nil {
12 fmt.Println("create sts client object :", err)
13 return
14 }
15 //Obtain a temporary authentication token with a validity period of 60 seconds and an empty ACL
16 stsObj, err := stsClient.GetSessionToken(60, "")
17 if err != nil {
18 fmt.Println("get session token failed:", err)
19 return
20 }
21 fmt.Println("GetSessionToken result:")
22 fmt.Println(" accessKeyId:", stsObj.AccessKeyId)
23 fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey)
24 fmt.Println(" sessionToken:", stsObj.SessionToken)
25 fmt.Println(" createTime:", stsObj.CreateTime)
26 fmt.Println(" expiration:", stsObj.Expiration)
27 fmt.Println(" userId:", stsObj.UserId)
28 //Create a VPC client object using the requested temporary STS, with the default endpoint
29 subnetClient, err := vpc.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "bcc.bj.baidubce.com")
30 if err != nil {
31 fmt.Println("create vpc client failed:", err)
32 return
33 }
34 stsCredential, err := auth.NewSessionBceCredentials(
35 stsObj.AccessKeyId,
36 stsObj.SecretAccessKey,
37 stsObj.SessionToken)
38 if err != nil {
39 fmt.Println("create sts credential object failed:", err)
40 return
41 }
42 subnetClient.Config.Credentials = stsCredential
43}
Note: Currently, when configuring a subnet client with STS, regardless of where the corresponding subnet service endpoint is located, the STS endpoint must be set to http://sts.bj.baidubce.com. This default is utilized when creating an STS object in the above code.
Configure HTTPS protocol access to subnet
Subnet supports the HTTPS protocol. By specifying HTTPS in the endpoint when creating a subnet client object, users can access the subnet service via HTTPS in the Subnet GO SDK:
1// import "github.com/baidubce/bce-sdk-go/services/vpc"
2 ENDPOINT := ""https://bcc.bj.baidubce.com" // Specify the use of HTTPS protocol
3AK, SK := <your-access-key-id>, <your-secret-access-key>
4subnetClient, _ := vpc.NewClient(AK, SK, ENDPOINT)
Configure subnet client
If users need to configure specific parameters for the subnet client, they can customize the configuration using the exported Config field of the subnet client object after its creation. This allows for configuring parameters such as proxy and maximum number of connections for the client.
Use a proxy
The following code snippet enables the client to access subnet service using a proxy:
1// import "github.com/baidubce/bce-sdk-go/services/vpc"
2 //Create subnet client object
3AK, SK := <your-access-key-id>, <your-secret-access-key>
4ENDPOINT := "bcc.bj.baidubce.com"
5client, _ := vpc.NewClient(AK, SK, ENDPOINT)
6 // Use the local port 8080 for the proxy
7client.Config.ProxyUrl = "127.0.0.1:8080"
Set network parameters
Users can configure network parameters using the following example code:
1// import "github.com/baidubce/bce-sdk-go/services/vpc"
2AK, SK := <your-access-key-id>, <your-secret-access-key>
3ENDPOINT := "bcc.bj.baidubce.com"
4client, _ := vpc.NewClient(AK, SK, ENDPOINT)
5 // Configure to not retry, default: Back Off retry
6client.Config.Retry = bce.NewNoRetryPolicy()
7 // Configure connection timeout to 30 seconds
8client.Config.ConnectionTimeoutInMillis = 30 * 1000
Configure options for generating signature strings
1// import "github.com/baidubce/bce-sdk-go/services/vpc"
2AK, SK := <your-access-key-id>, <your-secret-access-key>
3ENDPOINT := "bcc.bj.baidubce.com"
4client, _ := vpc.NewClient(AK, SK, ENDPOINT)
5 // Configure the HTTP request header Host for signing
6headersToSign := map[string]struct{}{"Host": struct{}{}}
7client.Config.SignOption.HeadersToSign = HeadersToSign
8 // Configure the validity period of the signature to 30 seconds
9client.Config.SignOption.ExpireSeconds = 30
Parameter description
When using the GO SDK to access subnet, the Config field of the created subnet client object supports the following parameters, as shown in the table below:
| ConfigMap name | Types | Meaning |
|---|---|---|
| Endpoint | string | Domain name for service requests |
| ProxyUrl | string | The proxy address for client requests |
| Region | string | Region for resource requests |
| UserAgent | string | User name, HTTP request’s User-Agent header |
| Credentials | *auth.BceCredentials | Authentication object for requests, divided into regular AK/SK and STS |
| SignOption | *auth.SignOptions | Options for authentication string signing |
| Retry | RetryPolicy | Retry policy for connections |
| ConnectionTimeoutInMillis | int | Connection timeout, in milliseconds, defaulting to 20 minutes |
Description:
- The
Credentialsis created using theauth.NewBceCredentialsandauth.NewSessionBceCredentialsfunctions. The former is used by default, while the latter is used for STS certification. For details, refer to Create Subnet Client with STS. - The
SignOptionfield represents options when generating a signature string, as detailed in the table below:
| Name | Types | Meaning |
|---|---|---|
| HeadersToSign | map[string]struct{} | HTTP headers used when generating the signature string |
| Timestamp | int64 | Timestamp used in the generated signature string, defaulting to the value at the time of sending request |
| ExpireSeconds | int | Validity period of the signature string |
1 Among configuration options, HeadersToSign defaults to `Host`, `Content-Type`, `Content-Length` and `Content-MD5`; TimeStamp is typically set to zero, indicating that the timestamp at the time of generating the certification string shall be used, and users generally shall not explicitly specify the value for this field; ExpireSeconds defaults to 1,800 seconds or 30 minutes.
- The
Retryfield specifies the retry policy, currently supporting two types:NoRetryPolicyandBackOffRetryPolicy. By default, the latter is used. This retry policy specifies the maximum number of retries, the maximum retry duration, and the retry base. Retries increase exponentially based on the retry base multiplied by 2 until the maximum number of retries or the maximum retry duration is reached.
Subnet management
A subnet is a user-defined IP address range within a VPC. Based on specific service needs, users can define address spaces and IP segments using classless inter-domain routing (CIDR). Subnets can also be used in the future to specify Internet access permissions, routing rules, and security policies.
Create subnet
Function declaration
1type CreateSubnetArgs struct {
2 ClientToken string `json:"-"`
3 Name string `json:"name"`
4 ZoneName string `json:"zoneName"`
5 Cidr string `json:"cidr"`
6 VpcId string `json:"vpcId"`
7 VpcSecondaryCidr string `json:"vpcSecondaryCidr,omitempty"`
8 SubnetType SubnetType `json:"subnetType,omitempty"`
9 Description string `json:"description,omitempty"`
10 EnableIpv6 bool `json:"enableIpv6,omitempty"`
11 Tags []model.TagModel `json:"tags,omitempty"`
12}
13func (c *Client) CreateSubnet(args *CreateSubnetArgs) (*CreateSubnetResult, error)
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/Yjwvyu8o1
Usage example
1createSubnetArgs := &vpc.CreateSubnetArgs{
2 Name: "TestSDK-Subnet", // Subnet name
3 Description: "vpc test", // Subnet description
4 Cidr: "192.168.96.0/20", // Subnet segment
5 VpcId: "vpc-p1eawhw5rx4n", // vpc id
6 ZoneName: "cn-bj-a", // Subnet availability zone
7}
8 response, err := client.CreateSubnet(createSubnetArgs) // Create subnet
Response Value
Operation succeeded:
1{
2 "subnetId":"sbn-1A09ef6b"
3}
Operation failed:
Throw an exception. For the exception list, refer to https://cloud.baidu.com/doc/VPC/s/sjwvyuhe7
Code example
For specific code examples, please refer to example_create_subnet.go
List subnets
Function declaration
1type ListSubnetArgs struct {
2 Marker string
3 MaxKeys int
4 VpcId string
5 ZoneName string
6 SubnetType SubnetType
7}
8func (c *Client) ListSubnets(args *ListSubnetArgs) (*ListSubnetResult, error)
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/xjwvyu8zu
Usage example
1args := &vpc.ListSubnetArgs{
2 MaxKeys: 100, // Set maximum number of items included per page, maximum 1,000. The default is 1,000
3. Marker: "", // Set starting position of batch list query, which is a system-generated string
4 VpcId: "vpc-p1eawhw5rx4n", // The VPC ID to which the subnet belongs
5}
6response, err := client.ListSubnets(args)
Response Value
Operation succeeded:
1{
2 "nextMarker": "sbn-IyarenI7",
3 "marker": "sbn-IyWRnII7",
4 "maxKeys": 1,
5 "isTruncated": true,
6 "subnets": [
7 {
8 "name": "System predefined subnet",
9 "subnetId": "sbn-IyWRnII7",
10 "zoneName": "cn-bj-a",
11 "cidr": "192.168.0.0/20",
12 "ipv6Cidr": "",
13 "vpcId": "vpc-IyrqYIQ7",
14 "subnetType": "BCC",
15 "description": "",
16 "createdTime": "2020-11-19T12:46:01Z",
17 "tags": [
18 {
19 "tagKey": "aa",
20 "tagValue": "bb"
21 }
22 ]
23 }
24 ]
25}
Operation failed:
Throw an exception. For the exception list, refer to https://cloud.baidu.com/doc/VPC/s/sjwvyuhe7
Code example
For specific code examples, please refer to example_list_subnet.go
Query subnet
Function declaration
1func (c *Client) GetSubnetDetail(subnetId string) (*GetSubnetDetailResult, error)
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/Sjwvyu89a
Usage example
1subnetID := "sbn-u166vdnqqubi" // Subnet ID
2 response, err := client.GetSubnetDetail(subnetID) // Get subnet details
Response Value
Operation succeeded:
1{
2 "subnet":
3 {
4 "name": "System predefined subnet",
5 "subnetId": "sbn-IyWRnII7",
6 "zoneName": "cn-bj-a",
7 "cidr": "192.168.0.0/20",
8 "ipv6Cidr": "",
9 "vpcId": "vpc-IyrqYIQ7",
10 "subnetType": "BCC",
11 "availableIp": 4090,
12 "description": "",
13 "createdTime": "2020-11-19T12:46:01Z"
14 }
15}
Operation failed:
Throw an exception. For the exception list, refer to https://cloud.baidu.com/doc/VPC/s/sjwvyuhe7
Code example
For specific code examples, please refer to example_get_subnet.go
Update subnet
Function declaration
1type UpdateSubnetArgs struct {
2 ClientToken string `json:"-"`
3 Name string `json:"name"`
4 Description string `json:"description,omitempty"`
5 EnableIpv6 bool `json:"enableIpv6"`
6}
7func (c *Client) UpdateSubnet(subnetId string, args *UpdateSubnetArgs) error
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/3jwvyu7wm
Usage example
1updateSubnetArgs := &vpc.UpdateSubnetArgs{
2 ClientToken: clientToken,
3 Name: "test_subnet", // Update subnet name
4 Description: "", // Update subnet description
5}
6 err := client.UpdateSubnet(subnetID, updateSubnetArgs) // Update subnet
Response Value
Operation succeeded:
1{
2}
Operation failed:
Throw an exception. For the exception list, refer to https://cloud.baidu.com/doc/VPC/s/sjwvyuhe7
Code example
For specific code examples, please refer to example_update_subnet.go
Note: Only the name and description fields of the subnet can be updated; the cidr, zone_name, and type fields cannot be modified
Delete subnet
Function declaration
1func (c *Client) DeleteSubnet(subnetId string, clientToken string) error
Parameter Meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/6jwvyu9b8
Usage example
1subnetID := "sbn-5uj2t9f1jazj"
2clientToken := "be31b98c-5141-4838-9830-9be700de5a20"
3err := client.DeleteSubnet(subnetID, clientToken)
Response Value
Operation succeeded:
1{
2}
Operation failed:
Throw an exception. For the exception list, refer to https://cloud.baidu.com/doc/VPC/s/sjwvyuhe7
Code example
For specific code examples, please refer to example_delete_subnet.go
Create reserved network segment
Use the following code to create routing rules
Function declaration
1func (c *Client) CreateIpreserve(args *CreateIpreserveArgs) (*CreateIpreserveResult, error)
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/xlgyjw2kn
Response value
Operation succeeded:
1{
2 "ipReserveId":"ipr-te2pa9cv4ikk"
3}
Operation failed:
Return error. Refer to the error code list at: https://cloud.baidu.com/doc/VPC/s/sjwvyuhe7
Code example
For specific code examples, please refer to: example_create_ip_reserve.go
Query the reserved network segment list
Use the following code to create routing rules
Function declaration
1func (c *Client) ListIpreserve(args *ListIpeserveArgs) (*ListIpeserveResult, error)
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/xlgyjw2kn
Response value
Operation succeeded:
1{
2 "marker": "",
3 "nextMarker": "ipr-7xp6wvzqpmhd",
4 "maxKeys": 1,
5 "isTruncated": true,
6 "ipReserves":[
7 {
8 "ipReserveId":"ipr-tqsbpf5hcvbp",
9 "subnetId":"sbn-a4cikyt7756r",
10 "ipCidr":"192.168.0.200/30",
11 "ipVersion":"4",
12 "description":"test",
13 "createdTime":"2023-04-27T03:44:38Z",
14 "updatedTime":"2023-04-27T03:45:38Z"
15 }
16 ]
17}
Operation failed:
Return error. Refer to the error code list at: https://cloud.baidu.com/doc/VPC/s/Flgyjya1o
Code example
For specific code examples, please refer to: example_list_ip_reserve.go
Delete reserved network segment
Use the following code to create routing rules
Function declaration
1func (c *Client) DeleteIpreserve(ipReserveId, clientToken string) error
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/xlgyjw2kn
Response value
Operation succeeded:
1{}
Operation failed:
Return error. Refer to the error code list at: https://cloud.baidu.com/doc/VPC/s/6lgyjz8jn
Code example
For specific code examples, please refer to: example_delete_ip_reserve.go
