Baidu AI Cloud
中国站

百度智能云

Virtual Private Cloud

NAT

Initialization

Confirm Endpoint

When confirming the Endpoint configured when you use the SDK, you can first read the section on NAT 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 NAT, 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 NAT.

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

Register Baidu AI Cloud Account

Create AK/SK

Create a NAT Client

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

Create a NAT Client with AK/SK

Access NAT via AK/SK, and users can create a NAT 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 NATClient 
	 natClient, 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 Acquire AKSK] in the Operation Guide (https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/). 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 VPC.

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 bcc.bj.baidubce.com.

Create NAT Client with STS

Apply for STS token

NAT 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 NAT via STS, you need to apply for an authentication string via client of STS, for the application method.

Create a NAT Client with STS token

After STS is applied, STS Token can be configured in NAT Client to create NAT 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 NAT 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 NAT service with the temporary STS applied, with Endpoint of default value. 
	 natClient, err := vpc.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "bcc.bj.baidubce.com") 
	 if err != nil { 
	 	 fmt.Println("create nat 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 
	 } 
	 natClient.Config.Credentials = stsCredential 
} 

Note: Currently, when STS is used to configure NAT Client, wherever the Endpoint corresponding to NAT 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 NAT

NAT supports HTTPS, and you can use HTTPS to access NAT service in NAT GO SDK by indicating the mode of HTTPS in the Endpoint specified during creation of NAT 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> 
natClient, _ := vpc.NewClient(AK, SK, ENDPOINT) 

Configure NAT Client

To configure parameters of some details of NAT Client, you can use the export field Config of NAT 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 NAT service:

// import "github.com/baidubce/bce-sdk-go/services/vpc" 

// Create NAT 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, _ := bcc.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, _ := bcc.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 NAT, the Config field of NAT 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 NAT 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. 
  1. 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.

NAT Gateway Management

NAT(Network Address Translation) The gateway provides Internet access services for the private network, supports SNAT and DNAT, and enables multiple cloud servers to share public network IP resources to access Internet, and the cloud server to provide Internet services. The NAT gateway can bind EIP instances and shared bandwidth packets to implement a many-to-one or many-to-many address translation service from the internal network IP to the public network IP for the cloud server.

Create an NAT gateway

You can create a nat gateway using the following code:

//import "github.com/baidubce/bce-sdk-go/services/vpc" 

args := &vpc.CreateNatGatewayArgs{ 
	 // Set the name of the nat gateway 
    Name:  name, 
    // Set the vpc id to which the nat gateway belongs 
    VpcId: vpcId, 
    // Set the specifications of the nat gateway 
    Spec:  vpc.NAT_GATEWAY_SPEC_SMALL, 
    // Set eip list of nat gateway 
    Eips:  []string{eip}, 
    // Set the billing information of the nat gateway 
    Billing: &vpc.Billing{ 
        PaymentTiming: vpc.PAYMENT_TIMING_POSTPAID, 
    }, 
} 
result, err := client.CreateNatGateway(args) 
if err != nil { 
    fmt.Println("create nat gateway error: ", err) 
    return 
} 

fmt.Println("create nat gateway success, nat gateway id: ", result.NatId) 

Note: During the creation process, you should pay attention to the following matters:

  • The name of NAT gateway is composed by upper and lower case letters, numbers, and -_ /. special characters, and must start with letters, with a length of 1-65.
  • The size of NAT gateway is divided into three kinds: small (supporting binding a maximum of 5 public network IPs), medium (supporting binding a maximum of 10 public network IPs) and large (supporting binding a maximum of 15 public network IPs).
  • One public network EIP associated with the NAT gateway or one or more EIPs in the shared bandwidth
  • The payment method supports two types: Prepaid and Postpaid. Currently, the monthly prepayment is supported, and the duration range is: [1,2,3,4,5,6,7,8,9,12,24,36]

Query the NAT gateway list

Use the following code to query the list of eligible nat gateways.

//import "github.com/baidubce/bce-sdk-go/services/vpc" 

args := &vpc.ListNatGatewayArgs{ 
	 // Set the vpc id to which the nat gateway belongs, required 
    VpcId: vpcId, 
    // Specify the Id of NAT to be queried. 
    NatId: natId, 
    // Specify the name of NAT to be queried. 
    Name: name, 
    // Specify the EIP bound to NAT to be queried. 
    Ip: ip, 
    // Set the starting position of the query of the nat gateway batch acquisition list 
    Marker: marker, 
    // Set nat gateway aximum number contained in each page, generally not exceeding 1000. The default value is 1000. 
    MaxKeys: maxKeys, 
} 
result, err := client.ListNatGateway(args) 
if err != nil { 
    fmt.Println("list nat gateway error: ", err) 
    return 
} 

// Return to the starting position of the mark query 
fmt.Println("nat 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("nat 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("nat list nextMarker: ", result.NextMarker) 
// Maximum number contained in each page. 
fmt.Println("nat list maxKeys: ", result.MaxKeys) 
// Get list information of nat 
for _, nat := range result.Nats { 
    fmt.Println("nat id: ", nat.Id) 
    fmt.Println("nat name: ", nat.Name) 
    fmt.Println("nat vpcId: ", nat.VpcId) 
    fmt.Println("nat spec: ", nat.Spec) 
    fmt.Println("nat eips: ", nat.Eips) 
    fmt.Println("nat status: ", nat.Status) 
    fmt.Println("nat paymentTiming: ", nat.PaymentTiming) 
    fmt.Println("nat expireTime: ", nat.ExpiredTime) 
} 

Note:

  • It can be queried according to the NAT gateway ID, the NAT gateway name, and EIP bound to the NAT gateway.
  • If you do not provide the query conditions, all NAT Gateway is overwritten by default.
  • vpcId is required parameters:

Query the NAT gateway details

Use the following code to query the detailed information of a specific nat gateway.

//import "github.com/baidubce/bce-sdk-go/services/vpc" 

result, err := client.GetNatGatewayDetail(natId) 
if err != nil { 
    fmt.Println("get nat gateway details error: ", err) 
    return 
} 

// Query to get the id of the nat gateway 
fmt.Println("nat id: ", result.Id) 
// Query to get the name of the nat gateway 
fmt.Println("nat name: ", result.Name) 
// Query to get the vpc id to which the nat gateway belongs 
fmt.Println("nat vpcId: ", result.VpcId) 
// Query to get the size of the nat gateway 
fmt.Println("nat spec: ", result.Spec) 
// Query to get the IP address list of EIP bound to the nat gateway 
fmt.Println("nat eips: ", result.Eips) 
// Query to get the status of the nat gateway 
fmt.Println("nat status: ", result.Status) 
// Query to get the payment method of the nat gateway 
fmt.Println("nat paymentTiming: ", result.PaymentTiming) 
// Query to get the expiration time of the nat gateway 
fmt.Println("nat expireTime: ", result.ExpiredTime) 

Update the NAT gateway name

Use the following code to change the name of the nat gateway.

//import "github.com/baidubce/bce-sdk-go/services/vpc" 

args := &vpc.UpdateNatGatewayArgs{ 
	 // Set the latest name of the nat gateway 
    Name: "TestNatUpdate", 
} 

if err := client.UpdateNatGateway(natId, args); err != nil { 
    fmt.Println("update nat gateway error: ", err) 
    return 
} 

fmt.Printf("update nat gateway %s success.", natId) 

Note: Currently this interface only supports the change of the gateway name attribute.

Bind EIP

Use the following code to bind eip to the nat gateway.

//import "github.com/baidubce/bce-sdk-go/services/vpc" 

args := &vpc.BindEipsArgs{ 
	 // Set the list of bound EIP IDs 
    Eips: []string{eip}, 
} 
if err := client.BindEips(natId, args); err != nil { 
    fmt.Println("bind eips error: ", err) 
    return 
} 

fmt.Println("bind eips success.") 

Note:

  • If the EIP has been bound to EIP, it may be bound only after being unbound.
  • If the shared bandwidth has been bound to the NAT, other IPs in the shared bandwidth can continue to be bound.

Unbind EIP

Use the following code to unbind eip for the nat gateway.

//import "github.com/baidubce/bce-sdk-go/services/vpc" 

args := &vpc.UnBindEipsArgs{ 
	 // Set list of unbound EIP IDs 
    Eips: []string{eip}, 
} 
if err := client.UnBindEips(natId, args); err != nil { 
    fmt.Println("unbind eips error: ", err) 
    return 
} 

fmt.Println("unbind eips success.") 

Release the NAT gateway

Use the following code to release a specific nat gateway.

//import "github.com/baidubce/bce-sdk-go/services/vpc" 

if err := client.DeleteNatGateway(natId, clientToken); err != nil { 
    fmt.Println("delete nat gateway error: ", err) 
    return 
} 

fmt.Printf("delete nat gateway %s success.", natId) 

Note: The prepaid and unexpired NAT gateway cannot be released.

NAT gateway renewal

Use the following interface to complete the renewal operation of the NAT gateway and extend the expiration time.

//import "github.com/baidubce/bce-sdk-go/services/vpc" 

args := &vpc.RenewNatGatewayArgs{ 
	 // Set the order information for nat gateway renewal 
    Billing: &vpc.Billing{ 
        Reservation: &vpc.Reservation{ 
            ReservationLength:   1, 
            ReservationTimeUnit: "month", 
        }, 
    }, 
} 
if err := client.RenewNatGateway(natId, args); err != nil { 
    fmt.Println("renew nat gateway error: ", err) 
    return 
} 

fmt.Printf("renew nat gateway %s success.", natId) 

Note:

  • The postpaid NAT gateway cannot be renewed.
Previous
Route
Next
Vpn