在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
1.简单实现 package main import ( "encoding/json" "fmt" consulapi "github.com/hashicorp/consul/api" "log" //_ "github.com/spf13/viper/remote" ) var ( cloudEntryURL = "cloud_entry/openstack/" resourceURL = "cmp/resource/yacmp:cloudentry:type:openstack/iaas.machine/" ) type cloudEntryValue struct { authInfo map[string]string resourceInfo map[string]map[string]string } func translate(m map[string]interface{}) map[string]string { ret := make(map[string]string, len(m)) for k, v := range m { ret[k] = fmt.Sprint(v) } return ret } func listResources(address string) (cloudEntry, cloudResource consulapi.KVPairs) { config := consulapi.DefaultConfig() config.Address = address client, err := consulapi.NewClient(config) if err != nil { log.Fatal("consul client error : ", err) } cloudEntry, _, _ = client.KV().List(cloudEntryURL, nil) cloudResource, _, _ = client.KV().List(resourceURL, nil) return } func getResourceCollection(address string) map[string]*cloudEntryValue { resourceCollection := make(map[string]*cloudEntryValue) cloudEntry, cloudResource := listResources(address) for _, value := range cloudEntry { var cloudEntryValue = new(cloudEntryValue) var entryInfos = make(map[string]string) if value.Value == nil { continue } err := json.Unmarshal(value.Value, &entryInfos) if err != nil { log.Fatal("unmarshal json from consul error : ", err) } if _, ok := resourceCollection[entryInfos["cloud_entry_id"]]; ok { continue } fmt.Println(resourceCollection,"resourceCollection") cloudEntryValue.authInfo = entryInfos cloudEntryValue.resourceInfo = make(map[string]map[string]string) resourceCollection[entryInfos["cloud_entry_id"]] = cloudEntryValue } for _, value := range cloudResource { var resources map[string]interface{} if value.Value == nil { continue } err := json.Unmarshal(value.Value, &resources) if err != nil { log.Fatal("unmarshal json from consul error : ", err) } if _, ok := resourceCollection[resources["cloud_entry_id"].(string)]; ok { if cmpInfos, ok := resources["resources"]; ok { cmpInfo := cmpInfos.([]interface{})[0].(map[string]interface{}) if instanceInfo, ok := cmpInfo["cmp_info"]; ok { key := instanceInfo.(map[string]interface{})["external_name"].(string) value := translate(instanceInfo.(map[string]interface{})) cloudEntry := resourceCollection[resources["cloud_entry_id"].(string)] cloudEntry.resourceInfo[key] = value } } } } return resourceCollection } func main(){ consulAddress := "http://47.98.136.126:8500" res:=getResourceCollection(consulAddress) for k,v:=range res{ fmt.Println(k,v) fmt.Println("id",v.authInfo["cloud_entry_id"]) for k,v:=range v.resourceInfo{ fmt.Println("k",k) fmt.Println("v",v["zone"]) } } }
|
请发表评论