调用阿里云EMR服务API,获取集群中的主机名和ip地址,输出到exl表中
例子:调用阿里云EMR服务的api,获取集群主机名和ip,输出到exl表
1、去阿里云api文档,查找接口文档
我这里只想获取集群的hostname和ip信息,所以我这里选择的是【查询集群主机列表】即可满足我的需求

2、把上图右侧代码复制到自己电脑中编辑
1)使用go mod init emr初始化mod仓库
2)直接get下远程仓库代码,使用go mod tidy 自动获取依赖文件
go get github.com/alibabacloud-go/emr-20160408
go get github.com/thedevsaddam/gojsonq
go mod tidy
3)修改代码
调用阿里云api,默认返回json格式值,把它转化成字符串,在函数中_main中添加_string返回字符串类型值,得到字符串返回值赋值给HostNameIp字符串变量,gojsonq包调用这个字符串变量,截取字段值,清空覆盖输出到exl表格中
// This file is auto-generated, don't edit it. Thanks.
package main
import (
"fmt"
openapi "/alibabacloud-go/darabonba-openapi/client"
emr20160408 "/alibabacloud-go/emr-20160408/client"
"/alibabacloud-go/tea/tea"
"/tealeg/xlsx"
"/thedevsaddam/gojsonq"
"os"
)
var HostNameIp string
func CreateClient(accessKeyId *string, accessKeySecret *string) (_result *emr20160408.Client, _err error) {
config := &openapi.Config{
// 您的AccessKey ID
AccessKeyId: accessKeyId,
// 您的AccessKey Secret
AccessKeySecret: accessKeySecret,
}
// 访问的域名
config.Endpoint = tea.String("emr.cn-zhangjiakou.aliyuncs.com")
_result = &emr20160408.Client{}
_result, _err = emr20160408.NewClient(config)
return _result, _err
}
func _main(args []*string) (_err error, _string string) {
client, _err := CreateClient(tea.String("LTxxxxxxD95t"), tea.String("VKrUZeSH5xxxxxxxxxxxxxxxxxvAqM"))//填写AccessKey ID和AccessKey Secret
if _err != nil {
return _err, "登录失败"
}
listClusterHostRequest := &emr20160408.ListClusterHostRequest{
RegionId: tea.String("cn-zhangjiakou"), //阿里云区域
ClusterId: tea.String("C-FD39C77B200AEB73"), //集群id
}
// 复制代码运行请自行打印 API 的返回值
List, _err := client.ListClusterHost(listClusterHostRequest)
if _err != nil {
return _err, "获取失败"
}
ListHostnameip := fmt.Sprint(*List)//把指针类型的值转化成字符串
fmt.Printf("list的类型是%T", ListHostnameip)
return _err, ListHostnameip //把得到的json格式值用string类型返回
}
func stdout() {
jq := gojsonq.New().FromString(HostNameIp).From("body.HostList.Host").Select("HostName", "PrivateIp")//定义字段,在body下的hostlist下的host中截取hostname和privateip值
deviceInfoList, ok := jq.Get().([]interface{})
if !ok {
fmt.Println("Convert deviceInfoList error")
}
xlsxFile := xlsx.NewFile()
sheet, err := xlsxFile.AddSheet("Sheet 1")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
sheet.AddRow().WriteSlice(&[]string{"主机名", "IP"}, 3)
for _, deviceInfo := range deviceInfoList {
deviceInfoMap, ok := deviceInfo.(map[string]interface{})
if !ok {
fmt.Println("Convert deviceInfoMap error")
}
row := sheet.AddRow()
row.AddCell().SetValue(deviceInfoMap["HostName"])
row.AddCell().SetValue(deviceInfoMap["PrivateIp"])
}
xlsxFile.Save("./result.xlsx")
}
func main() {
err, Hostnameip := _main(tea.StringSlice(os.Args[1:]))
if err != nil {
panic(err)
}
HostNameIp = fmt.Sprint(Hostnameip)
stdout()
//fmt.Println(HostNameIp)
}
















