sigs.k8s.io/controller-runtime@v0.18.2/pkg/controller/controllerutil/example_test.go (about) 1 /* 2 Copyright 2018 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package controllerutil_test 18 19 import ( 20 "context" 21 22 appsv1 "k8s.io/api/apps/v1" 23 corev1 "k8s.io/api/core/v1" 24 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 25 26 "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" 27 logf "sigs.k8s.io/controller-runtime/pkg/log" 28 ) 29 30 var ( 31 log = logf.Log.WithName("controllerutil-examples") 32 ) 33 34 // This example creates or updates an existing deployment. 35 func ExampleCreateOrUpdate() { 36 // c is client.Client 37 38 // Create or Update the deployment default/foo 39 deploy := &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "default"}} 40 41 op, err := controllerutil.CreateOrUpdate(context.TODO(), c, deploy, func() error { 42 // Deployment selector is immutable so we set this value only if 43 // a new object is going to be created 44 if deploy.ObjectMeta.CreationTimestamp.IsZero() { 45 deploy.Spec.Selector = &metav1.LabelSelector{ 46 MatchLabels: map[string]string{"foo": "bar"}, 47 } 48 } 49 50 // update the Deployment pod template 51 deploy.Spec.Template = corev1.PodTemplateSpec{ 52 ObjectMeta: metav1.ObjectMeta{ 53 Labels: map[string]string{ 54 "foo": "bar", 55 }, 56 }, 57 Spec: corev1.PodSpec{ 58 Containers: []corev1.Container{ 59 { 60 Name: "busybox", 61 Image: "busybox", 62 }, 63 }, 64 }, 65 } 66 67 return nil 68 }) 69 70 if err != nil { 71 log.Error(err, "Deployment reconcile failed") 72 } else { 73 log.Info("Deployment successfully reconciled", "operation", op) 74 } 75 }