TheCoder
TheCoder

Reputation: 89

k8s CRD embed k8s native type

using Operator-SDK to develop K8s operator. Requirement is to listen to CR and perform actions like create secrets and configmaps then update the workload(Deployment/DaemonSet/StatefulSet) by mounting the secret and configmaps. Until CR is reconciled workload should be in pending state.

To achieve this, In the CRD spec, embed k8s Deployment, StatefulSet or DaemonSet objects. Once pre-processing is done and adjusted the workload, the apply the workload to cluster.

type Foo struct{
  metav1.TypeMeta   `json:",inline"`
  metav1.ObjectMeta `json:"metadata,omitempty"`

   Spec   FooSpec   `json:"spec,omitempty"`
   Status FooStatus `json:"status,omitempty"`
}
type FooSpec struc{
   Template <Deployment|DaemonSet|StatefulSet> `json:"template,omitempty"`
}

Above is the template sample. In this Template can be of deployment or statefulSet or DaemonSet.

How to define such a CRD spec using operator-sdk in golang?

How to cast the Template, in reconciliation loop, to the actual object(Deployment/DaemonSet/StatefulSet)?

Upvotes: 0

Views: 82

Answers (1)

tuna
tuna

Reputation: 308

One option is to split template types and add a field that decides the kind of the workload. Validation markers can be used to specify the workload's kind.

type Foo struct{
   metav1.TypeMeta   `json:",inline"`
   metav1.ObjectMeta `json:"metadata,omitempty"`

   Spec   FooSpec   `json:"spec,omitempty"`
   Status FooStatus `json:"status,omitempty"`
}
type FooSpec struct{
   // +kubebuilder:validation:Required
   // +kubebuilder:validation:Enum=Deployment,DaemonSet,StatefulSet
   Kind                string            `json:"kind,omitempty"`
   DeploymentTemplate  DeploymentSpec    `json:"deploymentTemplate,omitempty"`
   DaemonSetTemplate   DaemonSetSpec     `json:"daemonSetTemplate,omitempty"`
   StatefulSetTemplate StatefulSetSpec   `json:"statefulSetTemplate,omitempty"`
}

Then you can use reflect package to compare your desired workload and the actual workload in your reconciler.

// check your deployment for example
if !reflect.DeepEqual(instance.Spec.DeploymentSpec, actualDeployment.Spec) {
    // update your deployment
}

Upvotes: 0

Related Questions