Vai al contenuto

yq Cheatsheet - Processore YAML/JSON/XML

Installazione

Piattaforma Comando
Ubuntu/Debian wget https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -O /usr/local/bin/yq && chmod +x /usr/local/bin/yq
Ubuntu (PPA) sudo add-apt-repository ppa:rmescandon/yq && sudo apt update && sudo apt install yq
macOS (Homebrew) brew install yq
macOS (MacPorts) sudo port install yq
Windows (Chocolatey) choco install yq
Windows (Scoop) scoop install yq
Snap snap install yq
Go go install github.com/mikefarah/yq/v4@latest
Docker docker run --rm -v "${PWD}":/workdir mikefarah/yq
Alpine Linux apk add yq
Arch Linux yay -S yq
Verify Installation yq --version
## Comandi Base - Lettura e Visualizzazione
Comando Descrizione
yq '.' file.yaml Visualizza l'intero file YAML (stampa formattata)
yq '.name' file.yaml Leggi un valore di campo specifico
yq '.metadata.name' file.yaml Leggere un campo annidato utilizzando la notazione a punto
yq '.items[0]' file.yaml Accedi al primo elemento di un array
yq '.items[*]' file.yaml Accedi a tutti gli elementi di un array
yq '.items[]' file.yaml Scorrere gli elementi dell'array
yq '.items[].name' file.yaml Estrai un campo specifico da tutti gli elementi dell'array
yq '.items[-1]' file.yaml Accedere all'ultimo elemento di un array
yq '.items[1:3]' file.yaml Array slice (elementi 1 e 2)
cat file.yaml \ | yq '.spec' Leggi da stdin
yq -r '.name' file.yaml Restituisci stringa grezza (senza virgolette)
yq '.items \ | length' file.yaml Ottieni la lunghezza di un array o di un oggetto
yq 'keys' file.yaml Elenca tutte le chiavi di primo livello
yq '.[] \ | keys' file.yaml Elenca le chiavi degli oggetti nidificati
## Comandi Base - Scrittura e Aggiornamento
Comando Descrizione
yq '.name = "new-value"' file.yaml Aggiornare un campo (stampa su stdout)
yq -i '.name = "new-value"' file.yaml Aggiorna campo sul posto (modifica file)
yq '.spec.replicas = 3' file.yaml Aggiorna valore nidificato
yq '.items[0].name = "updated"' file.yaml Aggiorna elemento dell'array
yq '.newField = "value"' file.yaml Crea nuovo campo
yq '.metadata.labels.env = "prod"' file.yaml Crea campo annidato
yq 'del(.fieldName)' file.yaml Elimina un campo
yq 'del(.metadata.annotations)' file.yaml Elimina campo nidificato
yq 'del(.items[0])' file.yaml Elimina elemento dell'array
yq '.items += {"name": "new"}' file.yaml Aggiungi all'array
yq '.items = []' file.yaml Cancella array
yq '.count += 1' file.yaml Incrementa valore numerico
yq '.total = .price * .quantity' file.yaml Operazioni aritmetiche
## Utilizzo Avanzato - Filtraggio e Selezione
Comando Descrizione
yq '.items[] \ | select(.kind == "Pod")' file.yaml Filtra gli elementi per condizione
yq '.items[] \ | select(.kind == "Pod" and .status == "Running")' file.yaml Condizioni multiple (AND)
yq '.items[] \ | select(.kind == "Pod" or .kind == "Service")' file.yaml Condizioni multiple (OR)
yq '.items[] \ | seleziona(.nome \ | test("^prod-"))' file.yaml Corrispondenza di pattern con regex
yq '.items[] \ | select(has("metadata"))' file.yaml Verifica se il campo esiste
yq '.items[] \ | select(.replicas > 3)' file.yaml Confronto numerico
yq '.items[] \ | select(.tags \ | contains(["prod"]))' file.yaml Verifica contenuto Array
yq '.items[] \ | select(.name != null)' file.yaml Filtra i valori nulli
yq '.[] \ | select(tag == "!!str")' file.yaml Filtra per tipo di tag YAML
## Utilizzo Avanzato - Operazioni su Array
Comando Descrizione
yq '.items \ | = sort_by(.name)' file.yaml Ordina array per campo
yq '.items \ | = sort_by(.metadata.creationTimestamp)' file.yaml Ordina per campo nidificato
yq '.items \ | = reverse' file.yaml Inverti l'ordine dell'array
yq '.tags \ | unique' file.yaml Ottieni valori di array unici
yq '.items \ | flatten' file.yaml Appiattire array nidificati
yq '.items \ | group_by(.kind)' file.yaml Raggruppa elementi dell'array
yq '.items \ | map(.name)' file.yaml Mappare l'array per estrarre i valori
yq '.items \ | map(select(.active))' file.yaml Filtra e mappa combinati
yq '.items = .items + .newItems' file.yaml Concatenare array
yq '.items \ | = unique_by(.name)' file.yaml Rimuovi duplicati per campo
yq '[.items[].name]' file.yaml Raccogli valori in un nuovo array
## Utilizzo Avanzato - Unione e Combinazione
Comando Descrizione
yq ea 'select(fi == 0) * select(fi == 1)' f1.yaml f2.yaml Unione profonda di due file (f2 sovrascrive f1)
yq ea '. as $item ireduce ({}; . * $item)' *.yaml Unisci più file
yq ea 'select(fi == 0) *+ select(fi == 1)' f1.yaml f2.yaml Unisci con concatenazione di array
yq ea '[.]' file1.yaml file2.yaml Combina file in un array
yq '.config = load("config.yaml")' file.yaml Carica e unisci file esterno
yq '.spec.template = load("template.yaml").spec' file.yaml Carica percorso specifico da file
yq ea 'select(fi == 0) *d select(fi == 1)' f1.yaml f2.yaml Merge profondo con eliminazione
## Utilizzo Avanzato - Operazioni su Stringhe
Comando Descrizione
yq '.fullName = .firstName + " " + .lastName' file.yaml Concatenazione di stringhe
yq '.name \ | = upcase' file.yaml Converti in maiuscole
yq '.name \ | = downcase' file.yaml Converti in minuscolo
yq '.name \ | = trim' file.yaml Rimuovi spazi bianchi
yq '.text \ | = sub("old", "new")' file.yaml Sostituisci la prima occorrenza
yq '.text \ | = gsub("old", "new")' file.yaml Sostituisci tutte le occorrenze
yq '.path \ | split("/")' file.yaml Dividi stringa in array
yq '.tags \ | join(", ")' file.yaml Unisci array in stringa
yq '.name \ | length' file.yaml Lunghezza della stringa
yq '.text \ | contains("substring")' file.yaml Verifica se la stringa contiene una sottostringa
## Utilizzo Avanzato - Conversione di Formato
Comando Descrizione
yq -o=json '.' file.yaml Converti YAML in JSON
yq -P '.' file.json Converti JSON in YAML
yq -o=xml '.' file.yaml Converti YAML in XML
yq -p=xml '.' file.xml Converti XML in YAML
yq -o=csv '.items[]' file.yaml Converti YAML in CSV
yq -o=props '.' file.yaml Converti YAML in formato properties
yq -o=json -I=4 '.' file.yaml JSON con rientro personalizzato
yq -o=yaml --yaml-output-version=1.1 '.' file.yaml Specificare la versione YAML
yq -p=csv -o=json '.' file.csv Converti CSV in JSON tramite YAML
## Configurazione

Opzioni della Riga di Comando

# Input/Output format options
-p, --input-format string    Input format (yaml/json/xml/csv/props)
-o, --output-format string   Output format (yaml/json/xml/csv/props)
-P, --prettyPrint           Pretty print (shorthand for -o=yaml)

# Modification options
-i, --inplace               Edit file in place
-I, --indent int            Indentation (default 2)

# Processing options
-e, --exit-status           Exit with status code based on result
-n, --null-input            Don't read input, start with null
-N, --no-colors             Disable colored output
-C, --colors                Force colored output

# Multiple file options
ea, eval-all                Evaluate all files together

Sintassi delle Espressioni

# Basic path expressions
.field                      # Access field
.nested.field              # Nested access
.[0]                       # Array index
.[]                        # Array iteration
.*                         # All fields

# Operators
=                          # Assignment
|=                         # Update assignment
+=                         # Append/increment
*                          # Multiply/merge
+                          # Add/concatenate
-                          # Subtract
//                         # Alternative operator (default value)

# Functions
select()                   # Filter
map()                      # Transform array
has()                      # Check existence
keys                       # Get keys
length                     # Get length
sort_by()                  # Sort array
group_by()                 # Group array
unique                     # Remove duplicates

Variabili di Ambiente

# Use environment variables in expressions
export APP_NAME="my-app"
yq '.name = env(APP_NAME)' file.yaml

