go-ini: Use custom seperators

Achtung! Dieser Artikel ist älter als ein Jahr. Der Inhalt ist möglicherweise nicht mehr aktuell!

Go-ini is a package for parsing section based config files. For example a Grafana.ini file like this one (🖇️ 🔐) . I wanted to use it for parsing an ansible inventory file. But I got greeted with an error message:

key-value delimiter not found: dns.veloc1ty.lan

The first lines of my inventory file are:

[dns-server]
dns.veloc1ty.lan

[archlinux]

The problem is that go-ini expects the = delimiter, because normally you would parse key value pairs in each section. But an ansible inventory file doesn’t use a key value structure. The seperators there are whitespaces.

In one of the issues I found the solution (🖇️ 🔐) . This feature is at the moment undocumented. For parsing ansible inventories I use the following code:

cfg, err := ini.LoadSources(ini.LoadOptions{
        KeyValueDelimiters: " \n",
}, "/path/to/inventory")

With this code I was able to parse an ansible inventory. Now you can list every host in a group (don’t forget to import the strings package):

for _, currentSection := range cfg.Sections() {
    fmt.Printf("Group \"%s\" contains the following hosts: %s\n",
        currentSection.Name(), strings.Join(currentSection.KeyStrings(), ","))
}

Du hast einen Kommentar, einen Wunsch oder eine Verbesserung? Schreib mir doch eine E-Mail! Die Infos dazu stehen hier.

🖇️ = Link zu anderer Webseite
🔐 = Webseite nutzt HTTPS (verschlüsselter Transportweg)
Zurück