Programmatically obtaining information about deployed Containerlab nodes (IPs, names) to build an inventory in Go, which is essential for scaling automation.
Write a Go program that parses the srl_2_nodes.clab.yaml file (or directly queries Containerlab if possible, but parsing YAML is more direct for this exercise) to extract the hostnames and expected management IPs of the SR Linux nodes.
// main.go
package main
import (
"fmt"
"os"
"gopkg.in/yaml.v3"
)
type Topology struct {
Name string `yaml:"name"`
Topology TopoBody `yaml:"topology"`
}
type TopoBody struct {
Nodes map[string]Node `yaml:"nodes"`
Links []Link `yaml:"links"`
}
type Node struct {
Kind string `yaml:"kind"`
Image string `yaml:"image"`
StartupConfig string `yaml:"startup-config"`
}
type Link struct {
Endpoints []string `yaml:"endpoints"`
}
func main() {
data, err := os.ReadFile("srl_2_nodes.clab.yaml")
if err != nil {
panic(err)
}
var topo Topology
if err := yaml.Unmarshal(data, &topo); err != nil {
panic(err)
}
fmt.Printf("Containerlab Lab Name: %s\n", topo.Name)
fmt.Println("Discovered SR Linux Nodes:")
for nodeName, nodeDetails := range topo.Topology.Nodes {
fmt.Printf("Node Name: %s, Kind: %s, Image: %s\n", nodeName, nodeDetails.Kind, nodeDetails.Image)
}
}- Ensure
srl_2_nodes.clab.yamlis present from Day 9. - Run
go mod init day10. - Run
go get gopkg.in/yaml.v2. - Save the code as
main.go. - Run
go run main.go.