效果
调用阿里云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 • 1 • 2
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 "github.com/alibabacloud-go/darabonba-openapi/client" emr20160408 "github.com/alibabacloud-go/emr-20160408/client" "github.com/alibabacloud-go/tea/tea" "github.com/tealeg/xlsx" "github.com/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{ StatusList: []*string{tea.String("NORMAL")}, //主机状态 PageNumber: tea.Int32(1), //分页数 PageSize: tea.Int32(10), //分页主机数量 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) }
上一段代码运行完成后会发现,出现了很多不存在的主机也被输出到xls表格中,根据阿里云提供的api字段修改,可以解决这个问题,指定主机状态和页数
// This file is auto-generated, don't edit it. Thanks. package main import ( "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/client" emr20160408 "github.com/alibabacloud-go/emr-20160408/client" "github.com/alibabacloud-go/tea/tea" "github.com/tealeg/xlsx" "github.com/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("LTxxxxxxxxxxxxxxxxxxt"), tea.String("VKrUZeS9oDxxxxxxxxxxxxxxxxxxM"))//填写AccessKey ID和AccessKey Secret if _err != nil { return _err, "登录失败" } listClusterHostRequest := &emr20160408.ListClusterHostRequest{ RegionId: tea.String("cn-zhangjiakou"), //阿里云区域 ClusterId: tea.String("C-FD39C77B200AEB73"), //集群id PageNumber: tea.Int32(1), PageSize: tea.Int32(10), // Array, 可选, 主机状态列表: - NORMAL:正常 - ABNORMAL:异常 - RESIZING:配置中 - INITIALIZING:初始化中 - RELEASED:已释放 StatusList: []*string{tea.String("NORMAL")}, } // 复制代码运行请自行打印 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) }
再次打开xls表格,会发现与现有集群信息一致