Module 0.3: Vim for YAML
Complexity:
[QUICK]- Learn 10 commands, use them foreverTime to Complete: 20-30 minutes
Prerequisites: None (Vim is pre-installed on exam systems)
What You’ll Be Able to Do
Section titled “What You’ll Be Able to Do”After this module, you will be able to:
- Edit YAML files in vim with proper indentation (2 spaces, no tabs)
- Fix common YAML errors (wrong indentation, missing fields) in under 30 seconds
- Configure vim settings (.vimrc) that make YAML editing painless in the exam
- Use the 10 essential vim commands that cover 95% of CKA editing tasks
Why This Module Matters
Section titled “Why This Module Matters”The CKA exam requires editing YAML files. A lot. You’ll create manifests, fix broken configs, and modify existing resources—all in a terminal.
The exam environment defaults to nano (as of 2025), but you can switch to vim. Whether you use vim or nano, you need to be fast. This module covers vim because it’s more powerful once you know the basics.
If you prefer nano, that’s fine—it’s simpler. But vim skills transfer to production troubleshooting where nano might not be available.
Part 1: Vim Survival Kit
Section titled “Part 1: Vim Survival Kit”The honest truth: Most CKA candidates spend 2 hours learning vim and then use
i(insert),Esc,:wq(save and quit), andu(undo) for 90% of their editing. That’s fine. The 10 commands below cover the remaining 10% that saves you minutes per question — indentation fixes, block deletion, and search-replace.
You don’t need to be a vim expert. You need 10 commands.
1.1 Modes
Section titled “1.1 Modes”Vim has modes. This confuses everyone at first.
The Gearshift Analogy
Vim modes are like a car’s gearshift. In Normal mode (drive), you’re navigating—moving around, not typing. In Insert mode (park), you’re stationary and typing. In Command mode (reverse), you’re doing special operations like saving. You wouldn’t try to park while driving. Vim forces you to “shift gears” deliberately. It feels weird at first, but it’s what makes vim so fast once you internalize it.
Pause and predict: If you are typing text and suddenly your backspace stops working or you start deleting lines by accident, what mode are you likely in, and how do you fix it?
| Mode | How to Enter | What It Does |
|---|---|---|
| Normal | Esc | Navigate, delete, copy, paste |
| Insert | i, a, o | Type text |
| Command | : | Save, quit, search |
Rule: When confused, press Esc to return to Normal mode.
1.2 Essential Commands
Section titled “1.2 Essential Commands”ENTERING INSERT MODEi Insert before cursora Insert after cursoro Open new line below and insertO Open new line above and insert
NAVIGATION (Normal mode)h Leftj Downk Upl Rightgg Go to first lineG Go to last line0 Go to beginning of line$ Go to end of linew Jump forward one wordb Jump backward one word
EDITING (Normal mode)x Delete character under cursordd Delete entire lineyy Copy (yank) entire linep Paste belowP Paste aboveu UndoCtrl+r Redo
SEARCH/pattern Search forwardn Next matchN Previous match
SAVE AND QUIT:w Save (write):q Quit:wq Save and quit:q! Quit without saving (discard changes)1.3 The Minimum You Need
Section titled “1.3 The Minimum You Need”Honestly? For the exam, you can survive with:
i → Start typingEsc → Stop typing:wq → Save and quitdd → Delete lineu → Undo mistakeThat’s 5 things. Master these, and you won’t fail because of vim.
Part 2: Vim Configuration for YAML
Section titled “Part 2: Vim Configuration for YAML”2.1 Create ~/.vimrc
Section titled “2.1 Create ~/.vimrc”YAML is whitespace-sensitive. A misconfigured vim will ruin your indentation.
cat << 'EOF' > ~/.vimrc" Basic settingsset number " Show line numbersset tabstop=2 " Tab = 2 spacesset shiftwidth=2 " Indent = 2 spacesset expandtab " Use spaces, not tabsset autoindent " Maintain indentationset smartindent " Smart indentation for codeset paste " Prevent auto-indent on paste (toggle with :set nopaste)
" YAML specificautocmd FileType yaml setlocal ts=2 sts=2 sw=2 expandtab
" Visual helpersset cursorline " Highlight current linesyntax on " Syntax highlightingset hlsearch " Highlight search resultsEOF2.2 Why These Settings Matter
Section titled “2.2 Why These Settings Matter”| Setting | Why |
|---|---|
tabstop=2 | Kubernetes YAML uses 2-space indentation |
expandtab | Converts tabs to spaces (tabs break YAML) |
autoindent | New lines maintain indentation |
number | Line numbers help with error messages |
set paste | Prevents auto-indent issues when pasting |
Stop and think: Why might setting
tabstop=2not be enough on its own to prevent YAML parsing errors when you press the Tab key?
Gotcha: Tabs vs Spaces
YAML requires consistent indentation. A single tab character mixed with spaces will break your manifest. Always use spaces. The
expandtabsetting converts tabs to spaces automatically.
War Story: The Invisible Character
A senior engineer spent 45 minutes debugging why
kubectl applykept failing with a cryptic YAML parsing error. The manifest looked perfect. They eventually rancat -Aon the file and discovered invisible tab characters mixed with spaces—introduced when they copied code from a Confluence page. The lesson: never trust copy-paste. Always verify indentation, and configure your editor to show invisible characters or convert tabs automatically.
Part 3: YAML Editing Workflows
Section titled “Part 3: YAML Editing Workflows”3.1 Creating a New File
Section titled “3.1 Creating a New File”vim pod.yamlPress i to enter Insert mode, then type:
apiVersion: v1kind: Podmetadata: name: nginxspec: containers: - name: nginx image: nginxPress Esc, then :wq to save and quit.
3.2 Copying Lines (Faster Than Retyping)
Section titled “3.2 Copying Lines (Faster Than Retyping)”You need to add another container. Instead of typing from scratch:
- Navigate to the container block
- Position cursor on
- name: nginx - Press
V(visual line mode) - Press
jtwice to select 3 lines - Press
yto yank (copy) - Navigate to where you want the new container
- Press
pto paste
3.3 Indenting Blocks
Section titled “3.3 Indenting Blocks”Selected the wrong indentation? Fix it:
Vto enter visual line mode- Select lines with
j/k >to indent right<to indent left
Or in Normal mode:
>>indent current line right<<indent current line left
3.4 Deleting Multiple Lines
Section titled “3.4 Deleting Multiple Lines”Need to remove a whole section?
- Navigate to start of section
- Type
5ddto delete 5 lines - Or
d}to delete until next blank line
3.5 Search and Replace
Section titled “3.5 Search and Replace”Wrong image name throughout file?
:%s/nginx:1.19/nginx:1.25/g%s= substitute in whole file/old/new/= patterng= all occurrences (not just first)
Part 4: Paste Without Mangling
Section titled “Part 4: Paste Without Mangling”When you copy YAML from documentation and paste into vim, auto-indent can mangle it.
Method 1: Set Paste Mode
Section titled “Method 1: Set Paste Mode”Before pasting:
:set pastePaste your content (usually Cmd+V or right-click).
After pasting:
:set nopasteMethod 2: Use the Terminal Paste
Section titled “Method 2: Use the Terminal Paste”In the exam environment, you might paste directly into the terminal. The :set paste in your .vimrc helps, but be aware of it.
Method 3: Alternative—Use cat
Section titled “Method 3: Alternative—Use cat”If vim paste is problematic:
cat << 'EOF' > pod.yamlapiVersion: v1kind: Podmetadata: name: nginxspec: containers: - name: nginx image: nginxEOFThis avoids vim entirely for creating files.
Part 5: Quick Reference Card
Section titled “Part 5: Quick Reference Card”Print this or memorize it:
╔════════════════════════════════════════════════════╗║ VIM YAML QUICK REFERENCE ║╠════════════════════════════════════════════════════╣║ MODES ║║ Esc → Normal mode (navigation) ║║ i → Insert mode (typing) ║║ : → Command mode (save/quit) ║╠════════════════════════════════════════════════════╣║ MOVEMENT ║║ gg → Top of file ║║ G → Bottom of file ║║ 0 → Start of line ║║ $ → End of line ║║ /pattern → Search ║╠════════════════════════════════════════════════════╣║ EDITING ║║ dd → Delete line ║║ yy → Copy line ║║ p → Paste below ║║ u → Undo ║║ >> → Indent right ║║ << → Indent left ║╠════════════════════════════════════════════════════╣║ SAVE/QUIT ║║ :w → Save ║║ :q → Quit ║║ :wq → Save and quit ║║ :q! → Quit without saving ║╠════════════════════════════════════════════════════╣║ YAML SPECIFIC ║║ :set paste → Before pasting ║║ :set nopaste → After pasting ║╚════════════════════════════════════════════════════╝Part 6: Nano Alternative
Section titled “Part 6: Nano Alternative”If vim feels like too much, use nano. It’s the exam default now.
nano pod.yamlNano shows shortcuts at the bottom:
Ctrl+O= Save (Write Out)Ctrl+X= ExitCtrl+K= Cut lineCtrl+U= Paste
For YAML, create ~/.nanorc:
cat << 'EOF' > ~/.nanorcset tabsize 2set tabstospacesset autoindentset linenumbersEOFExam Tip
The exam environment (as of 2025) defaults to nano, but you can use vim if you prefer. Pick one and stick with it—don’t waste exam time debating editors.
Did You Know?
Section titled “Did You Know?”-
Vim is on every Linux server. Learning vim pays off beyond the exam—you’ll use it for production troubleshooting, container debugging, and anywhere a GUI isn’t available.
-
The creator of vim (Bram Moolenaar) passed away in 2023. The project continues as an open-source community effort. Neovim is a popular modern fork.
-
vimtutoris built in. Runvimtutorin any terminal for an interactive vim tutorial. Takes about 30 minutes and teaches you more than this module.
Common Mistakes
Section titled “Common Mistakes”| Mistake | Problem | Solution |
|---|---|---|
| Stuck in insert mode | Can’t navigate | Press Esc |
| Pasted YAML is mangled | Auto-indent | :set paste before pasting |
| Tab characters in YAML | YAML syntax error | Use expandtab in .vimrc |
| Lost changes | Quit without saving | Use :wq not :q! |
| Wrong indentation | YAML parsing fails | >> and << to fix |
-
Scenario: You are in the middle of the CKA exam and need to quickly remove a broken volume mount block that spans exactly three lines from your deployment manifest. How do you achieve this efficiently in vim without repeatedly pressing the delete key?
Answer
You should position your cursor on the first line of the volume mount block, ensure you are in Normal mode (press `Esc`), and type `3dd`.Why: The
dcommand in vim stands for delete, and typing it twice (dd) deletes the current line. By prefixing it with a number like3, you instruct vim to repeat the action that many times, instantly removing the block. This is significantly faster than manually deleting characters or lines, saving precious seconds during the time-constrained exam. -
Scenario: You just found a perfect snippet of YAML in the Kubernetes documentation. You copy it and paste it directly into your terminal running vim, but the indentation instantly becomes a cascading mess of misaligned blocks. What caused this formatting disaster, and how do you correctly paste the snippet next time?
Answer
Vim's auto-indentation feature interpreted your pasted spaces as new indentation levels for each line, mangling the format. To prevent this, you must type `:set paste` before pasting your clipboard contents, and `:set nopaste` afterward.Why: The paste mode temporarily disables auto-indentation and other formatting automation. This ensures that vim accepts the characters exactly as they exist in your clipboard without trying to “helpfully” adjust the spacing, keeping the YAML structure intact. If you forget this step, vim tries to apply its own indentation rules on top of the already-indented text.
-
Scenario: You have just finished adding a missing environment variable to a critical manifest. You need to apply these changes immediately, but you are currently in Insert mode typing the last quote. What exact sequence of keystrokes do you use to save your changes and exit the file?
Answer
You must first press `Esc`, followed by typing `:wq` and pressing `Enter`.Why: Vim requires you to exit Insert mode to execute file-level commands, which is why
Escis necessary to return to Normal mode. The colon:enters Command mode,wwrites (saves) the file to disk, andqquits the editor. Combining them as:wqsafely persists your critical changes and returns you to the terminal in one fluid motion, ready to runkubectl apply. -
Scenario: You create a quick Pod manifest and visually align all the fields perfectly. However, when you run
kubectl apply, you get a cryptic error parsing your YAML. You realize you used the Tab key to align some fields. Why did this happen, and how should you configure vim to prevent it?Answer
The Kubernetes YAML parser strictly expects spaces for indentation and fundamentally rejects or misinterprets tab characters, breaking the document structure. You should add `set expandtab` to your `~/.vimrc` file.Why: YAML relies on exact whitespace character counts to determine the hierarchy of objects, and a tab character does not equal a consistent number of spaces across different systems. The
expandtabsetting fixes this automatically by converting any Tab key press into the correct number of spaces (defined bytabstop), ensuring your manifests always parse correctly regardless of how you type. This completely eliminates a common source of invisible, time-wasting syntax errors.
Hands-On Exercise
Section titled “Hands-On Exercise”Task: Configure vim and practice YAML editing.
Setup:
# Create .vimrc with YAML settingscat << 'EOF' > ~/.vimrcset numberset tabstop=2set shiftwidth=2set expandtabset autoindentsyntax onEOFPractice Tasks:
-
Create a pod manifest from scratch:
Terminal window vim practice-pod.yaml# Type a complete Pod manifest# Save and exit -
Duplicate a container block:
- Open the file
- Copy the container section
- Paste and modify the name
-
Fix intentionally broken indentation:
Terminal window cat << 'EOF' > broken.yamlapiVersion: v1kind: Podmetadata:name: testspec:containers:- name: nginximage: nginxEOF# Open in vim and fix indentation
Success Criteria:
- Can create a valid Pod manifest in vim
- Can copy and paste blocks within vim
- Can fix indentation issues
- Know how to save and quit
Verification:
# Validate your YAMLkubectl apply -f practice-pod.yaml --dry-run=clientPractice Drills
Section titled “Practice Drills”Drill 1: Vim Speed Test (Target: 2 minutes)
Section titled “Drill 1: Vim Speed Test (Target: 2 minutes)”Create this pod manifest from scratch in vim:
vim speed-test.yamlType this (don’t copy-paste):
apiVersion: v1kind: Podmetadata: name: nginx labels: app: webspec: containers: - name: nginx image: nginx:1.25 ports: - containerPort: 80Save and validate:
kubectl apply -f speed-test.yaml --dry-run=clientrm speed-test.yamlDrill 2: Fix Broken YAML - Indentation (Target: 3 minutes)
Section titled “Drill 2: Fix Broken YAML - Indentation (Target: 3 minutes)”# Create broken YAMLcat << 'EOF' > broken-indent.yamlapiVersion: v1kind: Podmetadata:name: broken-pod labels: app: testspec: containers: - name: nginx image: nginx ports: - containerPort: 80EOF
# Open in vim and fix ALL indentation errorsvim broken-indent.yaml
# Validate your fixkubectl apply -f broken-indent.yaml --dry-run=clientrm broken-indent.yamlFixed Version
apiVersion: v1kind: Podmetadata: name: broken-pod labels: app: testspec: containers: - name: nginx image: nginx ports: - containerPort: 80Drill 3: Fix Broken YAML - Mixed Tabs/Spaces (Target: 3 minutes)
Section titled “Drill 3: Fix Broken YAML - Mixed Tabs/Spaces (Target: 3 minutes)”# Create YAML with hidden tab charactersprintf 'apiVersion: v1\nkind: Pod\nmetadata:\n\tname: tab-pod\nspec:\n\tcontainers:\n\t- name: nginx\n\t image: nginx\n' > broken-tabs.yaml
# Look at it - seems fine visuallycat broken-tabs.yaml
# But kubectl fails!kubectl apply -f broken-tabs.yaml --dry-run=client
# YOUR TASK: Open in vim and fixvim broken-tabs.yaml# Hint: In vim, use :%s/\t/ /g to replace tabs with spaces
kubectl apply -f broken-tabs.yaml --dry-run=clientrm broken-tabs.yamlDrill 4: Copy and Modify Blocks (Target: 2 minutes)
Section titled “Drill 4: Copy and Modify Blocks (Target: 2 minutes)”# Create a deployment with one containercat << 'EOF' > multi-container.yamlapiVersion: v1kind: Podmetadata: name: multispec: containers: - name: app image: nginx ports: - containerPort: 80EOF
# YOUR TASK in vim:# 1. Duplicate the container block# 2. Change second container to: name: sidecar, image: busybox, remove ports# Target: 2 minutes
vim multi-container.yaml
# Validatekubectl apply -f multi-container.yaml --dry-run=clientrm multi-container.yamlExpected Result
apiVersion: v1kind: Podmetadata: name: multispec: containers: - name: app image: nginx ports: - containerPort: 80 - name: sidecar image: busyboxDrill 5: Search and Replace (Target: 1 minute)
Section titled “Drill 5: Search and Replace (Target: 1 minute)”# Create file with wrong image versioncat << 'EOF' > version-fix.yamlapiVersion: apps/v1kind: Deploymentmetadata: name: webspec: replicas: 3 selector: matchLabels: app: web template: metadata: labels: app: web spec: containers: - name: web image: nginx:1.19 - name: log image: fluentd:1.19 - name: cache image: redis:1.19EOF
# YOUR TASK: Change ALL "1.19" to "1.25" using vim search/replace# Command: :%s/1.19/1.25/g
vim version-fix.yaml
# Verify all changedgrep "1.25" version-fix.yaml # Should show 3 linesrm version-fix.yamlDrill 6: Fix Broken YAML - Syntax Errors (Target: 5 minutes)
Section titled “Drill 6: Fix Broken YAML - Syntax Errors (Target: 5 minutes)”This YAML has multiple errors. Find and fix all of them:
cat << 'EOF' > broken-syntax.yamlapiVersion: v1kind: Podmetadata: name: syntax-errors labels: app: test environment: production # missing quotes on value with special charsspec: containers: - name: app image: nginx env: - name: DATABASE_URL value: postgres://user:p@ssword@db:5432 # @ needs quoting - name: DEBUG value: true # boolean should be string ports: - containerPort: "80" # should be integer, not string resources: requests: memory: 128Mi # missing quotes won't break, but... cpu: 100 # should be 100mEOF
vim broken-syntax.yaml
# Testkubectl apply -f broken-syntax.yaml --dry-run=clientrm broken-syntax.yamlFixed Version
apiVersion: v1kind: Podmetadata: name: syntax-errors labels: app: test environment: productionspec: containers: - name: app image: nginx env: - name: DATABASE_URL value: "postgres://user:p@ssword@db:5432" - name: DEBUG value: "true" ports: - containerPort: 80 resources: requests: memory: "128Mi" cpu: "100m"Drill 7: Challenge - Nano Speed Test
Section titled “Drill 7: Challenge - Nano Speed Test”If you prefer nano, do Drill 1 using nano instead:
nano speed-test.yaml# Ctrl+O to save, Ctrl+X to exitkubectl apply -f speed-test.yaml --dry-run=clientrm speed-test.yamlCompare your time with vim. Use whichever is faster for you.
Next Module
Section titled “Next Module”Module 0.4: kubernetes.io Navigation - Finding documentation fast during the exam.