Skip to content

Commit 2eef243

Browse files
author
Kubernetes Submit Queue
authored
Merge pull request #39954 from ncdc/automated-cherry-pick-of-#39486-#39895-#39038-upstream-release-1.5
Automatic merge from submit-queue Automated cherry pick of #39486 #39895 #39038 Cherry pick of #39486 #39895 #39038 on release-1.5. #39486: Allow missing keys in templates by default #39895: Fix expected error text #39038: Fix kubectl get -f <file> -o <nondefault printer>
2 parents 63a4e72 + 3bdd803 commit 2eef243

13 files changed

Lines changed: 221 additions & 117 deletions

File tree

‎hack/make-rules/test-cmd.sh‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1251,6 +1251,47 @@ __EOF__
12511251
kube::test::if_has_string "${output_message}" "/apis/extensions/v1beta1/namespaces/default/deployments 200 OK"
12521252
kube::test::if_has_string "${output_message}" "/apis/extensions/v1beta1/namespaces/default/replicasets 200 OK"
12531253

1254+
### Test --allow-missing-template-keys
1255+
# Pre-condition: no POD exists
1256+
create_and_use_new_namespace
1257+
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
1258+
# Command
1259+
kubectl create -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml "${kube_flags[@]}"
1260+
# Post-condition: valid-pod POD is created
1261+
kubectl get "${kube_flags[@]}" pods -o json
1262+
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
1263+
1264+
## check --allow-missing-template-keys defaults to true for jsonpath templates
1265+
kubectl get "${kube_flags[@]}" pod valid-pod -o jsonpath='{.missing}'
1266+
1267+
## check --allow-missing-template-keys defaults to true for go templates
1268+
kubectl get "${kube_flags[@]}" pod valid-pod -o go-template='{{.missing}}'
1269+
1270+
## check --allow-missing-template-keys=false results in an error for a missing key with jsonpath
1271+
output_message=$(! kubectl get pod valid-pod --allow-missing-template-keys=false -o jsonpath='{.missing}' "${kube_flags[@]}")
1272+
kube::test::if_has_string "${output_message}" 'missing is not found'
1273+
1274+
## check --allow-missing-template-keys=false results in an error for a missing key with go
1275+
output_message=$(! kubectl get pod valid-pod --allow-missing-template-keys=false -o go-template='{{.missing}}' "${kube_flags[@]}")
1276+
kube::test::if_has_string "${output_message}" 'map has no entry for key "missing"'
1277+
1278+
# cleanup
1279+
kubectl delete pods valid-pod "${kube_flags[@]}"
1280+
1281+
### Test 'kubectl get -f <file> -o <non default printer>' prints all the items in the file's list
1282+
# Pre-condition: no POD exists
1283+
kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
1284+
# Command
1285+
kubectl create -f test/fixtures/doc-yaml/user-guide/multi-pod.yaml "${kube_flags[@]}"
1286+
# Post-condition: PODs redis-master and redis-proxy exist
1287+
1288+
# Check that all items in the list are printed
1289+
output_message=$(kubectl get -f test/fixtures/doc-yaml/user-guide/multi-pod.yaml -o jsonpath="{..metadata.name}" "${kube_flags[@]}")
1290+
kube::test::if_has_string "${output_message}" "redis-master redis-proxy"
1291+
1292+
# cleanup
1293+
kubectl delete pods redis-master redis-proxy "${kube_flags[@]}"
1294+
12541295

12551296
##################
12561297
# Global timeout #

‎hack/verify-flags/known-flags.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ advertised-address
77
algorithm-provider
88
all-namespaces
99
allocate-node-cidrs
10+
allow-missing-template-keys
1011
allow-privileged
1112
allowed-not-ready-nodes
1213
anonymous-auth

‎pkg/kubectl/cmd/annotate.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -196,14 +196,14 @@ func (o AnnotateOptions) RunAnnotate(f cmdutil.Factory, cmd *cobra.Command) erro
196196
return err
197197
}
198198

199-
var singularResource bool
200-
r.IntoSingular(&singularResource)
199+
var singleItemImpliedResource bool
200+
r.IntoSingleItemImplied(&singleItemImpliedResource)
201201

