github.com/nxadm/ctwrapper@v0.5.3-0.20200107113753-fb73fb7c1f50/vault.go (about) 1 package main 2 3 import ( 4 "errors" 5 "github.com/hashicorp/vault/api" 6 "strings" 7 ) 8 9 func retrieveVaultSecret(path string) (string, error) { 10 11 // Separate vaultPath and key 12 split := strings.SplitAfter(path, "/") 13 backendAndPath := strings.Join(split[0:len(split)-1], "") 14 key := split[len(split)-1] 15 16 /* Retrieve VAULT_ADDR, VAULT_TOKEN and other VAULT_* env variables */ 17 vaultConfig := api.DefaultConfig() 18 if err := vaultConfig.ReadEnvironment(); err != nil { 19 return "", err 20 } 21 22 /* Retrieve the secret */ 23 client, err := api.NewClient(vaultConfig) 24 if err != nil { 25 return "", err 26 } 27 secretsRaw, err := client.Logical().Read(backendAndPath) 28 if err != nil { 29 return "", err 30 } 31 if secretsRaw == nil { 32 return "", errors.New("can not find the requested secret") 33 } 34 35 var secret string 36 for k, v := range secretsRaw.Data { 37 if k == key { 38 secret = v.(string) 39 break 40 } 41 } 42 43 return secret, nil 44 }