Skip to content

Commit

Permalink
k8s: prep work to uniform annotations style
Browse files Browse the repository at this point in the history
This is a preparatory commit to the conversion of the annotations to the
xxxxxx.cilium.io/... from, introducing a function to retrieve the value
of an annotation associated with a given key, or one of the additional
aliases if not found.

Signed-off-by: Marco Iorio <[email protected]>
  • Loading branch information
giorio94 authored and qmonnet committed Feb 1, 2023
1 parent 9d41018 commit 6be2ebb
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
15 changes: 15 additions & 0 deletions pkg/annotation/k8s.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
}
61 changes: 61 additions & 0 deletions pkg/annotation/k8s_test.go
Original file line number Diff line number Diff line change
@@ -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)
})
}
}

0 comments on commit 6be2ebb

Please sign in to comment.