1 回答
TA贡献1842条经验 获得超21个赞
通过检查这个问题弄清楚: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")
}
...
}
- 1 回答
- 0 关注
- 216 浏览
添加回答
举报