-
-
Save petems/052404e06881e04595e4aac83098c8d3 to your computer and use it in GitHub Desktop.
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
"production" = { | |
"host" = "cool.example.com" | |
"password" = "xPYmDlsYDQKCbcaY3Xa68-SwdM-wYkHnNYn_ARiYbWRon2UNuzw6RG5DAZjO0Dmz6O-iMVIjX-hWc1ihT3WX" | |
"port" = 22 | |
"user" = "bob" | |
} |
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" | |
"io/ioutil" | |
"log" | |
"os" | |
"github.com/spf13/viper" | |
"gopkg.in/yaml.v2" | |
) | |
type Host struct { | |
Label string | |
Host string | |
Password string | |
} | |
type Hosts struct { | |
Hosts []Host | |
} | |
func main() { | |
viper.SetConfigName("ssh-cryptkpr") | |
viper.AddConfigPath(currentdir()) | |
err := viper.ReadInConfig() // Find and read the config file | |
if err != nil { // Handle errors reading the config file | |
log.Fatal(err) | |
} | |
h := Hosts{} | |
err = viper.Unmarshal(&h) | |
if err != nil { | |
log.Fatalf("unable to decode into struct, %v", err) | |
} | |
for _, v := range h.Hosts { | |
fmt.Println("Host Label: " + v.Label) | |
} | |
fmt.Println(h) | |
// Change value in map and marshal back into yaml | |
h.Hosts[0].Password = "new_password" | |
fmt.Println(h) | |
d, err := yaml.Marshal(&h) | |
if err != nil { | |
log.Fatalf("error: %v", err) | |
} | |
fmt.Println(string(d)) | |
// write to file | |
f, err := os.Create("/tmp/dat2") | |
if err != nil { | |
log.Fatal(err) | |
} | |
err = ioutil.WriteFile("changed.yaml", d, 0644) | |
if err != nil { | |
log.Fatal(err) | |
} | |
f.Close() | |
} | |
func currentdir() (cwd string) { | |
cwd, err := os.Getwd() | |
if err != nil { | |
log.Fatal(err) | |
} | |
return cwd | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment