Skip to content

Instantly share code, notes, and snippets.

@mayankshah1607
Last active October 13, 2021 10:52
Show Gist options
  • Select an option

  • Save mayankshah1607/644dce13ea6190a3112fe5d35bfb56aa to your computer and use it in GitHub Desktop.

Select an option

Save mayankshah1607/644dce13ea6190a3112fe5d35bfb56aa to your computer and use it in GitHub Desktop.
reconcile_good
type SidecarReconciler struct {
client.Client
Scheme *runtime.Scheme
}
func (r *SidecarReconciler) Reconcile(
ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
// STEP 1: get the deployment object
deployment := &appsv1.Deployment{}
err := r.Get(ctx, req.NamespacedName, deployment)
if err != nil {
return ctrl.Result{}, err
}
// STEP 2: reconcile
if err := r.handleDeploymentReconciliation(ctx, deployment); err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
func (r *SidecarReconciler) handleDeploymentReconciliation(ctx context.Context,
deployment *appsv1.Deployment) error {
labels := deployment.GetLabels()
sidecar := &corev1.Container{
Name: sidecarName,
Image: sidecarImage,
Command: []string{"sleep"},
Args: []string{"36000"},
}
desiredDeployment := deployment.DeepCopy()
containers := deployment.Spec.Template.Spec.Containers
// check if inject label present
if labels[sidecarInjectLabel] == "true" {
// add sidecar
containers = append(containers, *sidecar)
desiredDeployment.Spec.Template.Spec.Containers = containers
// update
err := r.Update(ctx, desiredDeployment)
if err != nil {
return err
}
return nil
}
for i, container := range containers {
if container.Name == sidecarName &&
container.Image == sidecarImage {
// remove sidecar
desiredContainers := append(containers[:i], containers[i+1:]...)
desiredDeployment.Spec.Template.Spec.Containers = desiredContainers
// update
err := r.Update(ctx, desiredDeployment)
if err != nil {
return err
}
return nil
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment