Skip to content

Commit

Permalink
feat: update operation should create resource if it doesn't exist
Browse files Browse the repository at this point in the history
Signed-off-by: Daniel Helfand <helfand.4@gmail.com>
  • Loading branch information
danielhelfand committed Jul 21, 2023
1 parent 7325567 commit 7cf6cdc
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
13 changes: 12 additions & 1 deletion pkg/kube/unstructured/unstructured.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,18 @@ func ResourceOperationInNamespace(dynamicClient dynamic.Interface, resource unst
case common.OperationUpdate:
currentResourceVersion, err := dynamicClient.Resource(gvr.Resource).Namespace(namespace).Get(context.Background(), unstruct.GetName(), metav1.GetOptions{})
if err != nil {
return err
if kerrors.IsNotFound(err) {
_, err = dynamicClient.Resource(gvr.Resource).Namespace(namespace).Create(context.Background(), unstruct, metav1.CreateOptions{})
if err != nil {
return err

Check warning on line 92 in pkg/kube/unstructured/unstructured.go

View check run for this annotation

Codecov / codecov/patch

pkg/kube/unstructured/unstructured.go#L92

Added line #L92 was not covered by tests
}

log.Infof("%s %s has been created in namespace %s", unstruct.GetKind(), unstruct.GetName(), namespace)

return nil
} else {
return err

Check warning on line 99 in pkg/kube/unstructured/unstructured.go

View check run for this annotation

Codecov / codecov/patch

pkg/kube/unstructured/unstructured.go#L98-L99

Added lines #L98 - L99 were not covered by tests
}
}

unstruct.SetResourceVersion(currentResourceVersion.DeepCopy().GetResourceVersion())
Expand Down
19 changes: 19 additions & 0 deletions pkg/kube/unstructured/unstructured_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,25 @@ func TestResourceOperationInNamespace(t *testing.T) {
}
}

func TestResourceOperationInNamespaceCreatesResourceWithUpdateOperation(t *testing.T) {
dynScheme := runtime.NewScheme()
fakeDynamicClient := fakeDynamic.NewSimpleDynamicClient(dynScheme)

deploymentFromYaml, err := resourceFromYaml("../../test/templates/resource-without-namespace.yaml")
if err != nil {
t.Errorf(err.Error())
}

deploymentUnstructured := unstructuredResource{
GVR: &meta.RESTMapping{},
Resource: deploymentFromYaml,
}

if err := ResourceOperationInNamespace(fakeDynamicClient, deploymentUnstructured, "update", "test-namespace"); err != nil {
t.Errorf("ResourceOperationInNamespace() error = %v", err)
}
}

func resourcePath(resourceFileName string) string {
return filepath.Join("../../../test/templates", resourceFileName)
}
Expand Down

0 comments on commit 7cf6cdc

Please sign in to comment.