yamleditor

module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2025 License: MIT

README

yamleditor

Kubernetes YAML 编辑工具,使用配置化规则进行批量修改。

特性

  • 通用路径语法:支持 spec.containers[name=foo].env[*] 等灵活路径表达式
  • 3种操作:replace、delete、regex_replace
  • 批量处理:递归处理目录下所有 YAML 文件
  • 安全模式:dry-run 预览变更,backup 自动备份
  • 零特殊情况:通过配置扩展,无需修改代码
  • regex_replace支持完整正则语法: 使用github.com/dlclark/regexp2实现

目录结构

yamleditor/
├── cmd/
│   └── yamleditor/
│       └── main.go              # CLI 入口
├── pkg/
│   ├── path/
│   │   ├── parser.go            # 路径解析
│   │   ├── matcher.go           # 条件匹配
│   │   └── navigator.go         # YAML 树遍历
│   ├── engine/
│   │   ├── engine.go            # 操作引擎
│   │   ├── replace.go           # 替换操作
│   │   ├── delete.go            # 删除操作
│   │   └── regex.go             # 正则操作
│   ├── rule/
│   │   ├── loader.go            # 规则加载
│   │   └── types.go             # 规则定义
│   └── processor/
│       └── processor.go         # 批量处理逻辑
├── go.mod
└── README.md

安装

go build -o /bin/yamleditor ./cmd/yamleditor

使用方法

配置文件
cp rules.example.yaml rules.yaml
单文件处理
# Dry-run 预览变更
yamleditor -c rules.yaml -i deployment.yaml --dry-run

# 输出到新文件
yamleditor -c rules.yaml -i input.yaml -o output.yaml

# 直接修改文件(带备份)
yamleditor -c rules.yaml -i deployment.yaml --backup
批量处理目录
# 批量处理(输出到新目录)
yamleditor -c rules.yaml -i ./input/ -o ./output/

# 原地批量修改(带备份)
yamleditor -c rules.yaml -i ./yamls/ --backup

配置说明

规则结构

每条规则包含以下字段:

字段 必需 类型 说明
action string 操作类型: replace/delete/regex_replace
path string YAML节点路径(见路径语法)
value * any 新值(replace与regex_replace需要)
pattern * string 正则表达式(regex_replace需要)
continue_on_not_found bool 路径未找到时不报错(默认false)

说明:

  • ✓ = 必需字段
  • * = 特定操作需要
  • 空 = 可选字段

完整示例:

rules:
  # replace操作
  - action: replace
    path: "spec.replicas"
    value: 3
    continue_on_not_found: true

  # delete操作
  - action: delete
    path: "metadata.managedFields"

  # regex_replace操作
  - action: regex_replace
    path: "containers[*].image"
    pattern: 'old.com'
    value: 'new.com'
路径语法
语法 说明 示例
field.subfield 字段访问 spec.template.metadata
field[*] 通配符(所有元素) containers[*]
field[0] 索引访问 containers[0]
field[name=value] 精确匹配 containers[name=nginx]
field[name=@pattern@] 正则匹配 env[name=@^xxx_.*$@]
操作类型
replace

替换节点(支持对象、字段、标量):

# 替换
- action: replace
  path: volumes[name=@.*old.*@].name
  value: new-volume

说明: replace 通过路径定位节点后,用 value 替换该节点。

delete

删除节点:

# 删除单个字段
- action: delete
  path: metadata.managedFields

# 使用正则删除(负向断言排除特定值)
- action: delete
  path: env[name=@^xxx_(?!(foo1|foo2)$).*@]
regex_replace

正则替换字符串内容:

- action: regex_replace
  path: containers[*].image
  pattern: 'registry.old.com'
  value: 'registry.new.com'

License

MIT

Directories

Path Synopsis
cmd
yamleditor command
pkg

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL