1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
//! Core inventory data model: hosts, groups, and the container that owns them.
//!
//! Mirrors ansible-core's `inventory/data.py`, `group.py`, `host.py`. Group depth and
//! `ansible_group_priority` are tracked here because they drive variable precedence
//! (see [`crate::vars`]).
use indexmap::IndexMap;
use serde_json::{Map, Value};
use crate::sanitize::to_safe_group_name;
/// Special group always present and always the root of the group tree (depth 0).
pub const ALL: &str = "all";
/// Special group holding every host that belongs to no other group.
pub const UNGROUPED: &str = "ungrouped";
#[derive(Debug, Clone)]
pub struct Host {
pub name: String,
pub vars: Map<String, Value>,
/// Vars from adjacent `host_vars/<name>` files. Higher precedence than `vars`.
pub file_vars: Map<String, Value>,
/// Groups this host was *explicitly* added to, excluding `all`/`ungrouped`.
/// Used to decide `ungrouped` membership; ancestry is computed on demand.
pub groups: Vec<String>,
}
impl Host {
fn new(name: impl Into<String>) -> Self {
Host {
name: name.into(),
vars: Map::new(),
file_vars: Map::new(),
groups: Vec::new(),
}
}
}
#[derive(Debug, Clone)]
pub struct Group {
pub name: String,
/// Distance from `all`. `all` = 0. Drives precedence ordering.
pub depth: u32,
/// `ansible_group_priority`, default 1. Drives precedence ordering.
pub priority: i64,
pub hosts: Vec<String>,
pub children: Vec<String>,
pub parents: Vec<String>,
pub vars: Map<String, Value>,
/// Vars from adjacent `group_vars/<name>` files. Higher precedence than `vars`.
pub file_vars: Map<String, Value>,
}
impl Group {
fn new(name: impl Into<String>) -> Self {
Group {
name: name.into(),
depth: 0,
priority: 1,
hosts: Vec::new(),
children: Vec::new(),
parents: Vec::new(),
vars: Map::new(),
file_vars: Map::new(),
}
}
}
#[derive(Debug, Clone)]
pub struct InventoryData {
pub hosts: IndexMap<String, Host>,
pub groups: IndexMap<String, Group>,
}
impl Default for InventoryData {
fn default() -> Self {
Self::new()
}
}
impl InventoryData {
/// A fresh inventory containing only the special groups `all` and `ungrouped`,
/// with `ungrouped` already a child of `all`.
pub fn new() -> Self {
let mut inv = InventoryData {
hosts: IndexMap::new(),
groups: IndexMap::new(),
};
inv.groups.insert(ALL.to_string(), Group::new(ALL));
inv.add_group(UNGROUPED);
inv.add_child(ALL, UNGROUPED);
inv
}
/// Ensure a group exists (creating it as a child-less, host-less group parented to
/// nothing yet). Names are sanitized to ansible's safe-group-name form. Returns the
/// sanitized name actually used as the key.
pub fn add_group(&mut self, name: &str) -> String {
let safe = to_safe_group_name(name);
if !self.groups.contains_key(&safe) {
self.groups.insert(safe.clone(), Group::new(safe.clone()));
}
safe
}
/// Ensure a host exists. Returns nothing; use [`InventoryData::host_mut`] to mutate.
pub fn add_host(&mut self, name: &str) {
if !self.hosts.contains_key(name) {
self.hosts.insert(name.to_string(), Host::new(name));
}
}
pub fn host_mut(&mut self, name: &str) -> &mut Host {
self.hosts
.get_mut(name)
.expect("host must be added before mutation")
}
pub fn group_mut(&mut self, name: &str) -> &mut Group {
self.groups
.get_mut(name)
.expect("group must be added before mutation")
}
/// Add `host` to `group` (both must already exist). Records the membership on both
/// sides; `all`/`ungrouped` memberships are not recorded on the host's explicit list.
pub fn add_host_to_group(&mut self, host: &str, group: &str) {
let g = self.group_mut(group);
if !g.hosts.iter().any(|h| h == host) {
g.hosts.push(host.to_string());
}
if group != ALL && group != UNGROUPED {
let h = self.host_mut(host);
if !h.groups.iter().any(|x| x == group) {
h.groups.push(group.to_string());
}
}
}
/// Set a single group variable. `ansible_group_priority` is consumed into the group's
/// priority and not stored as a normal var (matching ansible's `Group.set_variable`).
pub fn set_group_var(&mut self, group: &str, key: &str, value: Value) {
if key == "ansible_group_priority" {
if let Some(p) = value.as_i64() {
self.group_mut(group).priority = p;
}
return;
}
self.group_mut(group).vars.insert(key.to_string(), value);
}
/// Set a single host variable.
pub fn set_host_var(&mut self, host: &str, key: &str, value: Value) {
self.host_mut(host).vars.insert(key.to_string(), value);
}
/// Link `child` under `parent` and update depths of `child` and its descendants.
/// Both groups must already exist (use the sanitized names).
pub fn add_child(&mut self, parent: &str, child: &str) {
if parent == child {
// ansible guards against self-membership; ignore it silently.
return;
}
{
let p = self.group_mut(parent);
if !p.children.iter().any(|c| c == child) {
p.children.push(child.to_string());
}
}
{
let c = self.group_mut(child);
if !c.parents.iter().any(|x| x == parent) {
c.parents.push(parent.to_string());
}
}
self.recalc_depth(parent, child);
}
/// Set `child.depth = max(parent.depth + 1, child.depth)` and propagate to descendants,
/// guarding against cycles. Mirrors `Group._check_children_depth`.
fn recalc_depth(&mut self, parent: &str, child: &str) {
let parent_depth = self.groups[parent].depth;
let new_depth = parent_depth + 1;
if self.groups[child].depth >= new_depth {
return;
}
self.group_mut(child).depth = new_depth;
// Propagate downward. `seen` prevents infinite loops on cyclic child graphs.
let mut seen = std::collections::HashSet::new();
let mut stack = vec![child.to_string()];
while let Some(g) = stack.pop() {
if !seen.insert(g.clone()) {
continue;
}
let depth = self.groups[&g].depth;
let children = self.groups[&g].children.clone();
for c in children {
let want = depth + 1;
if self.groups[&c].depth < want {
self.group_mut(&c).depth = want;
stack.push(c);
}
}
}
}
/// After all sources are parsed, make every group that has no explicit parent a child
/// of `all` (mirrors `reconcile_inventory`'s "groups inherit from all" rule). `all`
/// and `ungrouped` are left as-is.
pub fn reconcile_all_children(&mut self) {
let orphans: Vec<String> = self
.groups
.values()
.filter(|g| g.name != ALL && g.parents.is_empty())
.map(|g| g.name.clone())
.collect();
for g in orphans {
self.add_child(ALL, &g);
}
}
/// After all sources are parsed, place every host that belongs to no explicit group
/// into `ungrouped`. Idempotent.
pub fn reconcile_ungrouped(&mut self) {
let orphans: Vec<String> = self
.hosts
.values()
.filter(|h| h.groups.is_empty())
.map(|h| h.name.clone())
.collect();
for h in orphans {
let g = self.group_mut(UNGROUPED);
if !g.hosts.contains(&h) {
g.hosts.push(h);
}
}
}
/// All host names in `group` and every descendant (child) group, deduplicated.
/// Mirrors ansible's `Group.get_hosts()`, which is recursive.
pub fn group_all_hosts(&self, group: &str) -> Vec<String> {
let mut seen_groups = std::collections::HashSet::new();
let mut seen_hosts = std::collections::HashSet::new();
let mut result = Vec::new();
let mut stack = vec![group.to_string()];
while let Some(g) = stack.pop() {
if !seen_groups.insert(g.clone()) {
continue;
}
if let Some(grp) = self.groups.get(&g) {
for h in &grp.hosts {
if seen_hosts.insert(h.clone()) {
result.push(h.clone());
}
}
for c in &grp.children {
stack.push(c.clone());
}
}
}
result
}
/// All groups a host belongs to, transitively (direct groups + their ancestors),
/// always including `all`. Used for variable resolution.
pub fn host_groups(&self, host: &str) -> Vec<String> {
let mut seen = std::collections::HashSet::new();
let mut result = Vec::new();
let mut stack: Vec<String> = Vec::new();
// Seed with the host's direct memberships plus `all` and (if applicable) `ungrouped`.
if let Some(h) = self.hosts.get(host) {
if h.groups.is_empty() {
stack.push(UNGROUPED.to_string());
}
for g in &h.groups {
stack.push(g.clone());
}
}
stack.push(ALL.to_string());
while let Some(g) = stack.pop() {
if !seen.insert(g.clone()) {
continue;
}
result.push(g.clone());
if let Some(grp) = self.groups.get(&g) {
for p in &grp.parents {
stack.push(p.clone());
}
}
}
result
}
}