Go:AliyunSDK
目录:
安装
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
使用
构建ecs的client
ecsClient, err := ecs.NewClientWithAccessKey(region, access_key_id, access_key_secret)
if err != nil {
panic(err)
}
构建ecs查询对应的request
// 方法为Create${apiName}Request
request := ecs.CreateDescribeInstancesRequest()
// 构建参数
request.PageSize = "10"
构建参数参考CreateDescribeInstancesRequest方法
func CreateDescribeInstancesRequest() (request *DescribeInstancesRequest) {
request = &DescribeInstancesRequest{
RpcRequest: &requests.RpcRequest{},
}
request.InitWithApiInfo("Ecs", "2014-05-26", "DescribeInstances", "ecs", "openAPI")
return
}
返回的DescribeInstancesRequest类型
type DescribeInstancesRequest struct {
*requests.RpcRequest
InnerIpAddresses string `position:"Query" name:"InnerIpAddresses"`
ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"`
PrivateIpAddresses string `position:"Query" name:"PrivateIpAddresses"`
HpcClusterId string `position:"Query" name:"HpcClusterId"`
PageSize requests.Integer `position:"Query" name:"PageSize"`
...
}
请求
response, err := ecsClient.DescribeInstances(request)
if err != nil {
fmt.Println("获取结果失败")
}
返回结果也是从DescribeInstances的返回值类型DescribeInstancesRequest获取
查询分页
func main() {
ecsClient, err := ecs.NewClientWithAccessKey("cn-beijing", access_key_id, access_key_secret)
if err != nil {
panic(err)
}
i := 1
host_slice := make([]Host, 0, 64)
for {
// Create${apiName}Request
// 参考service/ecs包
request := ecs.CreateDescribeInstancesRequest()
pagesize := 10
request.PageSize = "10"
request.PageNumber = requests.NewInteger(i)
response, err := ecsClient.DescribeInstances(request)
if err != nil {
fmt.Println("获取结果失败")
}
if pagesize * i > response.TotalCount {
break
}else{
instances := response.Instances.Instance
for _, instance := range instances{
fmt.Println(instance.HostName)
}
}
i ++
fmt.Println(len(host_slice))
}
}
获取对应磁盘数据
type MapStr map[string]interface{}
...
// 获取主机磁盘信息
requestDisk := ecs.CreateDescribeDisksRequest()
requestDisk.PageSize = "20"
responseDisk, err := ecsClient.DescribeDisks(requestDisk)
if err != nil {
fmt.Println("获取结果失败")
}
disks := responseDisk.Disks.Disk
storagesList := make([]mapstr.MapStr, 0)
for _, disk := range disks {
d := mapstr.MapStr{
"media": 1,
"volume": disk.Size,
"model": disk.Category,
"serial": disk.DiskId,
"rotation_rate": 1,
"form_factor": 2.5,
"power_on_hours": 1,
}
storagesList = append(storagesList, d)
}