Last active
January 26, 2022 10:43
-
-
Save progala/381cc5def21b9d89bae98e1fcc14b7df to your computer and use it in GitHub Desktop.
Go - Decoding YAML read from file
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
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" |
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" | |
"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