202202
// only apply resource version locking on a single resource.
203203
// we must perform this check after o.builder.Do() as
204204
// []o.resources can not not accurately return the proper number
205205
// of resources when they are not passed in "resource/name" format.
206-
if !singularResource && len(o.resourceVersion) > 0 {
206+
if !singleItemImpliedResource && len(o.resourceVersion) > 0 {
207207
return fmt.Errorf("--resource-version may only be used with a single resource")
208208
}
209209

‎pkg/kubectl/cmd/clusterinfo_dump.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ func dumpClusterInfo(f cmdutil.Factory, cmd *cobra.Command, args []string, out i
9191
return err
9292
}
9393

94-
printer, _, err := kubectl.GetPrinter("json", "", false)
94+
printer, _, err := kubectl.GetPrinter("json", "", false, true)
9595
if err != nil {
9696
return err
9797
}

‎pkg/kubectl/cmd/convert.go‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ func (o *ConvertOptions) Complete(f cmdutil.Factory, out io.Writer, cmd *cobra.C
146146
}
147147
}
148148
o.encoder = f.JSONEncoder()
149-
o.printer, _, err = kubectl.GetPrinter(outputFormat, templateFile, false)
149+
o.printer, _, err = kubectl.GetPrinter(outputFormat, templateFile, false, cmdutil.GetFlagBool(cmd, "allow-missing-template-keys"))
150150
if err != nil {
151151
return err
152152
}
@@ -162,8 +162,8 @@ func (o *ConvertOptions) RunConvert() error {
162162
return err
163163
}
164164

165-
singular := false
166-
infos, err := r.IntoSingular(&singular).Infos()
165+
singleItemImplied := false
166+
infos, err := r.IntoSingleItemImplied(&singleItemImplied).Infos()
167167
if err != nil {
168168
return err
169169
}
@@ -172,7 +172,7 @@ func (o *ConvertOptions) RunConvert() error {
172172
return fmt.Errorf("no objects passed to convert")
173173
}
174174

175-
objects, err := resource.AsVersionedObject(infos, !singular, o.outputVersion, o.encoder)
175+
objects, err := resource.AsVersionedObject(infos, !singleItemImplied, o.outputVersion, o.encoder)
176176
if err != nil {
177177
return err
178178
}

