Instance
Create an instance (by specifying instance package specifications)
You can create BCC instances with the following code, including general-purpose BCC instances, storage-optimized BCC instances, compute-optimized BCC instances, big data BCC instances, GPU-based BCC instances and FPGA-based BCC instances:
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8// Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12// Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 IsOpenHostnameDomain := true
15 AutoSeqSuffix := true
16 RelationTag := false
17 IsOpenIpv6 := true
18 CdsAutoRenew := true
19 argsV2 := &api.CreateInstanceBySpecArgsV2{
20// Image ID
21 ImageId: "m-***",
22// Specification
23 Spec: "bcc.g5.c2m8",
24// Size of system disk for virtual machine instance to be created, in GB. The default is 40 GB, with a range of [40, 2048]GB. Sizes exceeding 40 GB are charged according to cloud disk server prices. Note that the specified size of system disk must meet the minimum disk space requirement of the image used.
25 RootDiskSizeInGb: 20,
26// Medium of system disk for virtual machine instance to be created. By default, an SSD cloud disk server is used
27 RootDiskStorageType: api.StorageTypeEnhancedPl1,
28// List of CDS disks to be created
29 CreateCdsList: []api.CreateCdsModel{
30 {
31 CdsSizeInGB: 50,
32 StorageType: api.StorageTypeEnhancedPl1,
33 },
34 },
35// Public network bandwidth, in Mbps. It must be an integer between 0 and 200. 0 indicates that no public IP will be assigned, defaulting to 0 Mbps
36 NetWorkCapacityInMbps: 10,
37// Length: 1 - 65 bytes, starting with a letter. It can contain letters, numbers and the characters -_/. If this parameter is not provided, the service will automatically generate a name.
38 EipName: "eipN***",
39// Charge type for public network bandwidth. Optional parameters are detailed in internetChargeType. If internetChargeType is not specified, the default bill type is the same as that for BCC instances: prepaid instances default to subscription bandwidth billing, while postpaid instances default to billing based on actual bandwidth use.
40 InternetChargeType: "BANDWIDTH_PREPAID",
41// Count of virtual machine instances to be created (purchased) in batch, which must be an integer greater than 0 (optional). The default is 1
42 PurchaseCount: 1,
43// Virtual machine name (optional). By default, no name is specified. If a name is specified: For batch creation, the name serves as a prefix.
44//, suffix generation method: name{ -sequence number}. If no name is specified, it will be automatically generated as follows: {instance-eight-digit random string-sequence number}.
45// Note: The random string is generated from 0-9a-z; the sequence number increments according to the magnitude of the count. If the count is 100, the sequence number increments from 000-100; if the count is 10, it increments from 00-10.
46// Support uppercase and lowercase letters, numbers, Chinese characters, and -_ /. special characters, starting with a letter, and with a length of 1-65.
47 Name: "instance-***",
48// Hostname of the virtual machine. By default, no hostname is specified. If a hostname is specified: For batch creation, the hostname serves as a prefix. The backend will append a suffix, generated as follows: name{-sequence number}.
49 Hostname: "hostn***",
50// Whether to automatically generate the hostname domain (optional parameter) Yes: true No: false
51 IsOpenHostnameDomain: &IsOpenHostnameDomain,
52// Whether to automatically generate sequential suffixes for name and hostname (optional parameter) Yes: true No: false
53 AutoSeqSuffix: &AutoSeqSuffix,
54// Whether to enable IPv6 for the instance to be created. IPv6 can only be enabled if both the image and subnet support it. True indicates enable, false indicates disable, and not specifying the parameter indicates automatic adaptation to the IPv6 support status of the image and subnet
55 IsOpenIpv6: &IsOpenIpv6,
56// Administrator password for the instance to be created: 8-16 characters; it must contain English letters, numbers and symbols (limited to !@#$%^*()) simultaneously.
57 AdminPass: "***",
58// Order and billing-related parameters
59 Billing: api.Billing{
60 PaymentTiming: api.PaymentTimingPrePaid,
61 Reservation: &api.Reservation{
62 ReservationLength: 1,
63 ReservationTimeUnit: "Month",
64 },
65 },
66// Specify zone information. By default, it is empty and automatically selected by the system. The list of availability zones can be queried by calling the Query Availability Zone List API. The naming convention for zoneName is lowercase "country-region-availability zone sequence", such as "cn-bj-a" for Beijing availability zone A.
67 ZoneName: "cn-bj-a",
68// Specify subnet information. If empty, it is the default subnet
69 SubnetId: "sbn-***",
70// Specify security group information. If empty, it is the default security group
71 SecurityGroupIds: []string{"g-***"},
72// Whether the specified tag for the instance to be created needs to be associated with an existing tag key; default is false. Note: When the value is set to true, it is necessary to ensure that the tag key already exists
73 RelationTag: &RelationTag,
74// Whether CDS auto-renewal is enabled. Yes: true No: false
75 CdsAutoRenew: &CdsAutoRenew,
76// Automatic snapshot policy ID
77 AspId: "asp-***",
78// Specify the list of IDs of deployment groups where the instance is located
79 DeployIdList: []string{"dset-***"},
80// Specify the elastic high-performance computing cluster ID; only packages with RDMA networks are supported
81 EhcClusterId: "ehc-***",
82// A list of short IDs for elastic network interface cards to be mounted. During batch creation, elastic network interface cards will be evenly distributed among instances based on the count provided. Ensure that the count of elastic network interface card IDs provided is an integer multiple of the count of instances and that the count of ENIs assigned to each instance does not exceed the maximum count that can be mounted by the instance. Elastic baremetal compute (EBC) instances are not currently supported. The maximum number of eniIds is 5000.
83 EniIds: []string{"eni-***"},
84 }
85 createResult, err := bccClient.CreateInstanceBySpecV2(argsV2)
86 fmt.Println(err)
87 fmt.Println(createResult)
88}
Prompt:
- Creating a BCC request is an asynchronous process. A return code of 200 indicates that the order has been generated, and the progress of creating the BCC virtual machine can be monitored by checking the returned instance ID information.
- This API is used to create one or more identical virtual machine instances.
- Creating an instance requires real-name verification. Those who have not completed the verification can navigate to the Security Certification section in the Baidu Open Cloud Official Website Console to complete real-name certification.
- To create a postpaid instance, the account's cash balance combined with general coupons must exceed 100. For prepaid instances, the account's cash balance must at least match the cost of the instance.
- Batch creation is supported. If any instance fails during batch creation, all instances will be rolled back, resulting in no successful creations. If CDS is included in the creation, it will also be rolled back.
- By default, an instance can attach up to five cloud disk servers.
- When creating CDS disks and temporary data disks, the disk capacity must be an exact multiple of 5.
- Instance creation allows for the creation and addition of temporary data disks, but does not support creating or adding temporary data disks independently.
- Temporary data disks cannot be attached, detached, or deleted after creation.
- The maximum size of a temporary data disk for a general-purpose instance is capped at 500 GB.
- When specifying a subnet and security group during creation, both must be specified together or left unspecified. The chosen subnet and security group must belong to the same VPC. If neither is specified, the default subnet and security group will be used.
- Specify the public IP bandwidth during creation, with charges based on the selected bandwidth.
- The creation API is asynchronous. Instance status can be queried using the Query Instance Details API.
- Each instance is limited to purchasing a maximum of one temporary data disk.
- The default type for a temporary data disk in an instance is hp1.
- When creating a storage-optimized instance, you need to purchase a temporary data disk. Specify its size through the ephemeralDisks field. The default is an NVMe-type data disk, so you don't need to enter a value unless a specific size is required.
Create a spot instance
You can create BCC instances with the following code:
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8// Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12// Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 args := &api.CreateInstanceArgs{
15// Image ID
16 ImageId: "m-***",
17// Type of virtual machine instance to be created
18 InstanceType: "N6",
19 CpuCount: 1,
20 MemoryCapacityInGB: 4,
21 BidModel: "market",
22// Size of system disk for virtual machine instance to be created, in GB. The default is 40 GB, with a range of [40, 2048]GB. Sizes exceeding 40 GB are charged according to cloud disk server prices. Note that the specified size of system disk must meet the minimum disk space requirement of the image used.
23 RootDiskSizeInGb: 20,
24// Medium of system disk for virtual machine instance to be created. By default, an SSD cloud disk server is used
25 RootDiskStorageType: api.StorageTypeEnhancedPl1,
26// List of CDS disks to be created
27 CreateCdsList: []api.CreateCdsModel{
28 {
29 CdsSizeInGB: 50,
30 StorageType: api.StorageTypeEnhancedPl1,
31 },
32 },
33// Public network bandwidth, in Mbps. It must be an integer between 0 and 200. 0 indicates that no public IP will be assigned, defaulting to 0 Mbps
34 NetWorkCapacityInMbps: 10,
35// Length: 1 - 65 bytes, starting with a letter. It can contain letters, numbers and the characters -_/. If this parameter is not provided, the service will automatically generate a name.
36 EipName: "eipN***",
37// Count of virtual machine instances to be created (purchased) in batch, which must be an integer greater than 0 (optional). The default is 1
38 PurchaseCount: 1,
39// Virtual machine name (optional). By default, no name is specified. If a name is specified: For batch creation, the name serves as a prefix.
40//, suffix generation method: name{ -sequence number}. If no name is specified, it will be automatically generated as follows: {instance-eight-digit random string-sequence number}.
41// Note: The random string is generated from 0-9a-z; the sequence number increments according to the magnitude of the count. If the count is 100, the sequence number increments from 000-100; if the count is 10, it increments from 00-10.
42// Support uppercase and lowercase letters, numbers, Chinese characters, and -_ /. special characters, starting with a letter, and with a length of 1-65.
43 Name: "instance-***",
44// Hostname of the virtual machine. By default, no hostname is specified. If a hostname is specified: For batch creation, the hostname serves as a prefix. The backend will append a suffix, generated as follows: name{-sequence number}.
45 Hostname: "hostn***",
46// Administrator password for the instance to be created: 8-16 characters; it must contain English letters, numbers and symbols (limited to !@#$%^*()) simultaneously.
47 AdminPass: "***",
48// Order and billing-related parameters
49 Billing: api.Billing{
50 PaymentTiming: api.PaymentTimingPrePaid,
51 Reservation: &api.Reservation{
52 ReservationLength: 1,
53 ReservationTimeUnit: "Month",
54 },
55 },
56// Specify zone information. By default, it is empty and automatically selected by the system. The list of availability zones can be queried by calling the Query Availability Zone List API. The naming convention for zoneName is lowercase "country-region-availability zone sequence", such as "cn-bj-a" for Beijing availability zone A.
57 ZoneName: "cn-bj-a",
58// Specify subnet information. If empty, it is the default subnet
59 SubnetId: "sbn-***",
60// Specify security group information. If empty, it is the default security group
61 SecurityGroupIds: []string{"g-***"},
62// Automatic snapshot policy ID
63 AspId: "asp-***",
64// Specify the list of IDs of deployment groups where the instance is located
65 DeployIdList: []string{"dset-***"},
66 }
67 createResult, err := bccClient.CreateBidInstance(args)
68 fmt.Println(err)
69 fmt.Println(createResult)
70}
Create an instance (deprecated API; it is recommended to use the "Create Instance" API instead (by specifying instance package specifications))
You can create BCC instances with the following code, including dedicated instances, general-purpose type I instances, general-purpose type II instances, storage-optimized BCC instances and compute-optimized BCC instances
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8// Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12// Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 IsOpenHostnameDomain := true
15 AutoSeqSuffix := true
16 RelationTag := false
17 IsOpenIpv6 := true
18 CdsAutoRenew := true
19 argsV2 := &api.CreateInstanceArgsV2{
20// Image ID
21 ImageId: "m-***",
22// Type of virtual machine instance to be created
23 InstanceType: "N6",
24// CPU core count for instance
25 CpuCount: 1,
26// Memory size of the instance, in GB
27 MemoryCapacityInGB: 4,
28// Size of system disk for virtual machine instance to be created, in GB. The default is 40 GB, with a range of [40, 2048]GB. Sizes exceeding 40 GB are charged according to cloud disk server prices. Note that the specified size of system disk must meet the minimum disk space requirement of the image used.
29 RootDiskSizeInGb: 20,
30// Medium of system disk for virtual machine instance to be created. By default, an SSD cloud disk server is used
31 RootDiskStorageType: api.StorageTypeEnhancedPl1,
32// List of CDS disks to be created
33 CreateCdsList: []api.CreateCdsModel{
34 {
35 CdsSizeInGB: 50,
36 StorageType: api.StorageTypeEnhancedPl1,
37 },
38 },
39// Public network bandwidth, in Mbps. It must be an integer between 0 and 200. 0 indicates that no public IP will be assigned, defaulting to 0 Mbps
40 NetWorkCapacityInMbps: 10,
41// Length: 1 - 65 bytes, starting with a letter. It can contain letters, numbers and the characters -_/. If this parameter is not provided, the service will automatically generate a name.
42 EipName: "eipN***",
43// Charge type for public network bandwidth. Optional parameters are detailed in internetChargeType. If internetChargeType is not specified, the default bill type is the same as that for BCC instances: prepaid instances default to subscription bandwidth billing, while postpaid instances default to billing based on actual bandwidth use.
44 InternetChargeType: "BANDWIDTH_PREPAID",
45// Count of virtual machine instances to be created (purchased) in batch, which must be an integer greater than 0 (optional). The default is 1
46 PurchaseCount: 1,
47// Virtual machine name (optional). By default, no name is specified. If a name is specified: For batch creation, the name serves as a prefix.
48//, suffix generation method: name{ -sequence number}. If no name is specified, it will be automatically generated as follows: {instance-eight-digit random string-sequence number}.
49// Note: The random string is generated from 0-9a-z; the sequence number increments according to the magnitude of the count. If the count is 100, the sequence number increments from 000-100; if the count is 10, it increments from 00-10.
50// Support uppercase and lowercase letters, numbers, Chinese characters, and -_ /. special characters, starting with a letter, and with a length of 1-65.
51 Name: "instance-***",
52// Hostname of the virtual machine. By default, no hostname is specified. If a hostname is specified: For batch creation, the hostname serves as a prefix. The backend will append a suffix, generated as follows: name{-sequence number}.
53 Hostname: "hostn***",
54// Whether to automatically generate the hostname domain (optional parameter) Yes: true No: false
55 IsOpenHostnameDomain: &IsOpenHostnameDomain,
56// Whether to automatically generate sequential suffixes for name and hostname (optional parameter) Yes: true No: false
57 AutoSeqSuffix: &AutoSeqSuffix,
58// Whether to enable IPv6 for the instance to be created. IPv6 can only be enabled if both the image and subnet support it. True indicates enable, false indicates disable, and not specifying the parameter indicates automatic adaptation to the IPv6 support status of the image and subnet
59 IsOpenIpv6: &IsOpenIpv6,
60// Administrator password for the instance to be created: 8-16 characters; it must contain English letters, numbers and symbols (limited to !@#$%^*()) simultaneously.
61 AdminPass: "***",
62// Order and billing-related parameters
63 Billing: api.Billing{
64 PaymentTiming: api.PaymentTimingPrePaid,
65 Reservation: &api.Reservation{
66 ReservationLength: 1,
67 ReservationTimeUnit: "Month",
68 },
69 },
70// Specify zone information. By default, it is empty and automatically selected by the system. The list of availability zones can be queried by calling the Query Availability Zone List API. The naming convention for zoneName is lowercase "country-region-availability zone sequence", such as "cn-bj-a" for Beijing availability zone A.
71 ZoneName: "cn-bj-a",
72// Specify subnet information. If empty, it is the default subnet
73 SubnetId: "sbn-***",
74// Specify security group information. If empty, it is the default security group
75 SecurityGroupIds: []string{"g-***"},
76// Whether the specified tag for the instance to be created needs to be associated with an existing tag key; default is false. Note: When the value is true, ensure that the tag key already exists
77 RelationTag: &RelationTag,
78// Whether CDS auto-renewal is enabled. Yes: true No: false
79 CdsAutoRenew: &CdsAutoRenew,
80// Automatic snapshot policy ID
81 AspId: "asp-***",
82// Specify the list of IDs of deployment groups where the instance is located
83 DeployIdList: []string{"dset-***"},
84 }
85 createResult, err := bccClient.CreateInstanceV2(argsV2)
86 fmt.Println(err)
87 fmt.Println(createResult)
88}
Prompt:
- Creating a BCC request is an asynchronous process. A return code of 200 indicates that the order has been generated, and the progress of creating the BCC virtual machine can be monitored by checking the returned instance ID information.
- This API is used to create one or more identical virtual machine instances.
- Creating an instance requires real-name verification. Those who have not completed the verification can navigate to the Security Certification section in the Baidu Open Cloud Official Website Console to complete real-name certification.
- To create a postpaid instance, the account's cash balance combined with general coupons must exceed 100. For prepaid instances, the account's cash balance must at least match the cost of the instance.
- Batch creation is supported. If any instance fails during batch creation, all instances will be rolled back, resulting in no successful creations. If CDS is included in the creation, it will also be rolled back.
- By default, an instance can attach up to five cloud disk servers.
- When creating CDS disks and temporary data disks, the disk capacity must be an exact multiple of 5.
- Instance creation allows for the creation and addition of temporary data disks, but does not support creating or adding temporary data disks independently.
- Temporary data disks cannot be attached, detached, or deleted after creation.
- The maximum size of a temporary data disk for a general-purpose instance is capped at 500 GB.
- When specifying a subnet and security group during creation, both must be specified together or left unspecified. The chosen subnet and security group must belong to the same VPC. If neither is specified, the default subnet and security group will be used.
- Specify the public IP bandwidth during creation, with charges based on the selected bandwidth.
- The creation API is asynchronous. Instance status can be queried using the Query Instance Details API.
- This API enables you to designate a dedicated server for instance creation. Dedicated instances are not charged. These instances allow only the creation of temporary disks and the specification of disk types through ephemeralDisks.
- Each instance is limited to purchasing a maximum of one temporary data disk.
- The default type for a temporary data disk in an instance is hp1.
- Use the instanceType field to select the type of virtual machine (VM) you want to create. To see the currently supported VM types, refer to InstanceType. The parameters (instanceType, cpuCount, and memoryCapacityInGB) define the required machine type and configuration.
- When creating a storage-optimized instance, you need to purchase a temporary data disk. Specify its size through the ephemeralDisks field. The default is an NVMe-type data disk, so you don't need to enter a value unless a specific size is required.
- For detailed instructions on creating requests, please refer to the BCC API documentation Create Instance
- You need to use specified configurations (including CPU, memory, local data disk, FPGA card type and a dedicated image) to create an FPGA BCC virtual machine. For details, please refer to the BCC API documentation Optional Specification Configuration of FPGA BCC
- You need to use specified configurations (including CPU, memory, local data disk and GPU card type) to create an GPU BCC virtual machine. For details, please refer to the BCC API documentationOptional Specification Configuration of GPU BCC.
Cancel a spot instance order
You can cancel a spot instance order with the following code
1cancelBidOrderRequest := &CancelBidOrderRequest{
2 // Order ID
3 OrderId string "orderId"
4}
5if err := bccClient.CancelBidOrder(cancelBidOrderRequest); err != nil {
6 fmt.Println("CancelBidOrderRequest failed: ", err)
7} else {
8 fmt.Println("CancelBidOrderRequest success.")
9}
Query spot instance packages
You can query spot instance packages with the following code
1if res, err := bccClient.ListBidFlavor(); err != nil {
2 fmt.Println("List bidding instance flavors failed: ", err)
3} else {
4 fmt.Println("List bidding instance flavors success, result: ", res)
5}
Query the package list
Query package list using the following code
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 args := &api.ListFlavorSpecArgs{
15 Specs: "bcc.g5.c2m8",
16 ZoneName: "cn-bj-b",
17 }
18
19 if res, err := bccClient.ListFlavorSpec(args); err != nil {
20 fmt.Println("Get flavor list failed: ", err)
21 } else {
22 fmt.Println("Get flavor list success, result: ", res)
23 }
24}
Query the market price of spot instances
You can query the market price of spot instances with the following code
1createCdsList := []api.CreateCdsModel{{
2// CDS disk capacity must be an integer greater than 0, in GB, ranging from 0 - 5120G, optional parameter
3 CdsSizeInGB: 40,
4// Set CDS disk storage type. It is high-performance type by default, optional parameter
5 StorageType: api.StorageTypeHP1,
6// Set snapshot ID
7 SnapshotId: "your-snapshot-id",
8// Set encryption key, true or false
9 EncryptKey: true,
10}}
11tagList := []model.TagModel{{
12// Set the tagKey to be queried
13 TagKey: "your-tag-key",
14// Set the tagValue to be queried
15 TagValue: "your-tag-value",
16}}
17args := &api.GetBidInstancePriceArgs{
18// Use uuid to generate an ASCII string not exceeding 64 characters
19 ClientToken: "random-uuid",
20// Set the virtual machine instance type to be queried; for specific optional types, refer to InstanceType
21 InstanceType: "your-choose-instance-type",
22// Set the CPU core count for the virtual machine instance to be queried
23 CpuCount: 1,
24// Set the memory capacity for the virtual machine instance to be queried
25 MemoryCapacityInGB: 2,
26// Set the size of system disk for the virtual machine instance to be queried, in GB. The default is 40 GB, with a range of [40, 100]GB. Sizes exceeding 40 GB are charged according to cloud disk server prices. Note that the specified size of system disk must meet the minimum disk space requirement of the image used.
27 RootDiskSizeInGb: 45,
28// Medium of system disk for virtual machine instance to be queried. By default, an SSD cloud disk server is used. The disk type for the system disk can be specified; refer to StorageType
29 RootDiskStorageType: api.StorageTypeCloudHP1,
30// Set the CDS disk list to be queried
31 CreateCdsList: createCdsList,
32// Set the count of virtual machine instances to be queried (purchased) in batches, which must be an integer greater than 0 (optional). The default is 1
33 PurchaseCount: 1,
34// Set the virtual machine name; optional parameter
35 Name: "your-choose-instance-name",
36// Set the administrator password for the instance (8-16 characters; it must contain English letters, numbers, and symbols (limited to !@#$%^*()) simultaneously); optional parameter
37 AdminPass: "your-admin-pass",
38// Set the key pair ID to be bound to the instance to be queried; optional parameter
39 KeypairId: "your-keypair-id",
40// Set the automatic snapshot policy ID; optional parameter
41 AspId: "your-asp-id",
42// Set the image ID for the virtual machine instance to be queried; optional parameter
43 ImageId: "your-image-id",
44// Set the bidding model for spot instances; market price: "market" custom: "custom", optional parameter
45 BidModel: "your-bid-model",
46// If it is a custom bidding and the bidding price is less than the market price, creation is not allowed. It is valid only when bidModel='custom', and the optional parameter is
47 BidPrice: "your-bid-price",
48// Set the public network bandwidth in Mbps. The value must be an integer between 0 - 200. 0 indicates that no public IP is allocated. The default value is 0 Mbps and the optional parameter is
49 NetWorkCapacityInMbps: 20,
50// Set whether the specified tags for the instance to be queried need to be associated with existing tag keys. The default value is false. Note: When the value is set to true, it is necessary to ensure that the tag key already exists and the optional parameter is
51 RelationTag: false,
52// Set the tag list to be queried, and the optional parameter is
53 Tags: tagList,
54// Set security group information. If empty, it is the default security group and the optional parameter is
55 SecurityGroupId: "your-security-group-id",
56// Set subnet information. If empty, it is the default subnet and the optional parameter is
57 SubnetId: "your-subnet-id",
58// Set the specified zone information. By default, it is empty and automatically selected by the system, and the optional parameter is
59 ZoneName: "your-zone-name",
60// Set the charge type of the public network bandwidth, and the optional parameter is
61 InternetChargeType: "your-internet-charge-type",
62}
63if res, err := bccClient.GetBidInstancePrice(args); err != nil {
64 fmt.Println("Get bidding instance price failed: ", err)
65} else {
66 fmt.Println("Get bidding instance price success, result: ", res)
67}
Query the inventory of instance packages
Retrieve inventory information based on the specified instance package details.
1// Instance type
2instanceType := "instanceType"
3 // Count of CPU cores
4cpuCount := cpuCount
5 // Memory capacity (GB)
6memoryCapacityInGB := memoryCapacityInGB
7 // Availability zone name
8zoneName := "zoneNamen"
9 // GPU card type; GPU and VGPU can be specified
10gpuCard := "gpuCard"
11 // GPU card count; GPU and VGPU can be specified
12cardCount := "cardCount"
13 // Local disk information
14ephemeralDisks := []EphemeralDisks{{
15 "storageType": "ssd",
16 "sizeInGB": sizeInGB,
17}}
18args := &api.CreateInstanceStockArgs{
19 InstanceType: instanceType,
20 CpuCount: cpuCount,
21 MemoryCapacityInGB: memoryCapacityInGB,
22 ZoneName: zoneName,
23 GpuCard: gpuCard,
24 CardCount: cardCount,
25 EphemeralDisks: ephemeralDisks,
26}
27if res, err := bccClient.GetInstanceCreateStock(args); err != nil {
28 fmt.Println("GetInstanceCreateStock failed: ", err)
29} else {
30 fmt.Println("GetInstanceCreateStock success: ", res)
31}
Query instance scaling inventory
Query instance resizing allowance
1// Instance ID
2instanceId := "instanceId"
3 // Count of CPU cores
4cpuCount := cpuCount
5 // Memory capacity (GB)
6memoryCapacityInGB := memoryCapacityInGB
7args := &api.CreateInstanceStockArgs{
8 InstanceId: instanceId,
9 CpuCount: cpuCount,
10 MemoryCapacityInGB: memoryCapacityInGB,
11}
12if res, err := bccClient.ResizeInstanceStockArgs(args); err != nil {
13 fmt.Println("ResizeInstanceStockArgs failed: ", err)
14} else {
15 fmt.Println("ResizeInstanceStockArgs success: ", res)
16}
Query deployment group details
You can query deployment group details by the deployment group ID with the following code
1// Set the deploySetID to be queryed
2deploySetID := "your-choose-deploy-set-id"
3if res, err := bccClient.GetDeploySet(deploySetID); err != nil {
4 fmt.Println("Delete deploy set failed: ", err)
5} else {
6 fmt.Println("Get deploy set success: ", res)
7}
Remove the relationship between an instance and its deployment group
You can delete the relationship between an instance and a deployment group with the following code
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 queryArgs := &api.DelInstanceDeployArgs{
15 DeploySetId: "dset-***", // deployment group ID
16 InstanceIds: []string{"i-***", "i-***"}, // List of instance IDs
17 }
18 res, err := bccClient.DelInstanceDeploySet(queryArgs)
19 fmt.Println(err)
20 fmt.Println(res)
21}
Query the list of BCC instances eligible for no charge for stopped instances
Query the list of BCC instances eligible for no charge for stopped instances:
1listInstanceArgs := &ListInstanceArgs{
2 // Starting position of batch list query, which is a system-generated string
3 Marker string
4 // Set the size of the returned data; the default is 1,000
5. MaxKeys int
6 // Filter by intranet IP
7 InternalIp string
8 // Filter by DedicatedHostId
9 DedicatedHostId string
10 // Filter by ZoneName
11 ZoneName string
12 // Filter by KeypairId
13 KeypairId string
14}
15if res, err := bccClient.GetInstanceNoChargeList(listInstanceArgs); err != nil {
16 fmt.Println("GetInstanceNoChargeList failed: ", err)
17} else {
18 fmt.Println("GetInstanceNoChargeList success, result: ", res)
19}
Query instance list
You can query the list of BCC virtual machine instances with the following code, supporting filtering by intranet IP, dedicated server ID and availability zone name
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 listArgs := &api.ListInstanceArgs{
15 // Starting position of batch list query, which is a system-generated string
16 Marker: "i-***",
17 // Maximum number of items included per page, maximum: 1,000, default: 1,000
18 MaxKeys: 1,
19 // Intranet IP
20 InternalIp: "192.168.***.***",
21 // Dedicated server ID
22 DedicatedHostId: "d-***",
23 // Availability zone information
24 ZoneName: "cn-bj-d",
25 // Multiple instance IDs, separated by English commas, maximum 100 IDs
26 InstanceIds: "i-***",
27 // Multiple instance names, separated by English commas, maximum 100 IDs
28 InstanceNames: "instance-***",
29 // Multiple CDS disk IDs, separated by English commas, maximum 100
30 CdsIds: "v-***",
31 // Multiple deployment group IDs, separated by English commas, maximum 100
32 DeploySetIds: "dset-***",
33 // Multiple security group IDs, separated by English commas, maximum 100 IDs
34 SecurityGroupIds: "g-***",
35 // Payment method (Prepaid/Postpaid)
36 PaymentTiming: "Postpaid",
37 // Instance status (Recycled/Running/Stopped/Stopping/Starting)
38 Status: "Running",
39 // Multiple tags, separated by commas, format: tagKey:tagValue or tagKey
40 Tags: "***",
41 // vpcId, which can only be used in combination with the privateIps query parameter
42 VpcId: "vpc-***",
43 // Multiple intranet IPs, separated by English commas, maximum 100 IPs, which must be used in combination with vpcId
44 PrivateIps: "192.168.***.***",
45 }
46 res, err := bccClient.ListInstances(listArgs)
47 fmt.Println(err)
48 fmt.Println(res)
49}
Query recycle bin instance list
You can query the list of BCC virtual machine instances in the recycle bin with the following code, supporting filtering by virtual machine ID and name:
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "http://bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 // Starting position of batch list query, which is a system-generated string and optional
15 marker := "marker***"
16 // Maximum number of items included per page, maximum 1,000. The default is 1,000, optional
17 maxKeys := 100
18 // Set bill type for query; optional: Prepaid for prepay and Postpaid for postpay. If not specified, it means that both types are selected
19 paymentTiming := "Postpaid"
20 // Set virtual machine ID for query, optional
21 instanceId := "i-***"
22 // Set virtual machine name for query, optional
23 name := "instance***"
24 // Set recycle start time (Beijing time) of virtual machine for query, optional (closed interval)
25 recycleBegin := "2023-11-29T09:12:35Z"
26 // Set recycle end time (Beijing time) of virtual machine for query, optional (open interval)
27 recycleEnd := "2023-11-30T09:12:35Z"
28 args := &api.ListRecycleInstanceArgs{
29 Marker: marker,
30 MaxKeys: maxKeys,
31 PaymentTiming: paymentTiming,
32 InstanceId: instanceId,
33 Name: name,
34 RecycleBegin: recycleBegin,
35 RecycleEnd: recycleEnd,
36 }
37 result, err := bccClient.ListRecycleInstances(args)
38 if err != nil {
39 fmt.Println("list instance failed:", err)
40 } else {
41 fmt.Println("list instance success: ", result)
42 }
43}
Query the details of a specified instance
You can query the detailed information of the specified BCC virtual machine with the following code
1// Set instanceId to be operated
2instanceId := "your-choose-instance-id"
3result, err := client.GetInstanceDetail(instanceId)
4if err != nil {
5 fmt.Println("get instance detail failed:", err)
6} else
7 fmt.Println("get instance detail success ", result)
8}
Start an instance
You can start an instance with the following code
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5)
6func main() {
7 // Set your AK, SK and the endpoint to be accessed
8 ak := "ak"
9 sk := "sk"
10 endpoint := "http://bcc.bj.baidubce.com"
11 // Create a BCC client
12 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
13 // Set instanceId to be operated
14 instanceId := "i-***"
15 err := bccClient.StartInstance(instanceId)
16 if err != nil {
17 fmt.Println("start instance failed:", err)
18 } else {
19 fmt.Println("start instance success")
20 }
21}
Prompt:
- The instance must be in the Stopped status for this API call to succeed; otherwise, a 409 error will be returned.
- Once the API is called, instances will enter the Starting status
Stop an instance
You can stop an instance with the following code
1// You can forcibly stop an instance with the following code.
2err := client.StopInstance(instanceId, true)
3if err != nil {
4 fmt.Println("stop instance failed:", err)
5} else {
6 fmt.Println("stop instance success")
7}
Stop an instance (support forced stop and no charge for stopped instances)
You can stop an instance with the following code:
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5)
6func main() {
7 // Set your AK, SK and the endpoint to be accessed
8 ak := "ak"
9 sk := "sk"
10 endpoint := "http://bcc.bj.baidubce.com"
11 // Create a BCC client
12 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
13 err := bccClient.StopInstanceWithNoCharge(
14 // Instance ID to be stopped
15 "i-***",
16 // Specify whether to forcibly stop instance. Options: true, false. The default is false
17 true,
18 // Specify whether to perform no charge for stopped instances. Options: true, false. The default is false
19 true)
20 fmt.Println(err)
21}
Prompt:
- Once the instance has been successfully stopped, the system will transition to the "Stopped" status in the background.
- This operation is only applicable to instances in the Running status; otherwise, a 409 error will occur.
- The instance supports forced stopping, similar to a power-off operation, which might lead to the loss of data that hasn't been saved to the disk in the instance's OS.
Reboot an instance
You can reboot an instance with the following code
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5)
6func main() {
7 // Set your AK, SK and the endpoint to be accessed
8 ak := "ak"
9 sk := "sk"
10 endpoint := "http://bcc.bj.baidubce.com"
11 // Create a BCC client
12 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
13 // Set instanceId to be operated
14 instanceId := "i-***"
15 err := bccClient.RebootInstance(instanceId, true)
16 if err != nil {
17 fmt.Println("reboot instance failed:", err)
18 } else {
19 fmt.Println("reboot instance success")
20 }
21}
Prompt:
- This operation is only applicable to instances in the Running status; otherwise, a 409 error will occur.
- After a successful API call, the instances will enter the Starting status.
- It supports forced reboot, which is similar to a power failure reboot on a traditional server and may lead to the loss of data not saved to the disk from the instance's OS.
Modify the instance password
You can modify the instance password with the following code
1 package main
2 import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6 )
7 func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 // Instance ID
15 instanceId := "i-***"
16 args := &api.ChangeInstancePassArgs{
17 // Instance administrator password
18 AdminPass: "***",
19 }
20 err := bccClient.ChangeInstancePass(instanceId, args)
21 if err != nil {
22 fmt.Println("change instance password failed:", err)
23 } else {
24 fmt.Println("change instance password success")
25 }
26 }
Prompt: This API can only be called for instances in the Running or Stopped status; otherwise, a 409 error will be returned.
Modify instance attributes
You can modify instance attributes with the following code
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "http://bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 // Set instanceId to be operated
15 instanceId := "i-***"
16 args := &api.ModifyInstanceAttributeArgs{
17 // Modify name of instance
18 Name: "Instance***",
19 }
20 err := bccClient.ModifyInstanceAttribute(instanceId, args)
21 if err != nil {
22 fmt.Println("modify instance failed:", err)
23 } else {
24 fmt.Println("modify instance success")
25 }
26}
Prompt:
- Currently, this API only supports modifying the instance name or the count of network interface card queues
Modify instance description
You can modify instance description with the following code
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "http://bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 // Set instanceId to be operated
15 instanceId := "i-***"
16 modifyArgs := &api.ModifyInstanceDescArgs{
17 // Modify description
18 Description: "test modify",
19 }
20 err := bccClient.ModifyInstanceDesc(instanceId, modifyArgs)
21 if err != nil {
22 fmt.Println("modify instance failed:", err)
23 } else {
24 fmt.Println("modify instance success")
25 }
26}
Modify instance hostname
You can modify instance hostname with the following code
1 package main
2 import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6 )
7 func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14
15 // Set instanceId to be operated
16 instanceId := "i-***"
17 args := &api.ModifyInstanceHostnameArgs{
18 // Set new hostname to be modified
19 Hostname: "new-hostname***",
20 // Set whether to enable the domain, optional: true indicates enable, while false and null indicate disable
21 IsOpenHostnameDomain: true,
22 // Set whether to automatically reboot; optional: true indicates reboot, while false and null indicate no reboot
23 Reboot: true,
24 }
25 err := client.ModifyInstanceHostname(instanceId, args)
26 if err != nil {
27 fmt.Println("modify instance hostname failed:", err)
28 } else {
29 fmt.Println("modify instance hostname success")
30 }
31 }
Reinstall an instance
You can reinstall an instance with the following code
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8// Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12// Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 IsOpenHostEye := true
15 IsPreserveData := true
16 args := &api.RebuildInstanceArgsV2{
17// Specified image ID
18 ImageId: "m-***",
19// Machine password (8-16 characters, it must contain English letters, numbers, and symbols (limited to !@#$%^*()). The password must be encrypted for transmission
20 AdminPass: "***",
21// Key pair ID to be bound to the instance being reinstalled. Either adminPass or keypairId must be specified
22 KeypairId: "k-***",
23// Whether to enable host security, it is enabled by default
24 IsOpenHostEye: &IsOpenHostEye,
25// Whether to preserve data during reinstallation, and it is retained by default
26 IsPreserveData: &IsPreserveData,
27 }
28// i-*** is the specified instance ID
29 err := bccClient.RebuildInstanceV2("i-***", args)
30 fmt.Println(err)
31}
Reinstall instance (in batch)
You can reinstall an instance with the following code:
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8// Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12// Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 InstanceIds := []string{"i-***", "i-***"}
15 IsOpenHostEye := true
16 IsPreserveData := true
17 args := &api.RebuildBatchInstanceArgsV2{
18// The list of specified instance IDs, maximum 100
19 InstanceIds: InstanceIds,
20// Specified image ID
21 ImageId: "m-***",
22// Machine password (8-16 characters, it must contain English letters, numbers, and symbols (limited to !@#$%^*()). The password must be encrypted for transmission
23 AdminPass: "***",
24// Key pair ID to be bound to the instance being reinstalled. Either adminPass or keypairId must be specified
25 KeypairId: "k-***",
26// Whether to enable host security, it is enabled by default
27 IsOpenHostEye: &IsOpenHostEye,
28// Whether to retain data during reinstallation, it is retained by default
29 IsPreserveData: &IsPreserveData,
30 }
31 err := bccClient.BatchRebuildInstancesV2(args)
32 fmt.Println(err)
33}
Prompt:
- After reinstallation, any snapshots based on the original system disk will be automatically deleted, but custom images based on the original system disk will be retained.
Release an instance
You can release an instance with the following code
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5)
6func main() {
7 // Set your AK, SK and the endpoint to be accessed
8 ak := "ak"
9 sk := "sk"
10 endpoint := "bcc.bj.baidubce.com"
11 // Create a BCC client
12 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
13 err := bccClient.DeleteInstance("i-cNpT****") // ID of virtual machine to be deleted
14 fmt.Println(err)
15}
Release an instance (POST)
You can release a single postpaid cloud server instance with the following code:
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 args := &api.DeleteInstanceWithRelateResourceArgs{
15 // Whether to release both EIPs and data disks currently attached on instance
16 RelatedReleaseFlag: true,
17 // Whether to release cloud disk server snapshots
18 DeleteCdsSnapshotFlag: true,
19 // Whether to delete the associated ENI upon instance release
20 DeleteRelatedEnisFlag: true,
21 // Whether to move the instance to the recycle bin upon instance release
22 BccRecycleFlag: true,
23 }
24 // i-*** represents ID of instance to be released
25 err := bccClient.DeleteInstanceWithRelateResource("i-***", args)
26 fmt.Println(err)
27}
Release instances in batch (POST)
You can release instances with the following code in batch:
1 package main
2 import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6 )
7 func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14
15 deleteInstanceWithRelateResourceArgs := &api.BatchDeleteInstanceWithRelateResourceArgs{
16 // Specify whether to release the associated EIP and data disks attached on the instance at the time of release
17 // (The deleteCdsSnapshotFlag field will only be valid if this field is true. If this field is false, the value of the deleteCdsSnapshotFlag field is invalid)
18 RelatedReleaseFlag: true,
19 // Set whether to release cloud disk server snapshots
20 DeleteCdsSnapshotFlag: true,
21 // Set whether to move the instance to the recycle bin
22 BccRecycleFlag: true,
23 // Set whether to release the elastic network interfaces
24 DeleteRelatedEnisFlag: true,
25 // Instance IDs for batch release, maximum 100
26 InstanceIds: []string{"i-***"},
27 }
28 if err := bccClient.BatchDeleteInstanceWithRelateResource(deleteInstanceWithRelateResourceArgs); err != nil {
29 fmt.Println("release instance failed: ", err)
30 } else {
31 fmt.Println("release instance success.")
32 }
33 }
Release prepaid instance (POST)
Release a prepaid cloud server instance. Once released, the physical resources allocated to the instance are reclaimed, and all associated data is permanently deleted and unrecoverable.
By default, only the cloud server instance and its system disk are released during the release process. Users can opt to release the attached EIP and data disks as well. However, associated EIP and data disks must either be fully released or fully retained; partial release is not supported.
When choosing to release the EIP and data disks together, cloud disk server snapshots can also be included for release. If data disks are retained, cloud disk server snapshots cannot be included in the release process.
1 package main
2 import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6 )
7 func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14
15 deletePrepaidInstanceWithRelateResourceArgs := &api.DeletePrepaidInstanceWithRelateResourceArgs{
16 // Instance IDs for batch release
17 InstanceId: "i-***",
18 // Whether to release the EIPs and data disks currently attached on the instance at the same time (the DeleteCdsSnapshotFlag field will only be valid if this field is true. If this field is false, the value of the DeleteCdsSnapshotFlag field is invalid)
19 RelatedReleaseFlag: true,
20 // Set whether to release cloud disk server snapshots
21 DeleteCdsSnapshotFlag: true,
22 // Set whether to release the elastic network interfaces
23 DeleteRelatedEnisFlag: true,
24 }
25 if err := bccClient.DeletePrepaidInstanceWithRelateResource(deletePrepaidInstanceWithRelateResourceArgs); err != nil {
26 fmt.Println("release instance failed: ", err)
27 } else {
28 fmt.Println("release instance success.")
29 }
30 }
Release recycle bin instances
Instances in the recycle bin are automatically released after 7 days to clean up recycle bin resources. You can manually release them with the following code:
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14
15 // ID of instance to be operated
16 instanceId := "i-***"
17 // Request to release a specific instance from the recycle bin
18 err := bccClient.DeleteRecycledInstance(instanceId)
19 fmt.Println(err)
20}
Prompt:
- Release a single cloud server instance. Upon release, the physical resources used by the instance are reclaimed, and all associated data will be permanently deleted and cannot be restored.
- Only postpaid instances or expired prepaid instances are eligible for release.
- Once an instance is released, any associated CDS disks will be automatically detached, and snapshots based on these CDS disks will be retained.
- After the instance is released, snapshots of the original system disk will be deleted automatically, but custom images created from the original system disk will remain available.
Scheduled release (limited to postpaid instances)
Postpaid instances can be scheduled for release. When the specified time is reached, the BCC instance is automatically released. You can view the automatic release time under ReleaseTime in the instance details. To cancel a scheduled release, set the time to an empty string. Use this function cautiously to avoid mistakenly setting a schedule.
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5)
6func main() {
7 // Set your AK, SK and the endpoint to be accessed
8 ak := "ak"
9 sk := "sk"
10 endpoint := "http://bcc.bj.baidubce.com"
11 // Create a BCC client
12 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
13 err := bccClient.AutoReleaseInstance(
14 // Instance ID
15 "i-***",
16 // Release time, format: yyyy-MM-dd'T'HH:mm:ss'Z'
17 "2024-05-01T07:58:09Z")
18 fmt.Println(err)
19}
Prompt:
- Only postpaid instances are allowed for automatic release
- Both the system disk snapshot of this instance and the instance snapshot will be released
- All attached cloud disk servers (CDS) for this instance will be automatically detached but will not be released
- Released instances cannot be recovered.
- Associated network interface card resources will be automatically unmounted and released
Release protection
You can set release protection for a BCC instance with the following code. The current setting can be queried in the instance details under DeletionProtection, with the default of 0 (no protection) and 1 (release protection enabled) (the creation and query entry points are limited to v2 version use):
1args := &api.DeletionProtectionArgs {
2 // Release protection status: 0: disabled, 1: enabled
3 DeletionProtection : 0,
4}
5 // Set instanceId to be operated
6instanceId := "your-choose-instance-id"
7if err := bccClient.ModifyDeletionProtection(instanceId, args); err != nil {
8 fmt.Println("modifyDeletionProtection failed: ", err)
9} else {
10 fmt.Println("modifyDeletionProtection success.")
11}
Prompt:
- Both postpaid and prepaid instances can enable release protection
- Instances with release protection enabled cannot be released via the console or API. They must be manually released after the protection is disabled. However, scheduled releases, releases due to debt, or releases triggered by expiration are not affected by the release protection setting.
- Instance deletion protection is not enabled by default
Resize an instance
You can modify the CPU, MemoryCapacityInGB, EphemeralDisks and EnableJumboFrame configurations for a specified BCC instance with the following code:
1resizeInstanceArgs := &ResizeInstanceArgs{
2 // BCC core count
3 CpuCount: CpuCount
4 // Memory size (GB) of BCC instance
5 MemoryCapacityInGB: MemoryCapacityInGB
6 // Size of temporary/data disk
7 EphemeralDisks []EphemeralDisk "ephemeralDisks"
8 // Whether to enable Jumbo frames. Enable: true; disable: false.
9 // The default is empty. When empty:
10 // When resizing to a specification that does not support Jumbo frames, Jumbo frames will not be enabled;
11 // When resizing from a specification that does not support Jumbo frames to one that does, Jumbo frames will not be enabled;
12 // When resizing between specifications that both support Jumbo frames, if Jumbo frames are enabled before resizing, they will remain enabled after resizing; if they are not enabled before resizing, they will not be enabled after resizing.
13 EnableJumboFrame *bool enableJumboFrame,
14}
15 // Set instanceId to be operated
16instanceId := "your-choose-instance-id"
17if err := bccClient.ResizeInstance(instanceId, resizeInstanceArgs); err != nil {
18 fmt.Println("resize instance failed: ", err)
19} else {
20 fmt.Println("resize instance success.")
21}
Resize an instance (via instance package specifications)
You can select Spec and EnableJumboFrame to resize a specified BCC instance with the following code:
1resizeInstanceArgs := &ResizeInstanceArgs{
2 // Instance package specifications
3 Spec string "spec"
4 // Whether to enable Jumbo frames. Enable: true; disable: false.
5 // The default is empty. When empty:
6 // When resizing to a specification that does not support Jumbo frames, Jumbo frames will not be enabled;
7 // When resizing from a specification that does not support Jumbo frames to one that does, Jumbo frames will not be enabled;
8 // When resizing between specifications that both support Jumbo frames, if Jumbo frames are enabled before resizing, they will remain enabled after resizing; if they are not enabled before resizing, they will not be enabled after resizing.
9 EnableJumboFrame *bool enableJumboFrame
10}
11 // Set instanceId to be operated
12instanceId := "your-choose-instance-id"
13if err := bccClient.ResizeInstanceBySpec(instanceId, resizeInstanceArgs); err != nil {
14 fmt.Println("resize instance failed: ", err)
15} else {
16 fmt.Println("resize instance success.")
17}
Bind a security group
You can bind a security group with the following code:
1// Set instanceId to be operated
2instanceId := "your-choose-instance-id"
3 // Set security group to be bound to BCC instance
4SecurityGroupId := "SecurityGroupId"
5if err := bccClient.BindSecurityGroup(instanceId, SecurityGroupId); err != nil {
6 fmt.Println("Bind Security Group failed: ", err)
7} else {
8 fmt.Println("Bind Security Group success.")
9}
Unbind security group
You can unbind a security group with the following code:
1// Set instanceId to be operated
2instanceId := "your-choose-instance-id"
3 // Set security group to be unbound from BCC instance
4SecurityGroupId := "SecurityGroupId"
5if err := bccClient.UnBindSecurityGroup(instanceId, SecurityGroupId); err != nil {
6 fmt.Println("UnBind Security Group failed: ", err)
7} else {
8 fmt.Println("UnBind Security Group success.")
9}
Prompt:
- Each instance must be associated with at least one security group, with the default being the system's default security group.
- If an instance is part of only one security group, attempting to remove it from this group will cause a 403 error.
Instance scaling
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 // Configuration parameters for the instance to be modified
15 resizeArgs := &api.ResizeInstanceArgs{
16 CpuCount: 4, // Count of CPU cores
17 MemoryCapacityInGB: 16, // Memory size in GB
18 LiveResize: true, // Whether online resizing is supported. Default: false.
19 }
20 err := bccClient.ResizeInstance("i-SrzD****", resizeArgs)
21 fmt.Println(err)
22}
Prompt:
- When the instance is prepaid, downscaling operations are not allowed
- When the instance is postpaid, elastic scaling is allowed
- Scaling operations can only be performed when the instance is in the Running or Stopped status
- After scaling an instance, it will be rebooted once. You can select hot upgrades to perform scaling without interrupting services. For limitations on hot upgrades, please refer to the documentation Hot Upgrade Limitations
- As this is an asynchronous API, you can check the scaling status by the Query Instance Details API is completed
- For dedicated instances, you can specify CPU, memory and temporary disk size. For the temporary disk size of dedicated instances, Only expansion is supported, while contraction is not supported. For details, please refer to the API documentation Instance Scaling
Query the VNC address of the instance
You can query the VNC address of the instance with the following code
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5)
6func main() {
7 // Set your AK, SK and the endpoint to be accessed
8 ak := "ak"
9 sk := "sk"
10 endpoint := "bcc.bj.baidubce.com"
11 // Create a BCC client
12 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
13 // i-*** represents virtual machine instance ID
14 res, err := bccClient.GetInstanceVNC("i-***")
15 fmt.Println(err)
16 fmt.Println(res)
17}
Prompt:
- The VNC address becomes invalid after one use
- The URL address is valid for 10 minutes
Renew an instance
Renewing a BCC virtual machine extends its expiration period. You can renew an instance and its associated services with the following code
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 // Virtual machine instance ID
15 instanceId := "i-***"
16 args := &api.PurchaseReservedArgs{
17 // Set the instance's associated renewal flag, defaulting to an empty string
18 RelatedRenewFlag: "CDS",
19 // Order details
20 Billing: api.Billing{
21 // Renewal method; this API is for renewing prepaid instances.
22 PaymentTiming: api.PaymentTimingPrePaid,
23 // Renewal period and unit
24 Reservation: &api.Reservation{
25 // Renewal period
26 ReservationLength: 1,
27 // Renewal unit is months
28 ReservationTimeUnit: "month",
29 },
30 },
31 // Idempotency Token, an ASCII string with a length not exceeding 64 bits
32 ClientToken: "random-uuid",
33 }
34 res, err := bccClient.InstancePurchaseReserved(instanceId, args)
35 fmt.Println(err)
36 fmt.Println(res)
37}
Note:
Optional associated renewal products (relatedRenewFlag):
- CDS Renew only the prepaid CDS associated with the BCC instance
- EIP Renew only the prepaid EIP associated with the BCC instance
- MKT Renew only the prepaid MKT associated with the BCC instance
- CDS_EIP Renew only the prepaid CDS and EIP associated with the BCC instance
- CDS_MKT Renew only the prepaid CDS and MKT associated with the BCC instance
- EIP_MKT Renew only the prepaid EIP and MKT associated with the BCC instance
- CDS_EIP_MKT Renew only the prepaid CDS, EIP and MKT associated with the BCC instance
Prompt:
- Renewal actions cannot be performed on a BCC virtual machine instance while it's being scaled.
- If the instance was suspended due to unpaid debt, it will automatically reboot after the renewal process is successfully completed.
- This API operates asynchronously.
- Dedicated instances do not support renewal functionality.
Change the instance subnet
You can change the instance subnet with the following code
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 args := &api.InstanceChangeSubnetArgs{
15 // Virtual machine instance ID
16 InstanceId: "i-***",
17 // Subnet ID after change
18 SubnetId: "sbn-***",
19 // Specify intranet IP; if not specified, it will be randomly generated
20 InternalIp: "10.59.***.***",
21 // Whether to reboot after change
22 Reboot: true,
23 // Regular security group, which takes effect only when changing VPC and cannot be specified simultaneously with EnterpriseSecurityGroupIds
24 SecurityGroupIds: []string{"g-i24fkh******"},
25 // Enterprise security group, which takes effect only when changing VPC and cannot be specified simultaneously with SecurityGroupIds
26 EnterpriseSecurityGroupIds: []string{"esg-i24fkh******"},
27 }
28 err := bccClient.InstanceChangeSubnet(args)
29 fmt.Println(err)
30}
Prompt:
- By default, the instance will reboot automatically when subnet changes are made, but this operation can be configured based on user preference.
- Subnet changes are currently only supported within the same availability zone (AZ). Changes across AZs or between VPCs are not allowed. To switch from a regular subnet to a NAT-dedicated subnet, you must unbind the EIP manually first.
Change the instance VPC
You can change the instance VPC with the following code
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 args := &api.InstanceChangeVpcArgs{
15 InstanceId: "i-AgPa****", // Instance ID
16 SubnetId: "sbn-wwqfr3rd****", // Subnet ID
17 InternalIp: "192.168.*.*", // Intranet IP
18 SecurityGroupIds: []string{"g-cfbk8xa0****"}, // Security group ID
19 }
20 err := bccClient.InstanceChangeVpc(args)
21 if err != nil {
22 fmt.Println(err)
23 }
24}
Prompt:
- By default, the instance will automatically reboot after VPC changes, but users can choose whether to perform this operation.
- After changing the VPC, only the primary IP address of the main network interface card will be preserved (automatically assigned in the new subnet). Secondary IPs, elastic network interfaces, and security group information associated with the instance will not be transferred.
- Security groups and enterprise security groups cannot be specified at the same time.
Add specified IPs to a designated instance in batch
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 privateIps := []string{"192.168.***.***", "192.168.***.***"}
15 batchAddIpArgs := &api.BatchAddIpArgs{
16 // Instance ID
17 InstanceId: "i-***",
18 // Secondary IPs, up to 100 IPs, which cannot be used simultaneously with SecondaryPrivateIpAddressCount
19 PrivateIps: privateIps,
20 // Whether it is multi-IPv6; it must be true when adding IPv6 secondary addresses
21 AllocateMultiIpv6Addr: false,
22 // Count of automatically assigned IPs, which cannot be used simultaneously with PrivateIps
23 //SecondaryPrivateIpAddressCount: 2,
24 // Idempotency token, an ASCII string of up to 64 characters generated with UUID, optional
25 ClientToken: "random-uuid",
26 }
27 res, err := bccClient.BatchAddIP(batchAddIpArgs)
28 fmt.Println(err)
29 fmt.Println(res)
30}
Delete specified instance IPs in batch
1privateIps := []string{"192.168.1.25"}
2instanceId := "your-choose-instance-id"
3 // Idempotency token, an ASCII string of up to 64 characters generated with UUID, optional
4clientToken := "clientToken"
5batchDelIpArgs := &api.BatchDelIpArgs{
6 InstanceId: instanceId,
7 // Secondary IPs, maximum 100
8 PrivateIps: privateIps,
9 ClientToken: clientToken,
10}
11if err := client.BatchDelIP(batchDelIpArgs); err != nil {
12 fmt.Println("delete ips failed: ", err)
13} else {
14 fmt.Println("delete ips success.")
15}
Enable automatic renewal (including associated services)
Automatic renewal is limited to prepaid products
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "http://bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 bccAutoRenewArgs := &api.BccCreateAutoRenewArgs{
15 // Instance ID
16 InstanceId: "i-***",
17 // Renewal period unit, options: year, month
18 RenewTimeUnit: "year",
19 // Renewal period
20 RenewTime: 1,
21 // Whether to enable automatic renewal for CDS. Defaul: true
22 RenewCds: false,
23 // Whether to enable auto-renewal for EIP. Default: true
24 RenewEip: false,
25 }
26 err := bccClient.BatchCreateAutoRenewRules(bccAutoRenewArgs)
27 fmt.Println(err)
28}
Disable auto-renewal (including associated services)
Automatic renewal is limited to prepaid products
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "http://bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 bccDeleteAutoRenewArgs := &api.BccDeleteAutoRenewArgs{
15 // Instance ID
16 InstanceId: "i-***",
17 // Whether to enable auto-renewal for CDS. Default: true.
18 RenewCds: false,
19 // Whether to enable auto-renewal for EIP. Default: true.
20 RenewEip: false,
21 }
22 err := bccClient.BatchDeleteAutoRenewRules(bccDeleteAutoRenewArgs)
23 fmt.Println(err)
24}
Billing for postpaid resources resumed from recycle bin
Only applicable to postpaid products; the renewal API is used for prepaid resources
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "http://bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 args := &api.RecoveryInstanceArgs{
15 InstanceIds: []api.RecoveryInstanceModel{
16 {
17 InstanceId: "i-***",
18 },
19 {
20 InstanceId: "i-***",
21 },
22 },
23 }
24 if err := bccClient.RecoveryInstance(args); err != nil {
25 fmt.Println("recovery instance failed: ", err)
26 } else {
27 fmt.Println("recovery instance success")
28 }
29}
Shift charge - convert to prepay
You can shift bill type for instances to prepay with the following code:
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 args := &api.ChangeToPrepaidRequest{
15 Duration: 1, // Duration for conversion to prepay in months
16 }
17 result, err := bccClient.ChangeToPrepaid("i-cVh8****", args) // Virtual machine ID, parameters for conversion to prepay
18 fmt.Println(err)
19 fmt.Println(result)
20}
Bind a tag to an instance
You can bind a tag to an instance with the following code:
1 package main
2 import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/model"
5 "github.com/baidubce/bce-sdk-go/services/bcc"
6 "github.com/baidubce/bce-sdk-go/services/bcc/api"
7 )
8 func main() {
9 // Set your AK, SK and the endpoint to be accessed
10 ak := "ak"
11 sk := "sk"
12 endpoint := "bcc.bj.baidubce.com"
13 // Create a BCC client
14 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
15 // Set the tag to be bound
16 args := &api.BindTagsRequest{
17 ChangeTags: []model.TagModel{
18 {
19 TagKey: "Key***",
20 TagValue: "Value***",
21 },
22 },
23 }
24 // Set instanceId to be operated
25 instanceId := "i-***"
26 if err := bccClient.BindInstanceToTags(instanceId, args); err != nil {
27 fmt.Println("BindInstanceToTags failed: ", err)
28 } else {
29 fmt.Println("BindInstanceToTags success.")
30 }
31 }
Unbind a tag from an instance
You can unbind a tag from an instance with the following code:
1 package main
2 import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/model"
5 "github.com/baidubce/bce-sdk-go/services/bcc"
6 "github.com/baidubce/bce-sdk-go/services/bcc/api"
7 )
8 func main() {
9 // Set your AK, SK and the endpoint to be accessed
10 ak := "ak"
11 sk := "sk"
12 endpoint := "bcc.bj.baidubce.com"
13 // Create a BCC client
14 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
15 // Set the tag to be unbound
16 args := &api.UnBindTagsRequest{
17 ChangeTags: []model.TagModel{
18 {
19 TagKey: "Key***",
20 TagValue: "Value***",
21 },
22 },
23 }
24 // Set instanceId to be operated
25 instanceId := "i-***"
26 if err := bccClient.UnBindInstanceToTags(instanceId, args); err != nil {
27 fmt.Println("UnBindInstanceToTags failed: ", err)
28 } else {
29 fmt.Println("UnBindInstanceToTags success.")
30 }
31 }
Query instance specifications for resizing
You can query instance specifications for resizing with the following code
1 package main
2 import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6 )
7 func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14
15 listAvailableResizeSpecsArgs := &api.ListAvailableResizeSpecsArgs{
16 // Instance specifications
17 Spec: "bcc.ic5.c1m1",
18 // Availability zone
19 Zone: "cn-bj-d",
20 }
21 res, _ := bccClient.ListAvailableResizeSpecs(listAvailableResizeSpecsArgs)
22 fmt.Println(res)
23 }
Convert to prepay in batch
You can batch convert the billing type of instances to prepay using the following code. To change the billing type of associated CDS resources, you must specify all relevant CDS IDs in the CdsList to be converted to prepay. If converting all CDS resources, specify "all".
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "http://bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 // InstanceIds, maximum 100
15 batchChangeInstanceToPrepayArgs := &api.BatchChangeInstanceToPrepayArgs{
16 Config: []api.PrepayConfig{
17 {
18 InstanceId: "i-***",
19 Duration: 1,
20 CdsList: []string{
21 "v-***",
22 "v-***",
23 },
24 },
25 {
26 InstanceId: "i-***",
27 Duration: 1,
28 CdsList: []string{
29 "all",
30 },
31 },
32 },
33 }
34 result, err := bccClient.BatchChangeInstanceToPrepay(batchChangeInstanceToPrepayArgs)
35 if err != nil {
36 fmt.Println("batch change instance to prepay failed:", err)
37 } else {
38 fmt.Println("batch change instance to prepay success: ", result)
39 }
40}
Convert to postpay in batch
You can batch convert the billing type of instances to postpay using the following code. To change the billing type of associated CDS resources, you must specify all relevant CDS IDs in the CdsList to be converted to postpay. If converting all CDS resources, specify "all".
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "http://bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 // InstanceIds, maximum 100
15 batchChangeInstanceToPostArgs := &api.BatchChangeInstanceToPostpayArgs{
16 Config: []api.PostpayConfig{
17 {
18 InstanceId: "i-***",
19 CdsList: []string{
20 "v-***",
21 "v-***",
22 },
23 },
24 {
25 InstanceId: "i-***",
26 CdsList: []string{
27 "all",
28 },
29 },
30 },
31 }
32 result, err := bccClient.BatchChangeInstanceToPostpay(batchChangeInstanceToPostArgs)
33 if err != nil {
34 fmt.Println("batch change instance to postpay failed:", err)
35 } else {
36 fmt.Println("batch change instance to postpay success: ", result)
37 }
38}
Retrieve a list of instance roles
You can retrieve a list of instance roles with the following code
1 package main
2 import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6 )
7 func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 result, err := bccClient.ListInstanceRoles()
15 if err != nil {
16 fmt.Println("list instance roles failed:", err)
17 } else {
18 fmt.Println("list instance roles success: ", result)
19 }
20 }
Bind a role
You can bind a role to a BCC instance with the following code
1 package main
2 import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6 )
7 func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14
15 // Set the tag to be bound
16 bindInstanceRoleArgs := &api.BindInstanceRoleArgs{
17 RoleName: "BCC_***",
18 Instances: []api.Instances{
19 {
20 InstanceId: "i-***",
21 },
22 },
23 }
24 if err := bccClient.BindInstanceRole(bindInstanceRoleArgs); err != nil {
25 fmt.Println("bind instance role failed: ", err)
26 } else {
27 fmt.Println("bind instance role success.")
28 }
Unbind a role
You can unbind a role from a BCC instance with the following code
1 package main
2 import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6 )
7 func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 // Set the tag to be bound
15 unbindInstanceRoleArgs := &api.UnBindInstanceRoleArgs{
16 RoleName: "BCC_***",
17 Instances: []api.Instances{
18 {
19 InstanceId: "i-***",
20 },
21 },
22 }
23 if err := bccClient.UnBindInstanceRole(unbindInstanceRoleArgs); err != nil {
24 fmt.Println("unbind instance role failed: ", err)
25 } else {
26 fmt.Println("unbind instance role success.")
27 }
28 }
Add IPv6
You can add IPv6 to a BCC instance with the following code
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "http://bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 addIpv6Args := &api.AddIpv6Args{
15 // Instance ID
16 InstanceId: "i-***",
17 // IPv6 address
18 Ipv6Address: "240c:4081:8005:ca0b:***:***",
19 // Whether to reboot the instance
20 Reboot: true,
21 }
22 result, err := bccClient.AddIpv6(addIpv6Args)
23 fmt.Println(result)
24 fmt.Println(err)
25}
Release IPv6
You can release IPv6 from a BCC instance with the following code
1package main
2import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6)
7func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "http://bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 addIpv6Args := &api.DeleteIpv6Args{
15 // Instance ID
16 InstanceId: "i-***",
17 // Whether to reboot the instance
18 Reboot: true,
19 }
20 err := bccClient.DeleteIpv6(addIpv6Args)
21 fmt.Println(err)
22}
Query the instance list by the instance ID in batch
You can query the instance list by the instance ID in batch with the following code
1 package main
2 import (
3 "fmt"
4 "github.com/baidubce/bce-sdk-go/services/bcc"
5 "github.com/baidubce/bce-sdk-go/services/bcc/api"
6 )
7 func main() {
8 // Set your AK, SK and the endpoint to be accessed
9 ak := "ak"
10 sk := "sk"
11 endpoint := "bcc.bj.baidubce.com"
12 // Create a BCC client
13 bccClient, _ := bcc.NewClient(ak, sk, endpoint)
14 args := &api.ListInstanceByInstanceIdArgs{
15 // List of instance IDs to be queried, maximum 100 IDs
16 InstanceIds: []string{
17 "i-***",
18 "i-***",
19 },
20 }
21 result, err := bccClient.ListInstanceByInstanceIds(args)
22 if err != nil {
23 fmt.Println("list instance failed:", err)
24 } else {
25 fmt.Println("list instance success: ", result)
26 }
27 }
Query the list of elastic network interfaces bound to the instance
You can query the list of elastic network interfaces bound to the instance with the following code
1// Set instanceId to be operated (up to 100)
2instanceId := "instanceId"
3if res, err := BCC_CLIENT.ListInstanceEnis(instanceId); err != nil {
4 fmt.Println("Get specific instance eni failed: ", err)
5} else {
6 fmt.Println("Get specific instance eni success, result: ", res)
7}
Query the custom data of the instance
You can query the custom data of the instance with the following code
1// Set instanceId to be operated
2 args := &api.DescribeInstanceUserDataArg{
3 InstanceId: "i-b34ycow2",
4 }
5 result, err := BCC_CLIENT.getInstanceUserData(args)
6 fmt.Println(result)
7 fmt.Println(err)
