inventory

package module
v0.19.3 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: BSD-3-Clause Imports: 14 Imported by: ? modules, 0 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

inventory

Ansible-compatible inventory: INI/YAML parsers, groups, host/group vars, patterns.

Part of go-ansible — a pure-Go (CGO=0), functional-parity port of Ansible.

CI Go Reference License

Usage

inv, err := inventory.Load("inventory.ini") // INI or YAML, group_vars/host_vars included

hosts, err := inv.Match("webservers:&staging:!maintenance") // Ansible host-pattern syntax
vars := inv.HostVars("web1.example.com")                    // group + host var precedence applied
groups := inv.GroupsForHost("web1.example.com")              // full ancestry, not just direct membership

Merge combines a second *Inventory (e.g. a dynamic-inventory result) into an existing one.

Documentation

Overview

Package inventory parses Ansible-compatible inventories (YAML and INI), builds the group/host graph including group_vars/host_vars directories, and matches Ansible host patterns against it.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoSources = errors.New("no inventory sources found")

ErrNoSources reports a path that exists but holds no inventory source at all — a directory whose entries are all subdirectories, group_vars/host_vars, or dotfiles. It is a distinct error because a caller reporting to a user treats it like a missing file rather than like a parse failure: real names the directory but, having never reached a parser, gives no cause for it.

Functions

func IsScript added in v0.2.0

func IsScript(mode os.FileMode) bool

IsScript reports whether a file with this mode should be treated as a dynamic inventory script rather than a static INI/YAML file — real Ansible's own detection: any executable bit set on the file (not a directory), regardless of extension.

Types

type Group

type Group struct {
	Name     string
	Hosts    map[string]*Host
	Children map[string]*Group
	Parents  map[string]*Group
	Vars     map[string]any
	// contains filtered or unexported fields
}

Group is a named collection of hosts and/or child groups, plus the variables attached to the group itself.

func (*Group) ChildNames added in v0.16.0

func (g *Group) ChildNames() []string

ChildNames returns this group's child groups in the order they were added, which is document order for a parsed inventory. Use it rather than ranging over Children when the order is observable.

type Host

type Host struct {
	Name string
	Vars map[string]any
}

Host is one managed node: its name (as given in the inventory) plus the variables attached to it directly (not counting group-inherited vars — see Inventory.HostVars for the merged view).

type Inventory

type Inventory struct {
	Hosts  map[string]*Host
	Groups map[string]*Group

	// SourceDir is the ABSOLUTE directory the inventory was loaded
	// from, which real exposes to a playbook as inventory_dir. Empty
	// for an inventory built in memory, which has no directory to
	// name.
	SourceDir string
	// contains filtered or unexported fields
}

Inventory is the full host/group graph for one inventory source (a single file, or a directory merging several — see Load).

func Load

func Load(path string) (*Inventory, error)

Load reads an inventory from path, which may be:

  • a single YAML file (.yml/.yaml)
  • a single INI file (any other extension, or none)
  • a directory, in which every regular file directly inside it (except group_vars/ and host_vars/) is parsed and merged, in name order

group_vars/<name>.yml, group_vars/<name>/*.yml, host_vars/<name>.yml and host_vars/<name>/*.yml siblings of the source are then merged in, group vars before host vars, per Ansible's precedence.

func LoadWithVault added in v0.3.0

func LoadWithVault(path, vaultPassword string) (*Inventory, error)

LoadWithVault is Load with a vault password, so an inventory file or any group_vars/host_vars file it merges may be vault-encrypted — the canonical place real Ansible keeps secrets is a group_vars/*/vault.yml. An empty password behaves exactly like Load: a plaintext inventory loads fine, and an encrypted one is a clear error rather than a YAML parse failure on ciphertext.

func New

func New() *Inventory

New returns an empty inventory pre-seeded with the two groups every Ansible inventory implicitly has: "all" (every host) and "ungrouped" (hosts in no other group).

func ParseINI

func ParseINI(data []byte) (*Inventory, error)

ParseINI parses an Ansible INI-style inventory:

host1 ansible_host=192.0.2.1

[webservers]
web[01:02].example.com http_port=80

[webservers:vars]
ansible_user=deploy

[webservers:children]
edge

func ParseScript added in v0.2.0

func ParseScript(path string) (*Inventory, error)

ParseScript runs the dynamic inventory script at path — real Ansible's inventory-script contract: `path --list` prints one JSON document to stdout describing every group (either the shorthand `["host1","host2"]` array form or the full `{"hosts":[...], "vars":{...},"children":[...]}` form) plus an optional top-level "_meta" key holding `{"hostvars": {"host1": {...}, ...}}`.

func ParseYAML

func ParseYAML(data []byte) (*Inventory, error)

ParseYAML parses an Ansible YAML inventory (the format produced by `ansible-inventory --list` / documented as "YAML inventory"):

all:
  hosts:
    host1: {}
  vars:
    v: 1
  children:
    group1:
      hosts:
        host2:
          v: 2

func (*Inventory) AddHost added in v0.1.1

func (inv *Inventory) AddHost(name string, vals map[string]any, groups ...string)

AddHost adds a host to the inventory at runtime — Ansible's add_host module — with the given variables, as a member of every named group (created if new). With no groups it is still reachable by the "all" pattern (matchTerm's "all"/"*" case iterates every known host directly) even though it joins no group's direct membership. Hosts already matched by an in-progress play are unaffected; only plays matched after this call see the addition, matching real Ansible.

func (*Inventory) AddToGroup added in v0.1.1

func (inv *Inventory) AddToGroup(hostName, groupName string)

AddToGroup records an existing (or new) host as a member of group, creating the group if it doesn't exist — Ansible's group_by module.

func (*Inventory) GroupsForHost

func (inv *Inventory) GroupsForHost(hostName string) []*Group

GroupsForHost returns every group host belongs to (directly or via a parent group), "all" first, deepest/most-specific last — the order group vars are merged in.

func (*Inventory) HostIndex added in v0.12.0

func (inv *Inventory) HostIndex(name string) int

HostIndex is the position a host was first seen at, which is the order real lists and runs them in. An unknown host sorts last.

func (*Inventory) HostVars

func (inv *Inventory) HostVars(hostName string) map[string]any

HostVars returns the fully merged variables for hostName: group vars (from "all" down through parent groups to the most specific group, alphabetically among siblings) followed by the host's own vars, which win on conflict — matching Ansible's group-before-host precedence.

func (*Inventory) Match

func (inv *Inventory) Match(pattern string) ([]*Host, error)

Match resolves an Ansible host pattern ("all", a group name, a glob, a numeric/alpha range, or a colon/comma-separated combination with `!` exclusion and `&` intersection, e.g. "webservers:!web3:&datacenter1") against the inventory, and returns the matching hosts in inventory order.

func (*Inventory) MatchReport added in v0.14.0

func (inv *Inventory) MatchReport(pattern string) ([]*Host, []string, error)

MatchReport is Match, and additionally reports each TERM of the pattern that matched neither a host nor a group. Real Ansible warns about exactly those, one line per term — "Could not match supplied host pattern, ignoring: <term>" — so that a mistyped pattern is distinguishable from one that legitimately selects nothing, and a caller that reports to a user wants them.

Terms are reported WITHOUT their `!`/`&` operator and in real's own evaluation order (see orderPatterns), because that is the spelling and the order real's own warnings use: `all:!zzz` reports `zzz`, and `aaa,bbb` reports `aaa` then `bbb`. A term naming an EMPTY GROUP is not reported, nor is `all` or `*` — see matchTerm for why those are never mistyped patterns.

func (*Inventory) Merge

func (inv *Inventory) Merge(other *Inventory)

Merge folds other into inv (later sources override earlier ones on scalar var conflicts, group/host membership is unioned) — how Ansible combines multiple inventory sources.

Jump to

Keyboard shortcuts

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