golang unmarshal yaml from a vault file

huangapple go评论86阅读模式
英文:

golang unmarshal yaml from a vault file

问题

使用以下代码,我可以从Ansible保险库文件中获取yaml,结果如下:

---
dbtype: redis
vsad: go0v

尝试解组YAML时,我只得到:

map[string]string(nil)

我的目标是解锁文件,编辑数据,重新锁定文件。

如何实现解组以编辑数据?

package main

import (
	"fmt"
	"github.com/sosedoff/ansible-vault-go"
	"gopkg.in/yaml.v2"
)

type Props struct {
	values map[string]string
}
func main() {
	str, err := vault.DecryptFile("/tmp/tmpvlt", `.NunY4hb33zWx!)`)
	if err != nil {
		panic(err)
	}
	props := Props{}
	err2 := yaml.Unmarshal([]byte(str), &props)
	if err2 != nil {
		panic(err2)
	}
	fmt.Println(str)
	fmt.Printf("%#v\n",props.values)

}
英文:

With the below code I can get the yaml from the Ansible vault file which results in:

---
dbtype: redis
vsad: go0v

When attempting to unmarshal the YAML I get only:

map[string]string(nil)

My desired goal is to unvault the file, edit the data, re-vault the file.

How do I achieve the unmarshal so as to edit the data?

package main

import (
	"fmt"
	"github.com/sosedoff/ansible-vault-go"
	"gopkg.in/yaml.v2"
)

type Props struct {
	values map[string]string
}
func main() {
	str, err := vault.DecryptFile("/tmp/tmpvlt", `.NunY4hb33zWx!)`)
	if err != nil {
		panic(err)
	}
	props := Props{}
	err2 := yaml.Unmarshal([]byte(str), &props)
	if err2 != nil {
		panic(err2)
	}
	fmt.Println(str)
	fmt.Printf("%#v\n",props.values)

}

答案1

得分: 3

你想要执行以下操作:

var props map[string]string

或者

err2 := yaml.Unmarshal([]byte(str), &props.values)

在你当前的代码中,解析器无法访问私有字段values,即使你将其重命名为Values使其变为公有字段,也不会被填充,因为你的YAML中没有名为values的顶级键。

英文:

You want to do either

var props map[string]string

or

err2 := yaml.Unmarshal([]byte(str), &props.values)

In your current code, the unmarshaler cannot access the private field values, and even if you make it public by renaming it to Values, it would not be filled because your YAML doesn't have a top-level key named values.

huangapple
  • 本文由 发表于 2021年9月30日 23:46:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/69395247.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定