Last active
September 30, 2022 15:11
-
-
Save jmdelafe/ddb3baebf518fc0cf148f93e7cb14669 to your computer and use it in GitHub Desktop.
parsing-yaml-go
This file contains 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" | |
"strings" | |
"gopkg.in/yaml.v2" | |
) | |
var data = ` | |
--- | |
devices: | |
- host: bdr-101-1.net.fr5-fra.github.net | |
primary_address: 10.232.0.1/32 | |
type: border | |
model: Juniper MX10008 | |
interfaces: | |
et-0/2/2: | |
units: | |
'0': 10.16.17.157/31 | |
metadata: | |
circuit_ids: [] | |
tags: | |
- env:production | |
- region:fra | |
- site:fr5-fra | |
- host: bdr-102-2.mgmt.dc2-iad.github.net | |
primary_address: 10.225.0.2/32 | |
type: border | |
model: Juniper MX960 | |
interfaces: | |
et-7/0/2: | |
units: {} | |
description: Member of ae0 | |
tags: | |
- env:production | |
- region:sea | |
- site:se3-sea | |
` | |
type DeviceInterface struct { | |
Metadata map[string]string `yaml:"metadata"` | |
} | |
type DeviceMetadata struct { | |
FQDN string `yaml:"host"` | |
PrimaryAddress string `yaml:"primary_address"` | |
DeviceType string `yaml:"type"` | |
DeviceModel string `yaml:"model"` | |
DeviceTags []string `yaml:"tags"` | |
Interfaces map[string]DeviceInterface `yaml:"interfaces"` | |
} | |
type DeviceYAMLBase struct { | |
Devices []DeviceMetadata `yaml:"devices"` | |
} | |
type DeviceIPMetadataMapper struct { | |
DeviceMetadata map[string]DeviceMetadata | |
} | |
func NewDeviceIPMetadataMapper(dataname string) (*DeviceIPMetadataMapper, error) { | |
config := DeviceYAMLBase{} | |
err := yaml.Unmarshal([]byte(dataname), &config) | |
if err != nil { | |
return nil, err | |
} | |
mapper := &DeviceIPMetadataMapper{ | |
DeviceMetadata: make(map[string]DeviceMetadata), | |
} | |
for _, device := range config.Devices { | |
address := device.PrimaryAddress | |
parts := strings.SplitN(address, "/", 2) // remove any subnet size suffix | |
justIP := parts[0] | |
mapper.DeviceMetadata[justIP] = device | |
} | |
return mapper, nil | |
} | |
func main() { | |
metadataMapper, err := NewDeviceIPMetadataMapper(data) | |
if err != nil { | |
fmt.Printf("Failed to create load metadata map for juniper telemetry. error: --%s--", err) | |
} else { | |
fmt.Printf("--- m dump:\n%s\n\n", metadataMapper) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment