VPC
VPC services
Overview
This document details the usage of VPC GO SDK. Prerequisites include prior understanding of VPC fundamentals, and activated VPC service. If you are not yet familiar with VPC, you can refer to Product Description and Guide.
Initialization
Confirm Endpoint
Before configuring the endpoint for SDK usage, please refer to the developer guide section on VPC Access Domain Name 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 use the VPC services, users must obtain a valid AK (Access Key ID) and SK (Secret Access Key) for signature verification. AK/SK are system-assigned identifiers used for user authentication and VPC access.
Your AK/SK information can be obtained and understood through the following steps:
Register a Baidu AI Cloud account
Create a new VPC client
The VPC client acts as an interface for VPC services, offering developers various methods to interact with VPC functionalities.
Create a new VPC client with AK/SK
Users can refer to the following code to create a new VPC client to access VPC 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 VpcClient
10 vpcClient, 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 VPC 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 VPC client with STS
Request STS Token
VPC supports temporary third-party access authorization through the STS (Security Token Service) mechanism. STS, provided by Baidu AI Cloud, is a service that issues temporary access credentials with customizable validity and permissions. Third-party users can use these credentials to directly call Baidu AI Cloud APIs or SDKs to access cloud resources.
To access VPC via STS, users must first request a credential string through the STS client.
Create VPC client with STS Token
Once the STS token is obtained, users can configure it into the VPC client to enable STS-based VPC client creation.
Code example
The GO SDK implements the STS service API. Below is a complete example for requesting an STS Token and creating an VPC 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 vpcClient, 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 vpcClient.Config.Credentials = stsCredential
43}
Note: Currently, when configuring a VPC client with STS, regardless of where the corresponding VPC 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 access to VPC
VPC supports the HTTPS transport protocol. To use HTTPS to access VPC services with the VPC Go SDK, specify HTTPS in the endpoint when creating the VPC client object.
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>
4vpcClient, _ := vpc.NewClient(AK, SK, ENDPOINT)
Configure the VPC client
If users need to configure specific parameters for the VPC client, they can customize the configuration using the exported Config field of the VPC 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 VPC service using a proxy:
1// import "github.com/baidubce/bce-sdk-go/services/vpc"
2 // Create an VPC 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 VPC, the Config field of the created VPC 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 a VPC 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.
VPC management
A virtual private cloud (VPC) is a flexible virtual network that enables users to design their own networking environment. By configuring parameters such as IP address ranges and subnets, users can rapidly create a VPC. Each VPC is fully isolated from others, allowing users to create and manage BCC instances within their dedicated VPC.
Create VPC
Function declaration
1type CreateVPCArgs struct {
2 ClientToken string `json:"-"`
3 Name string `json:"name"`
4 Description string `json:"description,omitempty"`
5 Cidr string `json:"cidr"`
6 Tags []model.TagModel `json:"tags,omitempty"`
7}
8func (c *Client) CreateVPC(args *CreateVPCArgs) (*CreateVPCResult, error)
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/Njwvyuaq5
Usage example
1 createVpcArgs := &vpc.CreateVPCArgs{
2 Name: "TestSDK-VPC", // VPC name
3 Description: "vpc test", // VPC description
4 Cidr: "192.168.0.0/16", // VPC segment
5 Tags: []model.TagModel{ // VPC tags
6 {
7 TagKey: "tagK",
8 TagValue: "tagV",
9 },
10 },
11 }
12 response, err := client.CreateVPC(createVpcArgs)
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, refer to example_create_vpc.go
Query VPC list
Function declaration
1type ListVPCArgs struct {
2 Marker string
3 MaxKeys int
4 // IsDefault is a string type,
5 // so we can identify if it has been setted when the value is false.
6 // NOTE: it can be only true or false.
7 IsDefault string
8}
9func (c *Client) ListVPC(args *ListVPCArgs) (*ListVPCResult, error)
Parameter meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/wjwvyub23
Usage example
1args := &vpc.ListVPCArgs{
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}
5 response, err := client.ListVPC(args) // Retrieve VPC list
Response Value
Operation succeeded:
1{
2"nextMarker": "vpc-xktdeMSf",
3"marker": "vpc-IyWRtII7",
4"maxKeys": 1,
5"isTruncated": true,
6"vpcs": [
7 {
8 "vpcId': "vpc-IyWRtII7",
9 "name": "VPC Name",
10 "isDefault": True,
11 "cidr": "0.0.0.0/0",
12 "description": "default",
13 "ipv6Cidr": "2400:da00:e003:4c00::/56",
14 "tags":[
15 {
16 "tagKey": "tagKey",
17 "tagValue": "tagValue"
18 }
19 ]
20 }
21 ]
22}
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, refer to example_list_vpc.go
Query specified VPC
Function declaration
1func (c *Client) GetVPCDetail(vpcId string) (*GetVPCDetailResult, error)
Parameter Meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/yjwvyuaeo
Usage example
1vpcID := "vpc-p1eawhw5rx4n" // vpc id
2 response, err := client.GetVPCDetail(vpcID) // Get VPC details
Response Value
Operation succeeded:
1{
2 "vpc": {
3 "vpcId': "vpc-p1eawhw5rx4n",
4 "name": u"\u9ed8\u8ba4\u79c1\u6709\u7f51\u7edc",
5 "isDefault": True,
6 "cidr": "0.0.0.0/0",
7 "ipv6Cidr": "2400:da00:e003:4c00::/56",
8 "description": "default",
9 "subnets": [
10 {
11 "name": "System predefined subnet",
12 "subnetId": "sbn-IyWRnII7",
13 "zoneName": "cn-bj-a",
14 "cidr": "192.168.0.0/20",
15 "ipv6Cidr": "2400:da00:e003:4c11::/64",
16 "vpcId": "vpc-IyrqYIQ7",
17 "subnetType": "BCC",
18 "description": ""
19 "createdTime": "2018-03-14T14:45:02Z"
20 }
21 ],
22 "tags":[
23 {
24 "tagKey": "tagKey",
25 "tagValue": "tagValue"
26 }
27 ]
28 }
29}
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, refer to example_get_vpc.go
Delete VPC
Function declaration
1func (c *Client) DeleteVPC(vpcId, clientToken string) error
Parameter Meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/Ijwvyua0d
Usage example
1vpcID := "vpc-is0j69zp08cx"
2clientToken := "be31b98c-5141-4838-9830-9be700de5a20"
3 err := client.DeleteVPC(vpcID, clientToken) // Delete VPC
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, refer to example_delete_vpc.go
Update VPC
Function declaration
1type UpdateVPCArgs struct {
2 ClientToken string `json:"-"`
3 Name string `json:"name"`
4 Description string `json:"description,omitempty"`
5}
6func (c *Client) UpdateVPC(vpcId string, updateVPCArgs *UpdateVPCArgs) error
Parameter Meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/tjwvyubez
Usage example
1clientToken := "be31b98c-5e41-4838-9830-9be700de5a20"
2vpcID := "vpc-p1eawhw5rx4n"
3updateVpcArgs := &vpc.UpdateVPCArgs{
4 ClientToken: clientToken,
5 Name: "test_vpc", // Update the VPC name
6 Description: "", // Update the VPC description
7}
8 err := client.UpdateVPC(vpcID, updateVpcArgs) // Update VPC
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, refer to example_update_vpc.go
Query intranet IPs
Function declaration
1type GetVpcPrivateIpArgs struct {
2 VpcId string `json:"vpcId"`
3 PrivateIpAddresses []string `json:"privateIpAddresses",omitempty`
4 PrivateIpRange string `json:"privateIpRange,omitempty"`
5}
6func (c *Client) GetPrivateIpAddressesInfo(args *GetVpcPrivateIpArgs) (*VpcPrivateIpAddressesResult, error)
Parameter Meaning
Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/2kih0m069
Usage example
1vpcID := "vpc-p1eawhw5rx4n" // vpc id
2 privateIPAddresses := []string{"172.17.1.1", "172.17.1.2", "172.17.1.3"} // Pritate IPaddress
3args := &vpc.GetVpcPrivateIpArgs{
4 VpcId: vpcID,
5 PrivateIpAddresses: privateIPAddresses,
6}
7 response, err := client.GetPrivateIpAddressesInfo(args) // Retrieve VPC private IP information
Response Value
Operation succeeded:
1{
2{
3 "vpcPrivateIpAddresses": [
4 {
5 "cidr": "172.17.1.0/24",
6 "privateIpAddress": "172.17.1.1",
7 "privateIpAddressType": "sys_occupancy",
8 "createdTime": "2020-11-19T12:46:01Z"
9 },
10 {
11 "cidr": "172.17.1.0/24",
12 "privateIpAddress": "172.17.1.2",
13 "privateIpAddressType": "dhcp",
14 "createdTime": "2020-06-23T07:50:14Z"
15 },
16 {
17 "cidr": "172.17.1.0/24",
18 "privateIpAddress": "172.17.1.3",
19 "privateIpAddressType": "dhcp",
20 "createdTime": "2020-06-23T07:50:16Z"
21 }
22 ]
23 }
24}
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, refer to example_get_vpc_ip.go
Shut down VPC relay
Function declaration
1type UpdateVpcRelayArgs struct {
2 ClientToken string `json:"-"`
3 VpcId string `json:"vpcId"`
4}
5func (c *Client) ShutdownRelay(updateVpcRelayArgs *UpdateVpcRelayArgs) error
Parameter Meaning Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/Cluccsywt
Usage example
1clientToken := "ca9ab08f-55e1-4675-a55d-6939a8efe3dd"
2vpcID := "vpc-p1eawhw5rx4n"
3args := &vpc.UpdateVpcRelayArgs{
4 ClientToken: clientToken,
5 VpcId: vpcID,
6}
7err := client.ShutdownRelay(args)
Response Value
Operation succeeded:
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, refer to example_shutdown_relay.go
Open VPC relay
Function declaration
1type UpdateVpcRelayArgs struct {
2 ClientToken string `json:"-"`
3 VpcId string `json:"vpcId"`
4}
5func (c *Client) OpenRelay(updateVpcRelayArgs *UpdateVpcRelayArgs) error
Parameter Meaning Refer to the OpenAPI documentation: https://cloud.baidu.com/doc/VPC/s/Lluccn0nc
Usage example
1clientToken := "c587aab8-cc6d-4e36-a7a6-b78339b1469f"
2vpcID := "vpc-x5re9ig1g53q"
3args := &vpc.UpdateVpcRelayArgs{
4 ClientToken: clientToken,
5 VpcId: vpcID, // vpc id
6}
7err := client.OpenRelay(args)
Response Value
Operation succeeded:
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, refer to example_open_relay.go
