華爲雲ecs,evs打標籤

背景是由於界面上不支持批量打標籤,我們機器又比較多,華爲雲ui很卡(個人猜測是因爲他每次都返回全量數據導致),體驗非常差,他們有個tms標籤管理服務,但是不支持各種排序,篩選,數據量一大,沒法搞,所以還是自己api實現吧。

過程其實還是簡單的,我們是定義project,每個project基本上都是同一個部門的服務器,打相同標籤就行了(但是我們project也比較多)

首先定義4個flag

	projectid  = flag.String("p", "", "please input projectid")
	regionName = flag.String("r", "cn-east-2", "please input regionname")
	tagKey     = flag.String("k", "", "input key")
	tagValue   = flag.String("v", "", "input value")

獲取client

func getEvsClient(projectId, regionName string) *evs.EvsClient {

	auth := basic.NewCredentialsBuilder().
		WithAk(ak).
		WithSk(sk).
		WithProjectId(projectId).
		Build()

	client := evs.NewEvsClient(
		evs.EvsClientBuilder().
			WithRegion(region.ValueOf(regionName)).
			WithCredential(auth).
			Build())
	return client
}

獲取evs id切片,當然這裏帶個過濾,我這裏是過濾沒有被打過標籤的evs

func getAllEvs(client *evs.EvsClient) []string {
	var ans []string
	request := &model.ListVolumesRequest{}
	response, err := client.ListVolumes(request)
	if err != nil {
		//return
		return ans
	}
	for i, v := range *response.Volumes {
		if !searchTag(v.Tags) {
			fmt.Println(i, v.Name, v.Id, v.Tags)
			ans = append(ans, v.Id)
		}

	}
	return ans
}

然後就是打標籤

func TagEvs(client *evs.EvsClient, key string, value string, evsids []string) {

	for i, e := range evsids {
		klog.Infof("do with %d %s", i, e)
		request := &model.BatchCreateVolumeTagsRequest{}
		//Body: model.BatchCreateVolumeTagsRequestBody{
		//Action: model.BatchCreateVolumeTagsRequestBodyAction{},
		//Tags:   []model.Tag{t},
		//request.Body.Action = model.BatchCreateVolumeTagsRequestBodyAction{}
		request.VolumeId = e
		var listTagsbody = []model.Tag{
			{
				Key:   key,
				Value: value,
			},
		}
		request.Body = &model.BatchCreateVolumeTagsRequestBody{
			Tags:   listTagsbody,
			Action: model.GetBatchCreateVolumeTagsRequestBodyActionEnum().CREATE,
		}
		klog.Infof("request:%+v\n", request)
		response, err := client.BatchCreateVolumeTags(request)
		if err != nil {
			klog.Fatalln("cannot tag volume: ", err)
		}
		klog.Infof("response:%+v", response)

	}

}

這樣標籤就打完了。當然有多個項目的你需要吧項目信息持久化一下,比如寫文件或者讀數據庫裏面,這樣可以重複利用一下。

ecs與之類似,不過ecs的tag類型跟evs還不一樣。令人費解,ecs裏面是map[string]string,ecs裏面卻是[]string。

然後rms資源管理裏面設置合規,沒有相關標籤的就提示不合規來定期檢查,我做的過程中發現華爲雲的一些小bug,evs有些鏡像標籤不生效的事。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章