📋 Copy All yq Commands
📄 Generate yq PDF Guide
yq チートシート - YAML/JSON/XML プロセッサ
インストール
プラットフォーム コマンド Ubuntu/Debian wget https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -O /usr/local/bin/yq && chmod +x /usr/local/bin/yqUbuntu (PPA) sudo add-apt-repository ppa:rmescandon/yq && sudo apt update && sudo apt install yqmacOS (Homebrew) brew install yqmacOS (MacPorts) sudo port install yqWindows (Chocolatey) choco install yqWindows (Scoop) scoop install yqSnap snap install yqGo go install github.com/mikefarah/yq/v4@latestDocker docker run --rm -v "${PWD}":/workdir mikefarah/yqAlpine Linux apk add yqArch Linux yay -S yqVerify Installation yq --version
基本コマンド - 読み取りと表示
コマンド 説明 yq '.' file.yamlYAMLファイル全体を表示(整形出力) yq '.name' file.yaml特定のフィールド値を読み取る yq '.metadata.name' file.yamlドット記法を使用してネストされたフィールドを読み取る yq '.items[0]' file.yaml配列の最初の要素にアクセスする yq '.items[*]' file.yaml配列のすべての要素にアクセスする yq '.items[]' file.yaml配列の要素を繰り返し処理する yq '.items[].name' file.yaml配列のすべての要素から特定のフィールドを抽出する yq '.items[-1]' file.yaml配列の最後の要素にアクセスする yq '.items[1:3]' file.yaml配列のスライス(要素1と2) `cat file.yaml \ yq ‘.spec’` yq -r '.name' file.yaml生の文字列(引用符なし)を出力 `yq ‘.items \ length’ file.yaml` yq 'keys' file.yamlすべてのトップレベルのキーを一覧表示 `yq ’.[] \ keys’ file.yaml`
基本コマンド - 書き込みと更新
コマンド 説明 yq '.name = "new-value"' file.yamlフィールドを更新 (標準出力に出力) yq -i '.name = "new-value"' file.yamlフィールドをその場で更新(ファイルを変更) yq '.spec.replicas = 3' file.yaml入れ子になった値を更新 yq '.items[0].name = "updated"' file.yaml配列の要素を更新 yq '.newField = "value"' file.yaml新しいフィールドを作成 yq '.metadata.labels.env = "prod"' file.yaml入れ子フィールドを作成 yq 'del(.fieldName)' file.yamlフィールドを削除 yq 'del(.metadata.annotations)' file.yaml入れ子のフィールドを削除 yq 'del(.items[0])' file.yaml配列要素を削除 yq '.items += {"name": "new"}' file.yaml配列に追加 yq '.items = []' file.yaml配列をクリア yq '.count += 1' file.yaml数値をインクリメント yq '.total = .price * .quantity' file.yaml算術演算
高度な使用法 - フィルタリングと選択
コマンド 説明 `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[] \ select(.name \ `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`
高度な使用法 - 配列操作
コマンド 説明 `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.yaml配列を連結する `yq ‘.items \ = unique_by(.name)’ file.yaml` yq '[.items[].name]' file.yaml値を新しい配列に収集する
高度な使用法 - マージと結合
コマンド 説明 yq ea 'select(fi == 0) * select(fi == 1)' f1.yaml f2.yaml2つのファイルのディープマージ(f2がf1を上書き) yq ea '. as $item ireduce ({}; . * $item)' *.yaml複数のファイルをマージ yq ea 'select(fi == 0) *+ select(fi == 1)' f1.yaml f2.yaml配列の連結でマージする yq ea '[.]' file1.yaml file2.yamlファイルを配列に結合する yq '.config = load("config.yaml")' file.yaml外部ファイルを読み込んでマージする yq '.spec.template = load("template.yaml").spec' file.yamlファイルから特定のパスをロードする yq ea 'select(fi == 0) *d select(fi == 1)' f1.yaml f2.yaml削除を伴うディープマージ
高度な使用法 - 文字列操作
コマンド 説明 yq '.fullName = .firstName + " " + .lastName' file.yaml文字列連結 `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`
高度な使用法 - フォーマット変換
コマンド 説明 yq -o=json '.' file.yamlYAML を JSON に変換 yq -P '.' file.jsonJSONをYAMLに変換 yq -o=xml '.' file.yamlYAML を XML に変換 yq -p=xml '.' file.xmlXMLをYAMLに変換 yq -o=csv '.items[]' file.yamlYAML を CSV に変換 yq -o=props '.' file.yamlYAML を properties 形式に変換 yq -o=json -I=4 '.' file.yamlカスタムインデントを持つ JSON yq -o=yaml --yaml-output-version=1.1 '.' file.yamlYAML バージョンを指定 yq -p=csv -o=json '.' file.csvYAML 経由で CSV を JSON に変換
設定
コマンドラインオプション
# 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
式の構文
# 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
環境変数
# 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
一般的なユースケース
ユースケース1: 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
ユースケース2: 設定ファイルのマージ
# 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
ユースケース3: データの抽出と変換
# 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
ユースケース4: 複数のファイルにわたる一括更新
# 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
ユースケース5: 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
ベストプラクティス
常に最初にテストする -i:変更を加える前に、インプレースフラグなしでコマンドを実行して変更をプレビューする
yq '.spec.replicas = 5' deployment.yaml # Preview first
yq -i '.spec.replicas = 5' deployment.yaml # Then apply
バージョン管理を使用する :必要に応じて簡単に元に戻せるように、一括変更の前にファイルをコミットする
式を引用符で囲む :シェルの解釈を防ぐために、式にシングルクォートを使用する```bash
yq ‘.items[] | select(.name == “test”)’ file.yaml # Correct
yq '.' modified.yaml > /dev/null && echo "Valid YAML" || echo "Invalid YAML"
``` - ** 使用 [未完成] **
` select () ` - ** 条件付き更新に使用 [未完成] ** : すべてを更新するよりも正確
``` bash
yq '(select(.kind == "Deployment") | .spec.replicas) = 3' file.yaml
``` - ** コメントを保持 ** : yqはデフォルトでコメントを保持しますが、複雑な変換には注意が必要です
` eval-all ` - ** マルチファイル操作に使用 [未完成] ** : ファイルを個別に処理するよりも効率的
``` bash
yq ea '. as $item ireduce ({}; . * $item)' * .yaml
``` - ** 環境変数を活用 ** : 機密データをスクリプトから除外する
``` bash
export SECRET_KEY = "..."
yq '.apiKey = env(SECRET_KEY)' config.yaml
``` - ** スクリプティング用の生の出力を使用 ** : 他のコマンドにパイプする際は [未完成] フラグを使用
` -r `[未完成]
``` bash
IMAGE = $( yq -r '.spec.template.spec.containers[0].image' deployment.yaml )
``` - ** 検証のための終了コードを確認 ** : null/false結果で失敗するには [未完成] フラグを使用
` -e `[未完成]
``` bash
yq -e '.spec.replicas > 0' deployment.yaml && echo "Valid" || echo "Invalid"
```[未完成]
## トラブルシューティング
| 問題 | ソリューション |
| ------- | ---------- |
| **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"** | 式の構文を確認し、適切な引用を確実にし、演算子が正しいことを検証する |
| **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 | [未完成]
## クイックリファレンス - 一般的なパターン
[未完成]
Would you like me to clarify or complete the missing parts of the translation?``` 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