Skip to content

Instantly share code, notes, and snippets.

@progala
Last active January 26, 2022 10:43
Show Gist options
  • Save progala/381cc5def21b9d89bae98e1fcc14b7df to your computer and use it in GitHub Desktop.
Save progala/381cc5def21b9d89bae98e1fcc14b7df to your computer and use it in GitHub Desktop.
Go - Decoding YAML read from file
devices:
- hostname: "csr1"
platform: "cisco_iosxe"
commands:
- "show version"
- "show interfaces"
- hostname: "nxos-spine1"
platform: "cisco_nxos"
commands:
- "show version"
- "show interfaces"
- hostname: "eos-spine1"
platform: "arista_eos"
commands:
- "show version"
- "show interfaces"
package main
import (
"fmt"
"os"
"gopkg.in/yaml.v3"
)
type Device struct {
Hostname string `yaml:"hostname"`
Platform string `yaml:"platform"`
Commands []string `yaml:"commands"`
}
type Inventory struct {
Devices []Device `yaml:"devices"`
}
func main() {
in, err := os.Open("devices.yaml")
if err != nil {
panic(err)
}
defer in.Close()
d := yaml.NewDecoder(in)
var inv Inventory
err = d.Decode(&inv)
if err != nil {
panic(err)
}
for _, v := range inv.Devices {
fmt.Printf("Hostname: %v\n", v.Hostname)
fmt.Printf("Platform: %v\n", v.Platform)
fmt.Printf("Commands: %v\n", v.Commands)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment