Skip to main content

question1


sidebar_position: 1 title: "Question 1 - kubectl Context Management" sidebar_label: "Question 1" description: "CKA exam practical question 1: kubectl context management, listing available contexts and getting current context with and without kubectl." keywords:

  • cka question
  • practical exam
  • kubernetes hands-on
  • step-by-step solution
  • kubectl contexts
  • context management
  • current-context
  • kubectl configuration
  • kubeconfig
  • multiple clusters slug: /kubernetes/cka/solved-questions/question1 image: /img/social-cards/kubernetes.png

Question 1 | Contexts

You have access to multiple clusters from your main terminal through kubectl contexts. Write all those context names into /opt/course/1/contexts.

Next write a command to display the current context into /opt/course/1/context_default_kubectl.sh, the command should use kubectl.

Finally write a second command doing the same thing into /opt/course/1/context_default_no_kubectl.sh, but without the use of kubectl.


k config get-contexts -o name > /opt/course/1/contexts

# Using json path

# Just to check
k config view -o yaml
# Will return all results in a line separated by spaces
k config view -o jsonpath="{.contexts[*].name}"
# Let's change spaces to new lines and write to file
k config view -o jsonpath="{.contexts[*].name}" | tr " " "\n" > /opt/course/1/contexts

# Getting the current-context and writing to file

echo 'kubectl config current-context' > /opt/course/1/context_default_kubectl.sh
sh /opt/course/1/context_default_kubectl.sh

# The second method without using kubectl

# We could filter by current-context and print only the second part
cat ~/.kube/config | grep current | awk '{print $2}'
# or we could delete the first part
cat ~/.kube/config | grep current | sed -e "s/current-context: //"

# Write the command to /opt/course/1/context_default_no_kubectl.sh
sh /opt/course/1/context_default_no_kubectl.sh