# With default value
yq '.name = (env(NAME) // "default")' file.yaml

# String interpolation
yq '.message = "Hello " + env(USER)' file.yaml

Casi d'Uso Comuni

Caso d'Uso 1: Aggiornare le Repliche di un Deployment Kubernetes

# Single deployment
yq -i '.spec.replicas = 5' deployment.yaml

# Multiple deployments in one file
yq -i '(.spec.replicas | select(. != null)) = 5' deployments.yaml

# Conditionally update specific deployment
yq -i '(select(.metadata.name == "api-server") | .spec.replicas) = 10' deployment.yaml

# Update all deployments in multiple files
yq -i '.spec.replicas = 3' k8s/*.yaml

Caso d'Uso 2: Unire File di Configurazione

# Merge base config with environment-specific overrides
yq ea 'select(fi == 0) * select(fi == 1)' base-config.yaml prod-config.yaml > final-config.yaml

# Merge multiple environment files
yq ea '. as $item ireduce ({}; . * $item)' base.yaml dev.yaml local.yaml > merged.yaml

# Merge with array concatenation
yq ea 'select(fi == 0) *+ select(fi == 1)' config1.yaml config2.yaml > combined.yaml

Caso d'Uso 3: Estrarre e Trasformare Dati

# Extract all container images from Kubernetes manifests
yq '.spec.template.spec.containers[].image' deployment.yaml

# Get all service names and ports
yq '.items[] | select(.kind == "Service") | .metadata.name + ":" + (.spec.ports[0].port | tostring)' services.yaml

# Create summary report
yq '.items[] | {"name": .metadata.name, "kind": .kind, "namespace": .metadata.namespace}' resources.yaml -o=json

Caso d'Uso 4: Aggiornamenti in Massa su Più File

# Add label to all resources
find . -name "*.yaml" -exec yq -i '.metadata.labels.environment = "production"' {} \;

# Update image tag in all deployments
yq -i '(.spec.template.spec.containers[].image | select(. == "*:latest")) |= sub(":latest", ":v1.2.3")' k8s/**/*.yaml

# Add annotation to specific resources
yq -i 'select(.kind == "Service") | .metadata.annotations."prometheus.io/scrape" = "true"' *.yaml

Caso d'Uso 5: Configurazione Pipeline CI/CD

# Update version in multiple config files
export VERSION="2.1.0"
yq -i '.version = env(VERSION)' chart/Chart.yaml
yq -i '.image.tag = env(VERSION)' values.yaml

# Inject secrets from environment
yq -i '.database.password = env(DB_PASSWORD)' config.yaml

# Generate environment-specific configs
for env in dev staging prod; do
  yq ea 'select(fi == 0) * select(fi == 1)' base.yaml "env-${env}.yaml" > "config-${env}.yaml"
done

Migliori Pratiche

  • Testare sempre senza -iprima: Eseguire comandi senza il flag in-place per visualizzare in anteprima le modifiche prima di modificare i file

    yq '.spec.replicas = 5' deployment.yaml  # Preview first
    yq -i '.spec.replicas = 5' deployment.yaml  # Then apply
    

  • Utilizzare il controllo versione: Eseguire il commit dei file prima di modifiche in massa per poter facilmente annullare le modifiche se necessario

  • Racchiudere le espressioni tra virgolette: Utilizzare apici singoli per le espressioni per evitare l'interpretazione della shell

Note: Since some sections (3-20) were left blank in the original text, I've kept them blank in the translation as well. If you'd like me to fill those in with placeholder text or translations, please let me know.bash yq '.items[] | select(.name == "test")' file.yaml # Correct- Convalida YAML dopo le modifiche: Assicurati che le tue modifiche producano YAML valido

  yq '.' modified.yaml > /dev/null && echo "Valid YAML" || echo "Invalid YAML"
  ```- **Usa [termine mancante]**: Più preciso rispetto all'aggiornare tutto
`select()`[Testo incompleto]
```bash
  yq '(select(.kind == "Deployment") | .spec.replicas) = 3' file.yaml
  ```- **Preserva i commenti**: yq preserva i commenti di default, ma fai attenzione con trasformazioni complesse
`eval-all`- **Usa [termine mancante] per operazioni su più file**: Più efficiente rispetto all'elaborazione dei file separatamente
```bash
  yq ea '. as $item ireduce ({}; . * $item)' *.yaml
  ```- **Sfrutta le variabili d'ambiente**: Mantieni i dati sensibili fuori dagli script
```bash
  export SECRET_KEY="..."
  yq '.apiKey = env(SECRET_KEY)' config.yaml
  ```- **Usa output raw per gli script**: Usa [flag mancante] quando si invia a altri comandi
`-r`[Testo incompleto]
```bash
  IMAGE=$(yq -r '.spec.template.spec.containers[0].image' deployment.yaml)
  ```- **Controlla i codici di uscita per la convalida**: Usa [flag mancante] per fallire su risultati nulli/falsi
`-e`[Testo incompleto]
```bash
  yq -e '.spec.replicas > 0' deployment.yaml && echo "Valid" || echo "Invalid"
  ```[Testo incompleto]

## Risoluzione dei problemi

| Problema | Soluzione |
|-------|----------|
| **Error: "bad file descriptor"** | Use `-i` flag correctly or redirect output: `yq '.' file.yaml > temp && mv temp file.yaml` |
| **Changes not persisted** | Add `-i` flag for in-place editing: `yq -i '.field = "value"' file.yaml` |
| **"null" appears in output** | Field doesn't exist or is null. Use alternative operator: `yq '.field // "default"' file.yaml` |
| **Comments are removed** | Use `... comments=""` to explicitly remove, or check if using operations that don't preserve comments |
| **Array merge replaces instead of concatenates** | Use `*+` instead of `*` for merge: `yq ea 'select(fi==0) *+ select(fi==1)' f1.yaml f2.yaml` |
| **"Error: bad expression"** | Controlla la sintassi dell'espressione, assicurati che le virgolette siano corrette, verifica che gli operatori siano corretti |
| **Output has extra quotes** | Use `-r` flag for raw output: `yq -r '.name' file.yaml` |
| **Cannot process multiple files** | Use `ea` (eval-all) command: `yq ea '.' file1.yaml file2.yaml` |
| **Wrong version of yq** | Verify you have mikefarah/yq (not kislyuk/yq): `yq --version` should show github.com/mikefarah/yq |
| **Permission denied on `-i`** | Ensure write permissions: `chmod u+w file.yaml` or run with appropriate privileges |
| **Encoding issues with special characters** | Ensure UTF-8 encoding: `yq --encoding=utf-8 '.' file.yaml` |
| **Large files cause memory issues** | Process in chunks or use streaming: `yq -N '.items[]' large-file.yaml` |
| **Path not found errors** | Verify path exists: `yq 'has("path.to.field")' file.yaml` before accessing |
| **Merge conflicts with complex structures** | Use explicit merge strategies: `*d` for deep merge with deletion, `*+` for array concatenation |[Testo incompleto]
## Riferimento rapido - Pattern comuni

Would you like me to clarify or complete the missing parts?```bash
# Read value
yq '.path.to.field' file.yaml

# Update value
yq -i '.path.to.field = "new-value"' file.yaml

# Delete field
yq -i 'del(.path.to.field)' file.yaml

# Filter array
yq '.items[] | select(.name == "target")' file.yaml

# Merge files
yq ea 'select(fi==0) * select(fi==1)' base.yaml override.yaml

# Convert format
yq -o=json '.' file.yaml

# Use environment variable
yq '.field = env(VAR_NAME)' file.yaml

# Multiple operations
yq -i '.field1 = "value1" | .field2 = "value2"' file.yaml