亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Golang 中執行“kubectl apply”的等效方法

在 Golang 中執行“kubectl apply”的等效方法

Go
慕少森 2022-05-18 16:37:00
使用 應用復雜的 yaml 配置很簡單kubectl,例如,安裝kong-ingress-controller只需使用一行kubectl:kubectl apply -f https://raw.githubusercontent.com/Kong/kubernetes-ingress-controller/master/deploy/single/all-in-one-dbless.yaml在 Golang 中這樣做的等效方法是什么?
查看完整描述

1 回答

?
茅侃侃

TA貢獻1842條經驗 獲得超22個贊

通過檢查這個問題弄清楚:https ://github.com/kubernetes/client-go/issues/193#issuecomment-363318588


我在 using kubebuilder,簡單把 yamls 變成runtime.Objectsusing UniversalDeserializer,然后使用 Reconciler 的Create方法創建對象:


// ref: https://github.com/kubernetes/client-go/issues/193#issuecomment-363318588

func parseK8sYaml(fileR []byte) []runtime.Object {


    acceptedK8sTypes := regexp.MustCompile(`(Namespace|Role|ClusterRole|RoleBinding|ClusterRoleBinding|ServiceAccount)`)

    fileAsString := string(fileR[:])

    sepYamlfiles := strings.Split(fileAsString, "---")

    retVal := make([]runtime.Object, 0, len(sepYamlfiles))

    for _, f := range sepYamlfiles {

        if f == "\n" || f == "" {

            // ignore empty cases

            continue

        }


        decode := scheme.Codecs.UniversalDeserializer().Decode

        obj, groupVersionKind, err := decode([]byte(f), nil, nil)


        if err != nil {

            log.Println(fmt.Sprintf("Error while decoding YAML object. Err was: %s", err))

            continue

        }


        if !acceptedK8sTypes.MatchString(groupVersionKind.Kind) {

            log.Printf("The custom-roles configMap contained K8s object types which are not supported! Skipping object with type: %s", groupVersionKind.Kind)

        } else {

            retVal = append(retVal, obj)

        }


    }

    return retVal

}


func (r *MyReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {

    ctx := context.Background()

    log := r.Log.WithValues("MyReconciler", req.NamespacedName)


    // your logic here

    log.Info("reconciling")


    yaml := `

apiVersion: v1

kind: Namespace

metadata:

  name: test-ns`

    obj := parseK8sYaml([]byte(yaml))

    if err := r.Create(ctx, obj[0]); err != nil {

        log.Error(err, "failed when creating obj")

    }


    ...


}


查看完整回答
反對 回復 2022-05-18
  • 1 回答
  • 0 關注
  • 250 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號