华为云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有些镜像标签不生效的事。

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