mirror of
https://github.com/k3s-io/kubernetes.git
synced 2025-09-21 01:50:55 +00:00
Expose single annotation/label via downward API
This commit is contained in:
@@ -42,7 +42,20 @@ func ExtractFieldPathAsString(obj interface{}, fieldPath string) (string, error)
|
||||
return "", nil
|
||||
}
|
||||
|
||||
switch fieldPath {
|
||||
path, subscript := SplitMaybeSubscriptedPath(fieldPath)
|
||||
|
||||
if len(subscript) > 0 {
|
||||
switch path {
|
||||
case "metadata.annotations":
|
||||
return accessor.GetAnnotations()[subscript], nil
|
||||
case "metadata.labels":
|
||||
return accessor.GetLabels()[subscript], nil
|
||||
default:
|
||||
return "", fmt.Errorf("fieldPath %q does not support subscript", fieldPath)
|
||||
}
|
||||
}
|
||||
|
||||
switch path {
|
||||
case "metadata.annotations":
|
||||
return FormatMap(accessor.GetAnnotations()), nil
|
||||
case "metadata.labels":
|
||||
@@ -57,3 +70,29 @@ func ExtractFieldPathAsString(obj interface{}, fieldPath string) (string, error)
|
||||
|
||||
return "", fmt.Errorf("unsupported fieldPath: %v", fieldPath)
|
||||
}
|
||||
|
||||
// SplitMaybeSubscriptedPath checks whether the specified fieldPath is
|
||||
// subscripted, and
|
||||
// - if yes, this function splits the fieldPath into path and subscript, and
|
||||
// returns (path, subscript).
|
||||
// - if no, this function returns (fieldPath, "").
|
||||
//
|
||||
// Example inputs and outputs:
|
||||
// - "metadata.annotations['myKey']" --> ("metadata.annotations", "myKey")
|
||||
// - "metadata.annotations['a[b]c']" --> ("metadata.annotations", "a[b]c")
|
||||
// - "metadata.labels" --> ("metadata.labels", "")
|
||||
// - "metadata.labels['']" --> ("metadata.labels", "")
|
||||
func SplitMaybeSubscriptedPath(fieldPath string) (string, string) {
|
||||
if !strings.HasSuffix(fieldPath, "']") {
|
||||
return fieldPath, ""
|
||||
}
|
||||
s := strings.TrimSuffix(fieldPath, "']")
|
||||
parts := strings.SplitN(s, "['", 2)
|
||||
if len(parts) < 2 {
|
||||
return fieldPath, ""
|
||||
}
|
||||
if len(parts[0]) == 0 || len(parts[1]) == 0 {
|
||||
return fieldPath, ""
|
||||
}
|
||||
return parts[0], parts[1]
|
||||
}
|
||||
|
Reference in New Issue
Block a user