chezmoi Keeper 模板函数详解:在模板中安全获取 Keeper 密钥数据
【免费下载链接】chezmoiManage your dotfiles across multiple diverse machines, securely.项目地址: https://gitcode.com/gh_mirrors/ch/chezmoi
keeper、keeperDataFields与keeperFindPassword是 chezmoi 内置的三组 Keeper 模板函数,它们通过调用 Keeper 官方 Commander CLI 将密码库中的结构化数据注入点文件模板。读完本文,你将掌握这三个函数各自的适用场景、底层命令调用方式、keeper.command与keeper.args配置项的作用,以及如何配合--skip-secrets构建安全、可复现的多机点文件管理流程。
一、Keeper 函数概览
chezmoi 通过 Keeper 的 Commander CLI(命令名为keeper)把密码库能力暴露为模板函数。所有以keeper开头的函数统称为"Keeper 函数",它们的工作方式一致:在渲染模板时调用 Keeper CLI,将其标准输出解析后提供给模板使用。
从源码看,三个函数统一注册在 internal/cmd/config.go 的模板函数表中:
"keeper": c.keeperTemplateFunc, "keeperDataFields": c.keeperDataFieldsTemplateFunc, "keeperFindPassword": c.keeperFindPasswordTemplateFunc,这意味着在任意 chezmoi 模板(*.tmpl文件、chezmoi.toml.tmpl、脚本模板等)中都可以直接使用它们。Keeper 函数家族包含三个成员:
| 函数 | 参数 | 返回值 | 底层命令 |
|---|---|---|---|
keeper | uid | 解析为 JSON 的 map | keeper get --format=json <uid> |
keeperDataFields | uid | 按字段类型索引的 map | keeper get --format=json <uid> |
keeperFindPassword | query | 字符串(密码) | keeper find-password <query> |
其中query可以是记录的 UID,也可以是路径。keeper与keeperDataFields接受 UID;keeperFindPassword更灵活,UID 和路径都可以。
二、keeperuid:获取完整 JSON 结构化数据
keeper函数返回通过 Commander CLI 从 Keeper 获取的结构化数据。uid会被原样传给keeper get --format=json,输出结果按 JSON 解析后返回。
在 internal/cmd/keepertemplatefuncs.go 中的实现如下:
func (c *Config) keeperTemplateFunc(record string) map[string]any { chezmoi.SkipTemplateIf(c.skipSecrets) output := mustValue(c.keeperOutput([]string{"get", "--format=json", record})) var result map[string]any must(json.Unmarshal(output, &result)) return result }执行过程分为三步:
- 若启用了
--skip-secrets,直接跳过模板渲染; - 调用
keeper get --format=json <uid>获取 JSON 输出; - 将输出
json.Unmarshal为map[string]any返回。
因此模板中可以通过keeper "$UID"拿到记录的完整 JSON,再按 Key 逐层取值。典型用法(取自官方文档):
title = {{ (keeper "$UID").data.title }}keeper get的 JSON 顶层包含data、record_uid、type等字段,其中data下又有title、fields、custom等子结构,可逐层访问。例如获取记录的创建时间、类型等元数据:
recordType = {{ (keeper "$UID").type }}三、keeperDataFieldsuid:按字段类型索引的便捷封装
keeperDataFields是keeper的便捷变体:它同样执行keeper get --format=json <uid>,但只抽取 JSON 中.data.fields数组,并将其按字段的type重新索引为 map。这样就不必在模板里手工遍历fields数组。
实现位于 internal/cmd/keepertemplatefuncs.go:
var data struct { Data struct { Fields []struct { Type string `json:"type"` Value any `json:"value"` } `json:"fields"` } `json:"data"` } must(json.Unmarshal(output, &data)) result := make(map[string]any) for _, field := range data.Data.Fields { result[field.Type] = field.Value } return result注意字段的value在 Keeper 的 JSON 中本身是数组(如登录名、密码等字段可能有多个值),因此取值时通常需要用index取第一个元素。官方文档给出的示例:
url = {{ (keeperDataFields "$UID").url }} login = {{ index (keeperDataFields "$UID").login 0 }} password = {{ index (keeperDataFields "$UID").password 0 }}url字段直接可用,因为多数记录只有一个 URL;login、password字段是数组,必须用index ... 0取首个元素。
Keeper 记录常见的字段type有login、password、url、oneTimeCode等,均可按此方式索引。
四、keeperFindPasswordquery:直接取密码
keeperFindPassword返回keeper find-password <query>命令的输出,query可以是 UID 或路径,非常适合只想取一个密码、不想处理 JSON 结构的场景。
实现位于 internal/cmd/keepertemplatefuncs.go,与keeper的关键差异是:输出会经过bytes.TrimSpace去除首尾空白,保证模板中不会混入多余换行:
func (c *Config) keeperFindPasswordTemplateFunc(record string) string { chezmoi.SkipTemplateIf(c.skipSecrets) output := mustValue(c.keeperOutput([]string{"find-password", record})) return string(bytes.TrimSpace(output)) }用户指南中的示例展示了 UID 与路径两种查询方式:
examplePasswordFromPath = {{ keeperFindPassword "$PATH" }} examplePasswordFromUid = {{ keeperFindPassword "$UID" }}在真实点文件中,可以把密码直接渲染进需要密钥的配置文件。例如生成一个包含 API 密钥的~/.config/myapp/config:
api_key = "{{ keeperFindPassword "MyApp/API Key" }}"五、底层命令执行与结果缓存
三个函数最终都汇聚到keeperOutput(internal/cmd/keepertemplatefuncs.go),该函数是理解 Keeper 集成原理的关键:
func (c *Config) keeperOutput(args []string) ([]byte, error) { key := strings.Join(args, "\x00") if data, ok := c.Keeper.outputCache[key]; ok { return data, nil } name := c.Keeper.Command args = append(args, c.Keeper.Args...) cmd := exec.Command(name, args...) cmd.Stdin = os.Stdin cmd.Stderr = os.Stderr output, err := chezmoilog.LogCmdOutput(c.logger, cmd) ... c.Keeper.outputCache[key] = output return output, nil }几个值得注意的实现细节:
- 参数合并顺序:函数自带的参数(如
get --format=json <uid>)在前,配置的keeper.args追加在后; - 按参数缓存:以
\x00连接参数作为缓存 Key,同一个模板渲染过程中重复的 Keeper 查询只会执行一次 CLI,降低延迟与对 Keeper 服务的压力; - 标准输入/输出透传:
cmd.Stdin与cmd.Stderr直接透传,因此需要交互式解锁 Keeper 会话时(如输入主密码)可正常交互,错误信息也会原样展示; - 错误包装:CLI 失败时会通过
newCmdOutputError包装,模板渲染随之失败,避免静默使用错误数据。
六、配置项:keeper.command与keeper.args
Keeper 集成允许通过 chezmoi 配置文件定制 CLI 命令本身。默认配置定义在 internal/cmd/config.go:
Keeper: keeperConfig{ Command: "keeper", },两个配置项的完整定义(见 variables.md.yaml):
| 配置项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
keeper.command | string | keeper | Keeper CLI 命令 |
keeper.args | []string | 空 | 追加给 Keeper CLI 的额外参数 |
在~/.config/chezmoi/chezmoi.toml中为 CLI 附加配置文件的示例(官方文档原例):
[keeper] args = ["--config", "/path/to/config.json"]如果keeper命令不在PATH中,或需要指定绝对路径,可以设置command:
[keeper] command = "/usr/local/bin/keeper"在其他配置格式(YAML / JSON)中写法同理:
keeper: command: keeper args: - "--config" - "/path/to/config.json"七、安全实践:配合--skip-secrets使用
Keeper 函数与所有敏感数据函数一样,遵守 chezmoi 的--skip-secrets机制。在三个函数的实现开头都调用了chezmoi.SkipTemplateIf(c.skipSecrets);该标志在 internal/cmd/config.go 注册:
persistentFlags.BoolVar(&c.skipSecrets, "skip-secrets", c.skipSecrets, "Skip all templates containing secrets")这意味着执行chezmoi apply --skip-secrets时,任何包含 Keeper 函数的模板会被整体跳过,不会触发对 Keeper CLI 的调用,也不会在日志或输出中暴露密码。这在你只想知道"哪些文件会变化"(配合--dry-run、--diff)或在不具备 Keeper 会话的环境(如 CI)中预览变更时非常有用。
使用时还需注意前置条件:需要先按 Commander CLI 文档创建持久化登录会话(persistent login session),否则首次调用会触发交互式登录。
八、实操示例:一份完整的.tmpl用法
综合以上内容,一个典型的 Keeper 驱动的点文件模板(如dot_config/myapp/config.tmpl)可以是:
# 由 chezmoi 模板生成,不要直接编辑 app_title = {{ (keeper "ABCD-EFGH-IJKL-MNOP").data.title }} username = {{ index (keeperDataFields "ABCD-EFGH-IJKL-MNOP").login 0 }} password = {{ keeperFindPassword "MyApp/API Key" }} endpoint = {{ (keeperDataFields "ABCD-EFGH-IJKL-MNOP").url }}对应使用流程:
- 在 Keeper 中创建记录,记下其 UID(或使用路径);
- 按 Commander CLI 文档建立持久化登录会话;
- 编写包含上述模板函数的
.tmpl源文件并chezmoi add; - 执行
chezmoi apply完成渲染落盘; - 需要预览而不触碰密钥时,使用
chezmoi diff --skip-secrets。
相关文档与源码位置:
- Keeper 函数参考:keeper-functions/index.md
keeper函数:keeper-functions/keeper.mdkeeperDataFields函数:keeper-functions/keeperDataFields.mdkeeperFindPassword函数:keeper-functions/keeperFindPassword.md- 用户指南:password-managers/keeper.md
- 源码实现:internal/cmd/keepertemplatefuncs.go
【免费下载链接】chezmoiManage your dotfiles across multiple diverse machines, securely.项目地址: https://gitcode.com/gh_mirrors/ch/chezmoi
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考