@@ -17,11 +17,15 @@ limitations under the License.
17
17
package controllerutil
18
18
19
19
import (
20
+ "context"
20
21
"fmt"
22
+ "reflect"
21
23
24
+ "k8s.io/apimachinery/pkg/api/errors"
22
25
"k8s.io/apimachinery/pkg/apis/meta/v1"
23
26
"k8s.io/apimachinery/pkg/runtime"
24
27
"k8s.io/apimachinery/pkg/runtime/schema"
28
+ "sigs.k8s.io/controller-runtime/pkg/client"
25
29
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
26
30
)
27
31
@@ -46,3 +50,55 @@ func SetControllerReference(owner, object v1.Object, scheme *runtime.Scheme) err
46
50
object .SetOwnerReferences (append (object .GetOwnerReferences (), ref ))
47
51
return nil
48
52
}
53
+
54
+ // OperationType is the action result of a CreateOrUpdate call
55
+ type OperationType string
56
+
57
+ const ( // They should complete the sentence "v1.Deployment has been ..."
58
+ OperationNoop = "unchanged"
59
+ OperationCreated = "created"
60
+ OperationUpdated = "updated"
61
+ )
62
+
63
+ // CreateOrUpdate creates or updates a kuberenes resource. It takes in a key and
64
+ // a placeholder for the existing object and returns the modified object
65
+ func CreateOrUpdate (c client.Client , ctx context.Context , key client.ObjectKey , existing runtime.Object , t TransformFn ) (runtime.Object , OperationType , error ) {
66
+ err := c .Get (ctx , key , existing )
67
+ var obj runtime.Object
68
+
69
+ if errors .IsNotFound (err ) {
70
+ obj , err = t (existing )
71
+ if err != nil {
72
+ return nil , OperationNoop , err
73
+ }
74
+
75
+ err = c .Create (ctx , obj )
76
+ if err != nil {
77
+ return nil , OperationNoop , err
78
+ } else {
79
+ return obj , OperationCreated , err
80
+ }
81
+ } else if err != nil {
82
+ return nil , OperationNoop , err
83
+ } else {
84
+ obj , err = t (existing .DeepCopyObject ())
85
+ if err != nil {
86
+ return nil , OperationNoop , err
87
+ }
88
+
89
+ if ! reflect .DeepEqual (existing , obj ) {
90
+ err = c .Update (ctx , obj )
91
+ if err != nil {
92
+ return nil , OperationNoop , err
93
+ } else {
94
+ return obj , OperationUpdated , err
95
+ }
96
+ } else {
97
+ return obj , OperationNoop , nil
98
+ }
99
+ }
100
+ }
101
+
102
+ // TransformFn is a function which take in a kubernetes object and returns the
103
+ // desired state of that object
104
+ type TransformFn func (in runtime.Object ) (runtime.Object , error )
0 commit comments