YAML Prettify
Format and beautify YAML files with proper indentation
YAML Prettify
Format and beautify YAML files with proper indentation
Sample YAML Files
💡 YAML Formatting Tips
- • Indentation: YAML uses spaces for indentation, never tabs
- • 2 vs 4 spaces: 2 spaces is more common (Kubernetes), 4 spaces for some CI/CD
- • Arrays: Use consistent style - either block format with dashes or flow format
- • Comments: Use # for comments, they help document complex configurations
- • Always validate YAML syntax before deploying to production
About YAML File Formatting
YAML (YAML Ain't Markup Language) formatting transforms poorly structured YAML files into well-organized, human-readable configuration files with proper indentation and structure. Essential for DevOps, configuration management, and data serialization tasks.
- Proper indentation and structure alignment
- Comment preservation and formatting
- Array and object organization
- YAML syntax validation and error detection
- Multi-document support and separation
YAML Formatting Features
Structure Enhancement
- Consistent indentation levels (2 or 4 spaces)
- Proper key-value pair alignment
- Array and list formatting
- Nested object organization
- Multi-line string handling
Style Options
- Configurable indentation width
- Array style (block or flow)
- Quote handling preferences
- Line length optimization
- Comment alignment and spacing
Advertisement
Frequently Asked Questions
Does YAML formatting change file functionality?
No! YAML formatting only changes whitespace and indentation while preserving the exact data structure. The parsed result remains identical, ensuring your configurations work exactly the same.
Why is YAML indentation so important?
YAML uses indentation to define structure and hierarchy. Incorrect indentation can completely change the meaning or cause parsing errors. Proper formatting ensures correct interpretation.
Should I use 2 or 4 spaces for indentation?
Both are valid, but 2 spaces is more common in YAML. Choose based on your team's standards or the conventions of your specific use case (Kubernetes uses 2, some CI/CD tools prefer 4).
How do I handle multi-line strings in YAML?
Use literal (|) for preserving line breaks or folded (>) for wrapping lines. The formatter preserves these indicators and properly indents the content while maintaining readability.
YAML Formatting Examples
Before Formatting (Messy):
name: myapp
version: 1.0.0
database:
host: localhost
port: 5432
username: admin
services:
- name: web
port: 80
replicas: 3
- name: api
port: 8080
replicas: 2
config:
debug: true
timeout: 30
features: [auth, logging, metrics]
After Formatting (Clean):
name: myapp
version: 1.0.0
database:
host: localhost
port: 5432
username: admin
services:
- name: web
port: 80
replicas: 3
- name: api
port: 8080
replicas: 2
config:
debug: true
timeout: 30
features:
- auth
- logging
- metrics
Sponsored Content
YAML Formatting Styles
Kubernetes Style (2-space):
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.20
ports:
- containerPort: 80
CI/CD Configuration (4-space):
name: CI Pipeline
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: '16'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
Advanced YAML Formatting
Multi-line Strings and Comments:
# Application configuration
app:
name: MyApplication
version: "2.1.0"
# Database connection settings
database:
host: localhost
port: 5432
credentials: |
username: app_user
password: secure_password_123
ssl_mode: require
# Multi-line description
description: >
This is a long description that spans
multiple lines but will be folded into
a single line when parsed.
# Script content preserved with literal block
startup_script: |
#!/bin/bash
echo "Starting application..."
./start.sh --verbose
echo "Application started successfully"
# Environment-specific overrides
environments:
development:
debug: true
log_level: debug
production:
debug: false
log_level: error
Docker Compose Format:
version: '3.8'
services:
web:
build:
context: .
dockerfile: Dockerfile
ports:
- "80:80"
environment:
- NODE_ENV=production
- DATABASE_URL=postgresql://user:pass@db:5432/myapp
depends_on:
- db
- redis
volumes:
- ./app:/usr/src/app
- /usr/src/app/node_modules
networks:
- app-network
db:
image: postgres:13
environment:
POSTGRES_DB: myapp
POSTGRES_USER: user
POSTGRES_PASSWORD: password
volumes:
- postgres_data:/var/lib/postgresql/data
networks:
- app-network
redis:
image: redis:6-alpine
networks:
- app-network
volumes:
postgres_data:
networks:
app-network:
driver: bridge
YAML Formatting Best Practices
- Consistent Indentation: Always use spaces, never tabs. Stick to 2 or 4 spaces consistently
- Meaningful Comments: Add comments to explain complex configurations and sections
- Quote When Needed: Quote strings with special characters, numbers as strings, or when ambiguous
- Logical Grouping: Group related configuration items together with blank lines
- Array Style Consistency: Choose block or flow style for arrays and use consistently
- Key Ordering: Order keys logically (required first, optional after) for better readability
- Line Length: Keep lines under 120 characters for better code review experience
Programming Integration
JavaScript YAML Formatting:
// Using js-yaml library
const yaml = require('js-yaml');
function formatYAML(yamlString, options = {}) {
try {
// Parse YAML
const data = yaml.load(yamlString);
// Format with options
const formatted = yaml.dump(data, {
indent: options.indent || 2,
lineWidth: options.lineWidth || 120,
noRefs: true,
sortKeys: options.sortKeys || false,
quotingType: options.quotingType || '"',
forceQuotes: options.forceQuotes || false
});
return formatted;
} catch (error) {
throw new Error('Invalid YAML: ' + error.message);
}
}
// Usage example
const messyYAML = `
name:myapp
database:
host:localhost
port:5432
features: [auth,logging]`;
const formatted = formatYAML(messyYAML, {
indent: 2,
sortKeys: false
});
console.log(formatted);
/*
name: myapp
database:
host: localhost
port: 5432
features:
- auth
- logging
*/
Python YAML Formatting:
import yaml
from io import StringIO
def format_yaml(yaml_string, indent=2, sort_keys=False):
"""Format YAML string with proper indentation"""
try:
# Parse YAML
data = yaml.safe_load(yaml_string)
# Format with custom options
output = StringIO()
yaml.dump(data,
output,
default_flow_style=False,
indent=indent,
sort_keys=sort_keys,
allow_unicode=True,
width=120)
return output.getvalue()
except yaml.YAMLError as e:
raise ValueError(f"Invalid YAML: {e}")
def format_yaml_file(input_file, output_file, indent=2):
"""Format YAML file and save to new file"""
with open(input_file, 'r', encoding='utf-8') as f:
yaml_content = f.read()
formatted = format_yaml(yaml_content, indent)
with open(output_file, 'w', encoding='utf-8') as f:
f.write(formatted)
print(f"Formatted YAML saved to {output_file}")
# Usage example
yaml_str = '''
name:myapp
database:
host:localhost
port:5432
features: [auth,logging]
'''
formatted = format_yaml(yaml_str, indent=2)
print(formatted)
YAML Formatting Applications
- Kubernetes manifests
- Docker Compose files
- Ansible playbooks
- Helm charts
- GitHub Actions
- GitLab CI
- Azure DevOps
- Jenkins pipelines
- Application configs
- API specifications (OpenAPI)
- Static site generators
- Documentation sites
- Data serialization
- Configuration templates
- Localization files
- Test data fixtures
Common Use Cases
- Kubernetes deployment configuration
- CI/CD pipeline definition files
- Docker Compose service definitions
- Ansible automation playbooks
- Application configuration management
- API documentation (OpenAPI/Swagger)
- Static site generator configs
- Infrastructure as Code templates
Advertisement