‎pkg/kubectl/cmd/get.go‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -310,10 +310,10 @@ func RunGet(f cmdutil.Factory, out, errOut io.Writer, cmd *cobra.Command, args [
310310
// 2. if there is a single item and that item is a list, leave it as its specific list
311311
// 3. if there is a single item and it is not a a list, leave it as a single item
312312
var errs []error
313-
singular := false
314-
infos, err := r.IntoSingular(&singular).Infos()
313+
singleItemImplied := false
314+
infos, err := r.IntoSingleItemImplied(&singleItemImplied).Infos()
315315
if err != nil {
316-
if singular {
316+
if singleItemImplied {
317317
return err
318318
}
319319
errs = append(errs, err)
@@ -328,9 +328,7 @@ func RunGet(f cmdutil.Factory, out, errOut io.Writer, cmd *cobra.Command, args [
328328
}
329329

330330
var obj runtime.Object
331-
if singular {
332-
obj = infos[0].Object
333-
} else {
331+
if !singleItemImplied || len(infos) > 1 {
334332
// we have more than one item, so coerce all items into a list
335333
list := &runtime.UnstructuredList{
336334
Object: map[string]interface{}{
@@ -343,6 +341,8 @@ func RunGet(f cmdutil.Factory, out, errOut io.Writer, cmd *cobra.Command, args [
343341
list.Items = append(list.Items, info.Object.(*runtime.Unstructured))
344342
}
345343
obj = list
344+
} else {
345+
obj = infos[0].Object
346346
}
347347

348348
isList := meta.IsListType(obj)

‎pkg/kubectl/cmd/label.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ func (o *LabelOptions) RunLabel(f cmdutil.Factory, cmd *cobra.Command) error {
187187
Latest()
188188
}
189189
one := false
190-
r := b.Do().IntoSingular(&one)
190+
r := b.Do().IntoSingleItemImplied(&one)
191191
if err := r.Err(); err != nil {
192192
return err
193193
}

‎pkg/kubectl/cmd/util/printing.go‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ func AddOutputFlagsForMutation(cmd *cobra.Command) {
4848
// AddOutputFlags adds output related flags to a command.
4949
func AddOutputFlags(cmd *cobra.Command) {
5050
cmd.Flags().StringP("output", "o", "", "Output format. One of: json|yaml|wide|name|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=... See custom columns [http://kubernetes.io/docs/user-guide/kubectl-overview/#custom-columns], golang template [http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template [http://kubernetes.io/docs/user-guide/jsonpath].")
51+
cmd.Flags().Bool("allow-missing-template-keys", true, "If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.")
5152
}
5253

5354
// AddNoHeadersFlags adds no-headers flags to a command.
@@ -125,7 +126,13 @@ func PrinterForCommand(cmd *cobra.Command) (kubectl.ResourcePrinter, bool, error
125126
}
126127
}
127128

128-
printer, generic, err := kubectl.GetPrinter(outputFormat, templateFile, GetFlagBool(cmd, "no-headers"))
129+
// this function may be invoked by a command that did not call AddPrinterFlags first, so we need
130+
// to be safe about how we access the allow-missing-template-keys flag
131+
allowMissingTemplateKeys := false
132+
if cmd.Flags().Lookup("allow-missing-template-keys") != nil {
133+
allowMissingTemplateKeys = GetFlagBool(cmd, "allow-missing-template-keys")
134+
}
135+
printer, generic, err := kubectl.GetPrinter(outputFormat, templateFile, GetFlagBool(cmd, "no-headers"), allowMissingTemplateKeys)
129136
if err != nil {
130137
return nil, generic, err
131138
}

‎pkg/kubectl/resource/builder.go‎

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ type Builder struct {
7272
singleResourceType bool
7373
continueOnError bool
7474

75-
singular bool
75+
singleItemImplied bool
7676

7777
export bool
7878

@@ -139,7 +139,7 @@ func (b *Builder) FilenameParam(enforceNamespace bool, filenameOptions *Filename
139139
b.URL(defaultHttpGetAttempts, url)
140140
default:
141141
if !recursive {
142-
b.singular = true
142+
b.singleItemImplied = true
143143
}
144144
b.Path(recursive, s)
145145
}
@@ -600,21 +600,21 @@ func (b *Builder) visitBySelector() *Result {
600600
}
601601

602602
func (b *Builder) visitByResource() *Result {
603-
// if b.singular is false, this could be by default, so double-check length
604-
// of resourceTuples to determine if in fact it is singular or not
605-
isSingular := b.singular
606-
if !isSingular {
607-
isSingular = len(b.resourceTuples) == 1
603+
// if b.singleItemImplied is false, this could be by default, so double-check length
604+
// of resourceTuples to determine if in fact it is singleItemImplied or not
605+
isSingleItemImplied := b.singleItemImplied
606+
if !isSingleItemImplied {
607+
isSingleItemImplied = len(b.resourceTuples) == 1
608608
}
609609

610610
if len(b.resources) != 0 {
611-
return &Result{singular: isSingular, err: fmt.Errorf("you may not specify individual resources and bulk resources in the same call")}
611+
return &Result{singleItemImplied: isSingleItemImplied, err: fmt.Errorf("you may not specify individual resources and bulk resources in the same call")}
612612
}
613613

614614
// retrieve one client for each resource
615615
mappings, err := b.resourceTupleMappings()
616616
if err != nil {
617-
return &Result{singular: isSingular, err: err}
617+
return &Result{singleItemImplied: isSingleItemImplied, err: err}
618618
}
619619
clients := make(map[string]RESTClient)
620620
for _, mapping := range mappings {
@@ -633,12 +633,12 @@ func (b *Builder) visitByResource() *Result {
633633
for _, tuple := range b.resourceTuples {
634634
mapping, ok := mappings[tuple.Resource]
635635
if !ok {
636-
return &Result{singular: isSingular, err: fmt.Errorf("resource %q is not recognized: %v", tuple.Resource, mappings)}
636+
return &Result{singleItemImplied: isSingleItemImplied, err: fmt.Errorf("resource %q is not recognized: %v", tuple.Resource, mappings)}
637637
}
638638
s := fmt.Sprintf("%s/%s", mapping.GroupVersionKind.GroupVersion().String(), mapping.Resource)
639639
client, ok := clients[s]
640640
if !ok {
641-
return &Result{singular: isSingular, err: fmt.Errorf("could not find a client for resource %q", tuple.Resource)}
641+
return &Result{singleItemImplied: isSingleItemImplied, err: fmt.Errorf("could not find a client for resource %q", tuple.Resource)}
642642
}
643643

644644
selectorNamespace := b.namespace
@@ -650,7 +650,7 @@ func (b *Builder) visitByResource() *Result {
650650
if b.allNamespace {
651651
errMsg = "a resource cannot be retrieved by name across all namespaces"
652652
}
653-
return &Result{singular: isSingular, err: fmt.Errorf(errMsg)}
653+
return &Result{singleItemImplied: isSingleItemImplied, err: fmt.Errorf(errMsg)}
654654
}
655655
}
656656

@@ -664,25 +664,25 @@ func (b *Builder) visitByResource() *Result {
664664
} else {
665665
visitors = VisitorList(items)
666666
}
667-
return &Result{singular: isSingular, visitor: visitors, sources: items}
667+
return &Result{singleItemImplied: isSingleItemImplied, visitor: visitors, sources: items}
668668
}
669669

670670
func (b *Builder) visitByName() *Result {
671-
isSingular := len(b.names) == 1
671+
isSingleItemImplied := len(b.names) == 1
672672

673673
if len(b.paths) != 0 {
674-
return &Result{singular: isSingular, err: fmt.Errorf("when paths, URLs, or stdin is provided as input, you may not specify a resource by arguments as well")}
674+
return &Result{singleItemImplied: isSingleItemImplied, err: fmt.Errorf("when paths, URLs, or stdin is provided as input, you may not specify a resource by arguments as well")}
675675
}
676676
if len(b.resources) == 0 {
677-
return &Result{singular: isSingular, err: fmt.Errorf("you must provide a resource and a resource name together")}
677+
return &Result{singleItemImplied: isSingleItemImplied, err: fmt.Errorf("you must provide a resource and a resource name together")}
678678
}
679679
if len(b.resources) > 1 {
680-
return &Result{singular: isSingular, err: fmt.Errorf("you must specify only one resource")}
680+
return &Result{singleItemImplied: isSingleItemImplied, err: fmt.Errorf("you must specify only one resource")}
681681
}
682682

683683
mappings, err := b.resourceMappings()
684684
if err != nil {
685-
return &Result{singular: isSingular, err: err}
685+
return &Result{singleItemImplied: isSingleItemImplied, err: err}
686686
}
687687
mapping := mappings[0]
688688

@@ -700,7 +700,7 @@ func (b *Builder) visitByName() *Result {
700700
if b.allNamespace {
701701
errMsg = "a resource cannot be retrieved by name across all namespaces"
702702
}
703-
return &Result{singular: isSingular, err: fmt.Errorf(errMsg)}
703+
return &Result{singleItemImplied: isSingleItemImplied, err: fmt.Errorf(errMsg)}
704704
}
705705
}
706706

@@ -709,13 +709,13 @@ func (b *Builder) visitByName() *Result {
709709
info := NewInfo(client, mapping, selectorNamespace, name, b.export)
710710
visitors = append(visitors, info)
711711
}
712-
return &Result{singular: isSingular, visitor: VisitorList(visitors), sources: visitors}
712+
return &Result{singleItemImplied: isSingleItemImplied, visitor: VisitorList(visitors), sources: visitors}
713713
}
714714

715715
func (b *Builder) visitByPaths() *Result {
716-
singular := !b.dir && !b.stream && len(b.paths) == 1
716+
singleItemImplied := !b.dir && !b.stream && len(b.paths) == 1
717717
if len(b.resources) != 0 {
718-
return &Result{singular: singular, err: fmt.Errorf("when paths, URLs, or stdin is provided as input, you may not specify resource arguments as well")}
718+
return &Result{singleItemImplied: singleItemImplied, err: fmt.Errorf("when paths, URLs, or stdin is provided as input, you may not specify resource arguments as well")}
719719
}
720720
if len(b.names) != 0 {
721721
return &Result{err: fmt.Errorf("name cannot be provided when a path is specified")}
@@ -746,7 +746,7 @@ func (b *Builder) visitByPaths() *Result {
746746
if b.selector != nil {
747747
visitors = NewFilteredVisitor(visitors, FilterBySelector(b.selector))
748748
}
749-
return &Result{singular: singular, visitor: visitors, sources: b.paths}
749+
return &Result{singleItemImplied: singleItemImplied, visitor: visitors, sources: b.paths}
750750
}
751751

752752
// Do returns a Result object with a Visitor for the resources identified by the Builder.

0 commit comments

Comments
 (0)