Sign In

Curriculum 23: Advanced Output & Scripting

Go Templates

18 min · 35 XP

Go Template Output

Go templates offer more formatting power than JSONPath when you need conditional logic, string functions, or complex layouts. kubectl supports Go templates with the -o go-template flag.

Basic Syntax

# Print a pod's name
kubectl get pod my-app -o go-template='{{.metadata.name}}'

# Print name and namespace
kubectl get pod my-app -o go-template='{{.metadata.name}} in {{.metadata.namespace}}'

Template expressions are wrapped in double curly braces.

Iterating with range

For lists, use range to loop through items:

# Print each pod name on its own line
kubectl get pods -o go-template='{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'

# Print name and status as a formatted table
kubectl get pods -o go-template='{{range .items}}{{printf "%-30s %s\n" .metadata.name .status.phase}}{{end}}'

Conditional Output

Go templates support if statements for conditional rendering:

# Only print pods that are not Running
kubectl get pods -o go-template='{{range .items}}{{if ne .status.phase "Running"}}{{.metadata.name}} - {{.status.phase}}{{"\n"}}{{end}}{{end}}'

Using printf for Formatting

The printf function gives you control over spacing and alignment:

# Formatted output with columns
kubectl get pods -o go-template='{{range .items}}{{printf "%-40s %-15s %s\n" .metadata.name .status.phase .status.podIP}}{{end}}'

Accessing Nested and Optional Fields

Use index to safely access map keys or nested fields:

# Get a specific label value
kubectl get pod my-app -o go-template='{{index .metadata.labels "app.kubernetes.io/name"}}'

# Handle missing fields with if
kubectl get pods -o go-template='{{range .items}}{{if .metadata.deletionTimestamp}}TERMINATING: {{.metadata.name}}{{"\n"}}{{end}}{{end}}'

Go Template from a File

For complex templates, store them in a file:

# Save template to a file
# my-template.tmpl contains: {{range .items}}{{.metadata.name}}{{"\n"}}{{end}}

kubectl get pods -o go-template-file=my-template.tmpl

Key Takeaways

  • Go templates use double curly braces for expressions
  • range iterates over lists; if adds conditional logic
  • printf provides precise formatting control
  • Use go-template-file for reusable, complex templates