Salta ai contenuti

yq Cheatsheet - Processore YAML/JSON/XML

yq Cheatsheet - Processore YAML/JSON/XML

Installazione

PiattaformaComando
Ubuntu/Debianwget 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
Snapsnap install yq
Gogo install github.com/mikefarah/yq/v4@latest
Dockerdocker run --rm -v "${PWD}":/workdir mikefarah/yq
Alpine Linuxapk add yq
Arch Linuxyay -S yq
Verify Installationyq --version

Comandi Base - Lettura e Visualizzazione

ComandoDescrizione
yq '.' file.yamlVisualizza l’intero file YAML (stampa formattata)
yq '.name' file.yamlLeggi un valore di campo specifico
yq '.metadata.name' file.yamlLeggere un campo annidato utilizzando la notazione a punto
yq '.items[0]' file.yamlAccedi al primo elemento di un array
yq '.items[*]' file.yamlAccedi a tutti gli elementi di un array
yq '.items[]' file.yamlScorrere gli elementi dell’array
yq '.items[].name' file.yamlEstrai un campo specifico da tutti gli elementi dell’array
yq '.items[-1]' file.yamlAccedere all’ultimo elemento di un array
yq '.items[1:3]' file.yamlArray slice (elementi 1 e 2)
`cat file.yaml \yq ‘.spec’`
yq -r '.name' file.yamlRestituisci stringa grezza (senza virgolette)
`yq ‘.items \length’ file.yaml`
yq 'keys' file.yamlElenca tutte le chiavi di primo livello
`yq ’.[] \keys’ file.yaml`

Comandi Base - Scrittura e Aggiornamento

ComandoDescrizione
yq '.name = "new-value"' file.yamlAggiornare un campo (stampa su stdout)
yq -i '.name = "new-value"' file.yamlAggiorna campo sul posto (modifica file)
yq '.spec.replicas = 3' file.yamlAggiorna valore nidificato
yq '.items[0].name = "updated"' file.yamlAggiorna elemento dell’array
yq '.newField = "value"' file.yamlCrea nuovo campo
yq '.metadata.labels.env = "prod"' file.yamlCrea campo annidato
yq 'del(.fieldName)' file.yamlElimina un campo
yq 'del(.metadata.annotations)' file.yamlElimina campo nidificato
yq 'del(.items[0])' file.yamlElimina elemento dell’array
yq '.items += {"name": "new"}' file.yamlAggiungi all’array
yq '.items = []' file.yamlCancella array
yq '.count += 1' file.yamlIncrementa valore numerico
yq '.total = .price * .quantity' file.yamlOperazioni aritmetiche

Utilizzo Avanzato - Filtraggio e Selezione

ComandoDescrizione
`yq ‘.items[] \select(.kind == “Pod”)’ file.yaml`
`yq ‘.items[] \select(.kind == “Pod” and .status == “Running”)’ file.yaml`
`yq ‘.items[] \select(.kind == “Pod” or .kind == “Service”)’ file.yaml`
`yq ‘.items[] \seleziona(.nome \
`yq ‘.items[] \select(has(“metadata”))’ file.yaml`
`yq ‘.items[] \select(.replicas > 3)’ file.yaml`
`yq ‘.items[] \select(.tags \
`yq ‘.items[] \select(.name != null)’ file.yaml`
`yq ’.[] \select(tag == “!!str”)’ file.yaml`

Utilizzo Avanzato - Operazioni su Array

ComandoDescrizione
`yq ‘.items \= sort_by(.name)’ file.yaml`
`yq ‘.items \= sort_by(.metadata.creationTimestamp)’ file.yaml`
`yq ‘.items \= reverse’ file.yaml`
`yq ‘.tags \unique’ file.yaml`
`yq ‘.items \flatten’ file.yaml`
`yq ‘.items \group_by(.kind)’ file.yaml`
`yq ‘.items \map(.name)’ file.yaml`
`yq ‘.items \map(select(.active))’ file.yaml`
yq '.items = .items + .newItems' file.yamlConcatenare array
`yq ‘.items \= unique_by(.name)’ file.yaml`
yq '[.items[].name]' file.yamlRaccogli valori in un nuovo array

Utilizzo Avanzato - Unione e Combinazione

ComandoDescrizione
yq ea 'select(fi == 0) * select(fi == 1)' f1.yaml f2.yamlUnione profonda di due file (f2 sovrascrive f1)
yq ea '. as $item ireduce ({}; . * $item)' *.yamlUnisci più file
yq ea 'select(fi == 0) *+ select(fi == 1)' f1.yaml f2.yamlUnisci con concatenazione di array
yq ea '[.]' file1.yaml file2.yamlCombina file in un array
yq '.config = load("config.yaml")' file.yamlCarica e unisci file esterno
yq '.spec.template = load("template.yaml").spec' file.yamlCarica percorso specifico da file
yq ea 'select(fi == 0) *d select(fi == 1)' f1.yaml f2.yamlMerge profondo con eliminazione

Utilizzo Avanzato - Operazioni su Stringhe

ComandoDescrizione
yq '.fullName = .firstName + " " + .lastName' file.yamlConcatenazione di stringhe
`yq ‘.name \= upcase’ file.yaml`
`yq ‘.name \= downcase’ file.yaml`
`yq ‘.name \= trim’ file.yaml`
`yq ‘.text \= sub(“old”, “new”)’ file.yaml`
`yq ‘.text \= gsub(“old”, “new”)’ file.yaml`
`yq ‘.path \split(”/”)’ file.yaml`
`yq ‘.tags \join(”, ”)’ file.yaml`
`yq ‘.name \length’ file.yaml`
`yq ‘.text \contains(“substring”)’ file.yaml`

Utilizzo Avanzato - Conversione di Formato

ComandoDescrizione
yq -o=json '.' file.yamlConverti YAML in JSON
yq -P '.' file.jsonConverti JSON in YAML
yq -o=xml '.' file.yamlConverti YAML in XML
yq -p=xml '.' file.xmlConverti XML in YAML
yq -o=csv '.items[]' file.yamlConverti YAML in CSV
yq -o=props '.' file.yamlConverti YAML in formato properties
yq -o=json -I=4 '.' file.yamlJSON con rientro personalizzato
yq -o=yaml --yaml-output-version=1.1 '.' file.yamlSpecificare la versione YAML
yq -p=csv -o=json '.' file.csvConverti 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

```bash
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