Skip to content

Commit 5b1f824

Browse files
committed
Add CreateOrUpdate utility method
1 parent 3aaf8cd commit 5b1f824

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

pkg/controller/controllerutil/controllerutil.go

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,15 @@ limitations under the License.
1717
package controllerutil
1818

1919
import (
20+
"context"
2021
"fmt"
22+
"reflect"
2123

24+
"k8s.io/apimachinery/pkg/api/errors"
2225
"k8s.io/apimachinery/pkg/apis/meta/v1"
2326
"k8s.io/apimachinery/pkg/runtime"
2427
"k8s.io/apimachinery/pkg/runtime/schema"
28+
"sigs.k8s.io/controller-runtime/pkg/client"
2529
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
2630
)
2731

@@ -46,3 +50,55 @@ func SetControllerReference(owner, object v1.Object, scheme *runtime.Scheme) err
4650
object.SetOwnerReferences(append(object.GetOwnerReferences(), ref))
4751
return nil
4852
}
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

Comments
 (0)