Sign In

Curriculum 20: Kubeconfig & Contexts

Merging Configs

12 min · 35 XP

Merging Kubeconfig Files

When different teams or cloud providers give you separate kubeconfig files, you need a way to combine them. Kubernetes supports merging multiple config files through the KUBECONFIG environment variable.

The KUBECONFIG Environment Variable

Instead of copying everything into a single file, you can point kubectl at multiple files separated by colons (or semicolons on Windows):

# Set multiple kubeconfig files
export KUBECONFIG=~/.kube/config:~/.kube/staging-config:~/.kube/prod-config

# Verify the merged result
kubectl config view

# All contexts from every file are now available
kubectl config get-contexts

kubectl merges these files in order. If the same context name exists in multiple files, the first file wins.

Making It Permanent

Add the export to your shell profile so it persists across sessions:

# Add to ~/.bashrc or ~/.zshrc
echo 'export KUBECONFIG=~/.kube/config:~/.kube/staging-config:~/.kube/prod-config' >> ~/.zshrc
source ~/.zshrc

Flattening Into a Single File

If you prefer a single merged file, use config view --flatten:

# Merge and flatten all configs into one file
KUBECONFIG=~/.kube/config:~/.kube/staging-config \
  kubectl config view --flatten > ~/.kube/merged-config

# Replace the original config (back up first)
cp ~/.kube/config ~/.kube/config.backup
mv ~/.kube/merged-config ~/.kube/config

The --flatten flag ensures that certificate data and tokens are embedded directly in the output rather than referenced as file paths.

Adding a New File Dynamically

# Temporarily add a new config for one session
export KUBECONFIG=$KUBECONFIG:~/Downloads/new-cluster-config
kubectl config get-contexts

Key Takeaways

  • The KUBECONFIG variable accepts multiple file paths separated by colons
  • kubectl merges all specified files and presents a unified view
  • config view --flatten produces a self-contained single config file
  • Always back up your config before overwriting it