Skip to content

Commit

Permalink
feat(vault): generate secrets from yaml input
Browse files Browse the repository at this point in the history
  • Loading branch information
khuedoan committed Mar 2, 2022
1 parent e6cfe84 commit 4dec742
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 26 deletions.
1 change: 1 addition & 0 deletions platform/vault/files/generate-secrets/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,5 @@ require (
google.golang.org/grpc v1.41.0 // indirect
google.golang.org/protobuf v1.26.0 // indirect
gopkg.in/square/go-jose.v2 v2.5.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)
75 changes: 49 additions & 26 deletions platform/vault/files/generate-secrets/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,43 @@ package main
// ]
// }

// TODO config syntax with yaml
// randomPasswords:
// - path: gitea/admin-password
// length: 32
// special: false
// state: present

import (
"fmt"
"log"
// "crypto/rand"

vault "github.com/hashicorp/vault/api"
"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() {
randomPasswords := []RandomPassword{}

err := yaml.Unmarshal([]byte(data), &randomPasswords)
if err != nil {
log.Fatalf("error: %v", err)
}
config := vault.DefaultConfig()

config.Address = "http://127.0.0.1:8200"
Expand All @@ -41,29 +62,31 @@ func main() {

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 {
res, err := password.Generate(32, 24, 8, false, true)
if err != nil {
log.Fatal(err)
}
if secret == nil {
res, err := password.Generate(32, 3, 3, false, true)
if err != nil {
log.Fatal(err)
}

secretData := map[string]interface{}{
"data": map[string]interface{}{
"value": res,
},
}
secretData := map[string]interface{}{
"data": map[string]interface{}{
"password": res,
},
}

_, err = client.Logical().Write(path, secretData)
if err != nil {
log.Fatalf("Unable to write secret: %v", err)
_, err = client.Logical().Write(path, secretData)
if err != nil {
log.Fatalf("Unable to write secret: %v", err)
} else {
log.Println("Secret written successfully.")
}
} else {
log.Println("Secret written successfully.")
log.Println("Key abc in secret already existed.")
}
} else {
log.Println("Secret already existed.")
}
}

0 comments on commit 4dec742

Please sign in to comment.