# 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 optionsea, eval-all Evaluate all files together
# Use environment variables in expressionsexport APP_NAME="my-app"yq '.name = env(APP_NAME)' file.yaml# With default valueyq '.name = (env(NAME) // "default")' file.yaml# String interpolationyq '.message = "Hello " + env(USER)' file.yaml
Casos de Uso Comuns
Caso de Uso 1: Atualizar Réplicas de Implantação do Kubernetes
# Single deploymentyq -i '.spec.replicas = 5' deployment.yaml# Multiple deployments in one fileyq -i '(.spec.replicas | select(. != null)) = 5' deployments.yaml# Conditionally update specific deploymentyq -i '(select(.metadata.name == "api-server") | .spec.replicas) = 10' deployment.yaml# Update all deployments in multiple filesyq -i '.spec.replicas = 3' k8s/*.yaml
Caso de Uso 2: Mesclar Arquivos de Configuração
# Merge base config with environment-specific overridesyq ea 'select(fi == 0) * select(fi == 1)' base-config.yaml prod-config.yaml > final-config.yaml# Merge multiple environment filesyq ea '. as $item ireduce ({}; . * $item)' base.yaml dev.yaml local.yaml > merged.yaml# Merge with array concatenationyq ea 'select(fi == 0) *+ select(fi == 1)' config1.yaml config2.yaml > combined.yaml
Caso de Uso 3: Extrair e Transformar Dados
# Extract all container images from Kubernetes manifestsyq '.spec.template.spec.containers[].image' deployment.yaml# Get all service names and portsyq '.items[] | select(.kind == "Service") | .metadata.name + ":" + (.spec.ports[0].port | tostring)' services.yaml# Create summary reportyq '.items[] | {"name": .metadata.name, "kind": .kind, "namespace": .metadata.namespace}' resources.yaml -o=json
Caso de Uso 4: Atualizações em Massa em Múltiplos Arquivos
# Add label to all resourcesfind . -name "*.yaml" -exec yq -i '.metadata.labels.environment = "production"' {} \;# Update image tag in all deploymentsyq -i '(.spec.template.spec.containers[].image | select(. == "*:latest")) |= sub(":latest", ":v1.2.3")' k8s/**/*.yaml# Add annotation to specific resourcesyq -i 'select(.kind == "Service") | .metadata.annotations."prometheus.io/scrape" = "true"' *.yaml
Caso de Uso 5: Configuração de Pipeline CI/CD
# Update version in multiple config filesexport VERSION="2.1.0"yq -i '.version = env(VERSION)' chart/Chart.yamlyq -i '.image.tag = env(VERSION)' values.yaml# Inject secrets from environmentyq -i '.database.password = env(DB_PASSWORD)' config.yaml# Generate environment-specific configsfor env in dev staging prod; do yq ea 'select(fi == 0) * select(fi == 1)' base.yaml "env-${env}.yaml" > "config-${env}.yaml"done
Melhores Práticas
Sempre teste sem -iprimeiro: Execute comandos sem o sinalizador in-place para visualizar as alterações antes de modificar arquivos
yq '.spec.replicas = 5' deployment.yaml # Preview first yq -i '.spec.replicas = 5' deployment.yaml # Then apply
Use controle de versão: Faça commit dos arquivos antes de modificações em massa para poder reverter facilmente, se necessário
Coloque expressões entre aspas: Use aspas simples para expressões para evitar interpretação do shell```bash
yq ‘.items[] | select(.name == “test”)’ file.yaml # Correct
yq '.' modified.yaml > /dev/null && echo "Valid YAML" || echo "Invalid YAML" ```(Incomplete text)`select()`(Incomplete text)```bash yq '(select(.kind == "Deployment") | .spec.replicas) = 3' file.yaml ```- **Preservar comentários**: yq preserva comentários por padrão, mas tenha cuidado com transformações complexas`eval-all`(Incomplete text)```bash yq ea '. as $item ireduce ({}; . * $item)' *.yaml ```- **Aproveitar variáveis de ambiente**: Mantenha dados sensíveis fora dos scripts```bash export SECRET_KEY="..." yq '.apiKey = env(SECRET_KEY)' config.yaml ```(Incomplete text)`-r`(Incomplete text)```bash IMAGE=$(yq -r '.spec.template.spec.containers[0].image' deployment.yaml) ```(Incomplete text)`-e`(Incomplete text)```bash yq -e '.spec.replicas > 0' deployment.yaml && echo "Valid" || echo "Invalid" ```(Incomplete text)## Resolução de Problemas| Problema | Solução ||-------|----------|| **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"** | Verifique a sintaxe da expressão, garanta que as aspas estejam corretas, verifique se os operadores estão adequados || **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 |(Incomplete text)## Referência Rápida - Padrões ComunsIf you can provide the complete texts, I'll be happy to translate them fully.```bash# Read valueyq '.path.to.field' file.yaml# Update valueyq -i '.path.to.field = "new-value"' file.yaml# Delete fieldyq -i 'del(.path.to.field)' file.yaml# Filter arrayyq '.items[] | select(.name == "target")' file.yaml# Merge filesyq ea 'select(fi==0) * select(fi==1)' base.yaml override.yaml# Convert formatyq -o=json '.' file.yaml# Use environment variableyq '.field = env(VAR_NAME)' file.yaml# Multiple operationsyq -i '.field1 = "value1" | .field2 = "value2"' file.yaml
This site uses cookies for analytics and to improve your experience.
See our Privacy Policy for details.