Created
September 10, 2016 04:22
-
-
Save jpweber/11a36a39ef40097b23d496bb3c76281d to your computer and use it in GitHub Desktop.
Test vault mysql secret backend
This file contains 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
/* | |
* @Author: Jim Weber | |
* @Date: 2016-09-09 23:35:28 | |
* @Last Modified by: Jim Weber | |
* @Last Modified time: 2016-09-10 00:20:32 | |
*/ | |
package main | |
import ( | |
"database/sql" | |
"flag" | |
"fmt" | |
"log" | |
"net/http" | |
"os" | |
"time" | |
vaultapi "github.com/hashicorp/vault/api" | |
_ "github.com/go-sql-driver/mysql" | |
) | |
func main() { | |
vaultHost := flag.String("vault", "", "Hostname of Vault Server") | |
dbHost := flag.String("db", "", "Hostname of DB Server") | |
creds := flag.String("creds", "", "Vault Path to Credentials") | |
// Once all flags are declared, call `flag.Parse()` | |
// to execute the command-line parsing. | |
flag.Parse() | |
// init vault client config | |
httpClient := &http.Client{} | |
clientConfig := vaultapi.Config{ | |
Address: "https://" + *vaultHost + ":8200", | |
HttpClient: httpClient, | |
MaxRetries: 3, | |
} | |
// intialize vault client | |
client, err := vaultapi.NewClient(&clientConfig) | |
if err != nil { | |
log.Println(err) | |
} | |
log.Println("Reading mysql creds from vault") | |
// don't forget by default the vault token to auth with is | |
// read from your env vars. It looks for VAULT_TOKEN | |
secret, err := client.Logical().Read(*creds) | |
if err != nil { | |
log.Println(err) | |
} | |
username := secret.Data["username"].(string) | |
password := secret.Data["password"].(string) | |
log.Println("Username:", username) | |
log.Println("Password:", password) | |
log.Println("Connecting to", *dbHost) | |
// opening a new connection for every iteration of the loop | |
// mysql will leave connections open for a user even if that user | |
// has been removed. To demo the revocation of user credentials | |
// I am opening a new connection each time. | |
for { | |
//open db connection | |
db, err := sql.Open("mysql", username+":"+password+"@tcp("+*dbHost+":3306)/") | |
if err != nil { | |
// log.Fatal(err) | |
log.Println(err) | |
} | |
defer db.Close() | |
//ping database to make sure we're good | |
err = db.Ping() | |
if err != nil { | |
fmt.Println("something is wrong trying to reach database") | |
log.Println(err) | |
os.Exit(1) | |
} | |
var result string | |
err = db.QueryRow("select User from mysql.user limit 1").Scan(&result) | |
if err != nil { | |
log.Fatal(err) | |
os.Exit(1) | |
} | |
log.Println("Results", result) | |
time.Sleep(time.Second * 5) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment