hiera

package module
v0.0.0-...-5d1613b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 1, 2026 License: BSD-3-Clause Imports: 10 Imported by: 3 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-hiera/hiera

hiera — go-hiera

Docs License Go Coverage

A pure-Go (no cgo) reimplementation of Puppet's Hiera 5 hierarchical data-lookup engine. It loads a Hiera 5 configuration (hiera.yaml), walks the configured hierarchy of data sources, and resolves a key to a typed value — honouring Hiera's merge behaviours, per-key lookup_options, dotted-key digging, and the full %{...} interpolation grammar, with interpolation-loop detection.

It is faithful to Hiera 5 semantics so it can back Puppet's lookup() function, and it is a standalone, reusable module: it has no hard dependency on any particular fact source. The caller injects a Scope (variable provider), so a facts engine such as go-facter — or the Ruby binding go-ruby-hiera that maps Ruby's Hiera API and Puppet's lookup() onto it — plugs its own facts in.

What it is — and isn't. Resolving a hierarchy of YAML/JSON data with merge and interpolation is fully deterministic and needs no Ruby interpreter, so it lives here as pure Go. The Ruby-facing Hiera/lookup() surface and the automatic-data-binding wiring stay in the consumer (go-ruby-hiera / rbgo) — this library resolves data, the host presents the Ruby API.

Features

  • hiera.yaml v5 loader — version: 5, defaults (datadir + backend function), and a hierarchy list of levels using path / paths / glob / globs / mapped_paths, with per-level datadir, backend and options.
  • Backends — yaml_data (via the Ruby-faithful, pure-Go go-ruby-yaml Psych backend) and json_data (stdlib). Register your own with RegisterDataHash — the seam eyaml/hocon backends slot into.
  • Merge behaviours — first (default), unique (deep-flatten + dedup), hash (shallow), and deep (recursive) with knockout_prefix, merge_hash_arrays and sort_merged_arrays.
  • lookup_options — per-key (and ^regex) merge selection, hash-merged across the hierarchy; overridable per call.
  • Dotted-key dig — lookup("profile.ntp.servers.0") looks up the root key, merges it, then digs into the structured result (map keys and array indices).
  • Interpolation — %{var}, %{facts.x}, %{trusted.x}, %{scope('x')}, %{lookup('x')} / %{hiera('x')}, %{alias('x')} (whole-value, type-preserving) and %{literal('%')} — resolved against the injected Scope and recursive lookups, with interpolation-loop detection.
  • Defaults — default_value (interpolated) and default_values_hash.

CGO-free, 100% test coverage (including every error branch), gofmt + go vet clean, and green across the six 64-bit Go targets (amd64, arm64, riscv64, loong64, ppc64le, s390x).

Install

go get github.com/go-hiera/hiera

Usage

package main

import (
	"fmt"
	"log"

	"github.com/go-hiera/hiera"
)

func main() {
	// The caller supplies the variable/fact scope %{...} resolves against.
	// go-ruby-hiera / go-facter implement hiera.Scope over real facts.
	scope := hiera.MapScope{
		"facts":   map[string]any{"os": map[string]any{"family": "Debian"}},
		"trusted": map[string]any{"certname": "web01.example.com"},
	}

	h, err := hiera.Load("hiera.yaml", scope)
	if err != nil {
		log.Fatal(err)
	}

	// First-found lookup.
	v, found, err := h.Lookup("ntp::servers", nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(v, found)

	// Force a merge strategy for this call.
	deep := &hiera.MergeStrategy{Kind: hiera.MergeDeep, KnockoutPrefix: "--"}
	merged, _, _ := h.Lookup("profile::settings", &hiera.Options{Merge: deep})
	fmt.Println(merged)

	// Dotted key: dig into structured data after the merge.
	port, _, _ := h.Lookup("profile.ntp.port", nil)
	fmt.Println(port)
}
The Scope seam
// Scope is the pluggable variable provider %{...} resolves against.
type Scope interface {
	Lookup(ref string) (any, bool)
}

ref is the reference used inside %{...} or as the argument to scope() — a bare name (certname) or a dotted path (facts.os.name). The bundled MapScope digs through nested map[string]any / []any values; go-facter and go-ruby-hiera supply their own implementations backed by live facts.

Tests & coverage

go test -race -coverpkg=./... -coverprofile=cover.out ./...
go tool cover -func=cover.out | tail -1   # total: 100.0%

The suite is fixture-driven: each test builds a throw-away hiera.yaml + data tree under t.TempDir() and injects a fake Scope, covering every backend, merge, interpolation and error path.

License

BSD-3-Clause — Copyright (c) 2026, the go-hiera/hiera authors.

Documentation

Overview

Package hiera is a pure-Go (CGO-free) reimplementation of Puppet's Hiera 5 hierarchical data-lookup engine.

It loads a Hiera 5 configuration (hiera.yaml), walks the configured hierarchy of data sources, and resolves a key to a typed value, honouring Hiera's merge behaviours (first / unique / hash / deep), per-key lookup_options, dotted-key digging into structured data, and the full %{...} interpolation grammar (scope / facts / trusted variables plus the scope, lookup, hiera, alias, literal functions) with interpolation-loop detection. It is faithful to Hiera 5 semantics so it can back Puppet's lookup() function.

Composition

The engine does not resolve fact/variable references itself: the caller supplies a Scope (a pluggable variable provider). This is the seam a facts engine such as go-facter, or the Ruby binding go-ruby-hiera, plugs into — %{facts.os.name}, %{trusted.certname} and %{scope('x')} are resolved against the injected Scope. The engine therefore has no hard dependency on any particular fact source.

Value model

Data files are decoded to a small, fixed set of Go types so a host can map results onto its own object graph:

Hash    -> map[string]any
Array   -> []any
String  -> string
Integer -> int64
Float   -> float64
Boolean -> bool
Null    -> nil

YAML is decoded through github.com/go-ruby-yaml/yaml (the ecosystem's Ruby-faithful, pure-Go Psych backend, matching the YAML semantics Puppet relies on); JSON through the standard library.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	Version   int
	Defaults  Defaults
	Hierarchy []HierarchyEntry
	// contains filtered or unexported fields
}

Config is a parsed Hiera 5 configuration (hiera.yaml).

func ParseConfig

func ParseConfig(data []byte, dir string) (*Config, error)

ParseConfig parses hiera.yaml bytes; dir is the directory containing it.

func (*Config) Dir

func (c *Config) Dir() string

Dir reports the directory the configuration was loaded from.

type Defaults

type Defaults struct {
	DataDir     string
	BackendKind string // "", "data_hash", "data_dig", "lookup_key"
	BackendName string
	Options     map[string]any
}

Defaults holds the config-level defaults inherited by hierarchy levels.

type Hiera

type Hiera struct {
	// contains filtered or unexported fields
}

Hiera is a configured lookup engine: a parsed configuration bound to a Scope and a set of data-source backends.

func Load

func Load(configPath string, scope Scope) (*Hiera, error)

Load reads and parses the hiera.yaml at configPath and returns an engine resolving interpolation against scope. The configuration's directory is the base for resolving relative datadirs.

func New

func New(cfg *Config, scope Scope) *Hiera

New returns a lookup engine for cfg resolving interpolation against scope. The built-in yaml_data and json_data backends are registered; register more with Hiera.RegisterDataHash. New panics if cfg or scope is nil.

func (*Hiera) Config

func (h *Hiera) Config() *Config

Config returns the engine's parsed configuration.

func (*Hiera) Lookup

func (h *Hiera) Lookup(key string, opts *Options) (Value, bool, error)

Lookup resolves key and returns its value, whether it was found, and any error. key may be dotted (e.g. "profile.ntp.servers.0") to dig into structured data after the root key is looked up and merged.

func (*Hiera) RegisterDataHash

func (h *Hiera) RegisterDataHash(name string, fn func(data []byte, path string) (map[string]any, error))

RegisterDataHash registers (or replaces) a data_hash backend under name so a hierarchy level may select it via "data_hash: name". A backend parses the raw bytes of one data file into a hash; path is supplied for error context.

type HierarchyEntry

type HierarchyEntry struct {
	Name        string
	Paths       []string // from path / paths, relative to the datadir
	Globs       []string // from glob / globs, relative to the datadir
	MappedPaths []string // exactly 3 elements: [scope_key, loop_var, template]
	DataDir     string
	BackendKind string // "", "data_hash", "data_dig", "lookup_key"
	BackendName string
	Options     map[string]any
}

HierarchyEntry is one level of the hierarchy.

type MapScope

type MapScope map[string]Value

MapScope is a Scope backed by a nested map of variables. A dotted reference digs through nested map[string]any and []any (numeric index) values, so facts such as {"os": {"name": "Debian"}} resolve for "facts.os.name" when stored under the "facts" key. A leading "::" is ignored, matching Puppet's top-scope syntax.

func (MapScope) Lookup

func (s MapScope) Lookup(ref string) (Value, bool)

Lookup implements Scope.

type MergeKind

type MergeKind int

MergeKind is a Hiera merge behaviour.

const (
	// MergeFirst returns the highest-priority value found (the default).
	MergeFirst MergeKind = iota
	// MergeUnique flattens every found array/scalar into a single
	// deduplicated array.
	MergeUnique
	// MergeHash shallow-merges every found hash, higher priority winning.
	MergeHash
	// MergeDeep recursively merges every found hash, higher priority winning.
	MergeDeep
)

type MergeStrategy

type MergeStrategy struct {
	Kind             MergeKind
	KnockoutPrefix   string // deep: a prefixed array element removes the plain one
	MergeHashArrays  bool   // deep: merge arrays element-wise instead of unioning
	SortMergedArrays bool   // unique/deep: sort merged arrays
}

MergeStrategy selects a merge behaviour and its options.

type Options

type Options struct {
	// Merge, when non-nil, overrides the merge behaviour for this call.
	Merge *MergeStrategy
	// Default supplies a default_value returned when the key is not found.
	Default Value
	// HasDefault enables Default (so a nil default value is distinguishable).
	HasDefault bool
	// DefaultValuesHash supplies per-key defaults consulted, by the looked-up
	// root key, when the key is not found and HasDefault is false.
	DefaultValuesHash map[string]any
}

Options controls a single Hiera.Lookup call. A nil *Options is equivalent to the zero value: the merge behaviour comes from lookup_options (falling back to "first") and there is no default.

type Scope

type Scope interface {
	Lookup(ref string) (Value, bool)
}

Scope is the pluggable variable provider the engine resolves interpolation against. Lookup receives the raw reference used inside %{...} or as the argument to scope() — a bare name ("certname") or a dotted path ("facts.os.name", "trusted.certname") — and returns the value and whether it is present. This is the seam a facts engine (go-facter) or the Ruby binding (go-ruby-hiera) implements to feed facts / trusted / server_facts data in.

type Value

type Value = any

Value is any value the engine handles; it is documentary — the public API uses any.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址