Skip to content

Instantly share code, notes, and snippets.

@petems
Created October 4, 2020 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petems/052404e06881e04595e4aac83098c8d3 to your computer and use it in GitHub Desktop.
Save petems/052404e06881e04595e4aac83098c8d3 to your computer and use it in GitHub Desktop.
"production" = {
"host" = "cool.example.com"
"password" = "xPYmDlsYDQKCbcaY3Xa68-SwdM-wYkHnNYn_ARiYbWRon2UNuzw6RG5DAZjO0Dmz6O-iMVIjX-hWc1ihT3WX"
"port" = 22
"user" = "bob"
}
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