From 70a2a1b0496983d85362554b84c27eb454b54235 Mon Sep 17 00:00:00 2001 From: Nicholas Thomson Date: Wed, 12 May 2021 16:09:53 -0700 Subject: [PATCH] Add additional keys to set identifiers --- templates/pkg/resource/resource.go.tpl | 30 +++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/templates/pkg/resource/resource.go.tpl b/templates/pkg/resource/resource.go.tpl index ef36e53f..be9728db 100644 --- a/templates/pkg/resource/resource.go.tpl +++ b/templates/pkg/resource/resource.go.tpl @@ -3,9 +3,14 @@ package {{ .CRD.Names.Snake }} import ( + "reflect" + "strings" + ackv1alpha1 "github.com/aws-controllers-k8s/runtime/apis/core/v1alpha1" acktypes "github.com/aws-controllers-k8s/runtime/pkg/types" +{{- if $idField := .CRD.SpecIdentifierField }} ackerrors "github.com/aws-controllers-k8s/runtime/pkg/errors" +{{- end }} metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" k8srt "k8s.io/apimachinery/pkg/runtime" @@ -67,7 +72,8 @@ func (r *resource) SetObjectMeta(meta metav1.ObjectMeta) { } // SetIdentifiers sets the Spec or Status field that is referenced as the unique -// resource identifier +// resource identifier and any additional spec fields that may be required for +// describing the resource. func (r *resource) SetIdentifiers(identifier *ackv1alpha1.AWSIdentifiers) error { {{- if $idField := .CRD.SpecIdentifierField }} if identifier.NameOrID == nil { @@ -75,7 +81,29 @@ func (r *resource) SetIdentifiers(identifier *ackv1alpha1.AWSIdentifiers) error } r.ko.Spec.{{ $idField }} = identifier.NameOrID {{- else }} + if r.ko.Status.ACKResourceMetadata == nil { + r.ko.Status.ACKResourceMetadata = &ackv1alpha1.ResourceMetadata{} + } r.ko.Status.ACKResourceMetadata.ARN = identifier.ARN {{- end }} + + if len(identifier.AdditionalKeys) == 0 { + return nil + } + + specRef := reflect.Indirect(reflect.ValueOf(&r.ko.Spec)) + specType := specRef.Type() + + // Iterate over spec fields and associate corresponding json tags + for i := 0; i < specRef.NumField(); i++ { + // Get only the first field in the json tag (the field name) + jsonTag := strings.Split(specType.Field(i).Tag.Get("json"), ",")[0] + val, ok := identifier.AdditionalKeys[jsonTag] + if ok { + // Set the corresponding field with the value from the mapping + specRef.FieldByName(specType.Field(i).Name).Set(reflect.ValueOf(val)) + } + } + return nil } \ No newline at end of file