go如何修改configmap


func (r *RegistryCenterReconciler) updateIstioConfigMap(ctx context.Context) (ctrl.Result, error) {
	rlog.Info("start update istio configmap")
	cmList := &v1.ConfigMapList{}
	selector := &client.MatchingLabelsSelector{
		Selector: labels.SelectorFromSet(map[string]string{
			"release": "istio",
		}),
	}
	// 查询指定标签的cm
	err := r.Client.List(ctx, cmList, &client.ListOptions{
		Namespace:     "istio-system",
		LabelSelector: selector,
	})
	if err != nil {
		rlog.Error("list istio configmap error", err)
	}
	for _, cm := range cmList.Items {
		cmData := cm.Data
		if cmData == nil {
			break
		}
		meshData := cmData["mesh"]
		if meshData == "" {
			break
		}
		// 定义一个 map 来解析 YAML 数据
		var data map[string]interface{}

		// 将 YAML 字符串解析为 Go 对象
		err := yaml.Unmarshal([]byte(meshData), &data)
		if err != nil {
			return ctrl.Result{}, err
		}
		data["configSources"] = []map[string]string{
			{
				"address": "k8s://localhost/",
			},
		}

		// 将编辑后的数据转换回 YAML 字符串
		newYAML, err := yaml.Marshal(data)
		if err != nil {
			rlog.Error("convert istio configmap error", err)
		}

		// 输出新的 YAML 字符串
		fmt.Println("Modified YAML:")
		fmt.Println(string(newYAML))

		cmData["mesh"] = string(newYAML)
		// 打印解析后的数据
		fmt.Printf("Parsed YAML data: %+v\n", data)
		err = r.Update(ctx, &cm)
		if err != nil {
			rlog.Error("update istio configmap error", err)
		}
		rlog.Info("update istio configmap success")
	}

	rlog.Info("istio configmap updated successfully")
	return ctrl.Result{}, nil
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值