Last active
August 24, 2018 14:47
-
-
Save richardsonlima/649a5878e5862fb16c078afec26296bf to your computer and use it in GitHub Desktop.
Vault Client Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"time" | |
"log" | |
"net/http" | |
"os" | |
"flag" | |
"fmt" | |
"text/tabwriter" | |
vault "github.com/hashicorp/vault/api" | |
) | |
func main() { | |
vaultServer := os.Getenv("VAULT_ADDR") | |
vaultToken := os.Getenv("VAULT_TOKEN") | |
entry := flag.String("read", "", "Entry to read") | |
field := flag.String("field", "", "Field to return") | |
flag.Parse() | |
// Http Request | |
client := &http.Client{ | |
Timeout: time.Second * 10, | |
} | |
req, _ := http.NewRequest("GET", vaultServer + "/v1/" + *entry, nil) | |
req.Header.Set("X-Vault-Token", vaultToken) | |
resp, err := client.Do(req) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer resp.Body.Close() | |
secret, err := vault.ParseSecret(resp.Body) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// Printing | |
w := new(tabwriter.Writer) | |
w.Init(os.Stdout, 5, 0, 2, ' ', 0) | |
fmt.Fprintf(w, "Key\tValue\n") | |
fmt.Fprintf(w, "lease_id\t%s\n", secret.LeaseID) | |
fmt.Fprintf(w, "lease_duration\t%d\n", secret.LeaseDuration) | |
for key, value := range secret.Data { | |
fmt.Fprintf(w, "%s\t%v\n", key, value) | |
} | |
fmt.Fprintln(w) | |
w.Flush() | |
if *field != "" { | |
log.Println(secret.Data[*field]) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
_ "github.com/hashicorp/consul/connect" | |
"github.com/hashicorp/vault/api" | |
) | |
func main() { | |
client, err := api.NewClient(&api.Config{ | |
Address: "http://127.0.0.1:8200", // vault endpoint address and port | |
}) | |
token := "" // inset vault token here | |
client.SetToken(token) | |
secretData := map[string]interface{}{ | |
"govalue": "goworld", | |
"gofoo": "gobar", | |
"age": "-1", | |
} | |
secretKey := "secret/goanything" | |
secretValues, err1 := client.Logical().Read(secretKey) | |
if err != nil { | |
fmt.Println(err1) | |
} | |
fmt.Println("secret %s -> %v", secretKey, secretValues) | |
_, err = client.Logical().Write(secretKey, secretData) | |
if err != nil { | |
fmt.Println(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment