diff --git a/pkg/annotation/k8s.go b/pkg/annotation/k8s.go index 2137bbeb1af03..c8f92f3fb7f07 100644 --- a/pkg/annotation/k8s.go +++ b/pkg/annotation/k8s.go @@ -3,6 +3,8 @@ package annotation +import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + const ( // Prefix is the common prefix for all annotations Prefix = "io.cilium" @@ -82,3 +84,16 @@ const ( // to that node. WireguardPubKey = Prefix + ".network.wg-pub-key" ) + +// Get returns the annotation value associated with the given key, or any of +// the additional aliases if not found. +func Get(obj metav1.Object, key string, aliases ...string) (value string, ok bool) { + keys := append([]string{key}, aliases...) + for _, k := range keys { + if value, ok = obj.GetAnnotations()[k]; ok { + return value, ok + } + } + + return "", false +} diff --git a/pkg/annotation/k8s_test.go b/pkg/annotation/k8s_test.go new file mode 100644 index 0000000000000..fd4e9d606eae0 --- /dev/null +++ b/pkg/annotation/k8s_test.go @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright Authors of Cilium + +package annotation + +import ( + "testing" + + "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" +) + +func TestGet(t *testing.T) { + var ( + key = "key" + aliases = []string{"key-alt-1", "key-alt-2"} + obj = corev1.Service{} + ) + + tests := []struct { + name string + annotations map[string]string + wantValue string + wantOK bool + }{ + { + "the searched annotation is not present", + map[string]string{"other": "other"}, + "", false, + }, + { + "the searched annotation is present (preferred key)", + map[string]string{"key": "value", "other": "other"}, + "value", true, + }, + { + "the searched annotation is present (alias)", + map[string]string{"key-alt-1": "value-alt-1", "other": "other"}, + "value-alt-1", true, + }, + { + "the searched annotation is present (both preferred and alias keys)", + map[string]string{"key": "value", "key-alt-1": "value-alt-1", "other": "other"}, + "value", true, + }, + { + "the searched annotation is present (both alias keys)", + map[string]string{"key-alt-1": "value-alt-1", "key-alt-2": "value-alt-2", "other": "other"}, + "value-alt-1", true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + obj.ObjectMeta.Annotations = tt.annotations + value, ok := Get(&obj, key, aliases...) + require.Equal(t, tt.wantValue, value) + require.Equal(t, tt.wantOK, ok) + }) + } +}