feat(vault): generate secrets from yaml input

This commit is contained in:
Khue Doan
2022-03-03 02:37:11 +07:00
parent e6cfe84bdc
commit 4dec742406
2 changed files with 50 additions and 26 deletions

View File

@ -50,4 +50,5 @@ require (
google.golang.org/grpc v1.41.0 // indirect google.golang.org/grpc v1.41.0 // indirect
google.golang.org/protobuf v1.26.0 // indirect google.golang.org/protobuf v1.26.0 // indirect
gopkg.in/square/go-jose.v2 v2.5.1 // indirect gopkg.in/square/go-jose.v2 v2.5.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
) )

View File

@ -14,22 +14,43 @@ package main
// ] // ]
// } // }
// TODO config syntax with yaml
// randomPasswords:
// - path: gitea/admin-password
// length: 32
// special: false
// state: present
import ( import (
"fmt"
"log" "log"
// "crypto/rand"
vault "github.com/hashicorp/vault/api" vault "github.com/hashicorp/vault/api"
"github.com/sethvargo/go-password/password" "github.com/sethvargo/go-password/password"
"gopkg.in/yaml.v2"
) )
var data = `
- path: gitea/admin
key: password
length: 32
special: true
- path: gitea/renovate
key: id
length: 32
special: false
- path: gitea/renovate
key: token
length: 32
special: false
`
type RandomPassword struct {
Path string `yaml:"path"`
Length int `yaml:"length"`
Special bool `yaml:"special"`
}
func main() { func main() {
randomPasswords := []RandomPassword{}
err := yaml.Unmarshal([]byte(data), &randomPasswords)
if err != nil {
log.Fatalf("error: %v", err)
}
config := vault.DefaultConfig() config := vault.DefaultConfig()
config.Address = "http://127.0.0.1:8200" config.Address = "http://127.0.0.1:8200"
@ -41,19 +62,20 @@ func main() {
client.SetToken("root") client.SetToken("root")
path := "secret/data/gitea/admin-password" for _, randomPassword := range randomPasswords {
path := fmt.Sprintf("/secret/data/%s", randomPassword.Path)
secret, _ := client.Logical().Read(path) secret, _ := client.Logical().Read(path)
if secret == nil { if secret == nil {
res, err := password.Generate(32, 24, 8, false, true) res, err := password.Generate(32, 3, 3, false, true)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
secretData := map[string]interface{}{ secretData := map[string]interface{}{
"data": map[string]interface{}{ "data": map[string]interface{}{
"value": res, "password": res,
}, },
} }
@ -64,6 +86,7 @@ func main() {
log.Println("Secret written successfully.") log.Println("Secret written successfully.")
} }
} else { } else {
log.Println("Secret already existed.") log.Println("Key abc in secret already existed.")
}
} }
} }