or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdconfiguration.mderrors.mdexecution.mdindex.mdinventory.mdmodule-utils.mdplaybook.mdplugins.mdtemplating.md

inventory.mddocs/

0

# Inventory Management

1

2

Ansible Core's inventory system provides comprehensive host and group management capabilities supporting static and dynamic inventory sources, host pattern matching, variable scoping, and flexible target selection for automation tasks.

3

4

## Capabilities

5

6

### Inventory Manager

7

8

Central inventory management system that coordinates multiple inventory sources, maintains host and group relationships, and provides unified access to inventory data.

9

10

```python { .api }

11

class InventoryManager:

12

"""

13

Main inventory manager coordinating multiple inventory sources.

14

15

Parameters:

16

- loader: DataLoader instance for file operations

17

- sources: List of inventory source paths or URLs

18

19

Attributes:

20

- _loader: DataLoader for file operations

21

- _sources: List of inventory sources

22

- _hosts: Dictionary of all hosts

23

- _groups: Dictionary of all groups

24

- _pattern_cache: Cache for parsed host patterns

25

"""

26

27

def __init__(self, loader, sources=None):

28

"""Initialize inventory manager with sources"""

29

30

def parse_sources(self, cache=True):

31

"""

32

Parse all inventory sources and populate host/group data.

33

34

Parameters:

35

- cache: Whether to cache parsing results

36

"""

37

38

def get_hosts(self, pattern="all", ignore_limits=False, ignore_restrictions=False):

39

"""

40

Get hosts matching the specified pattern.

41

42

Parameters:

43

- pattern: Host pattern string (default: "all")

44

- ignore_limits: Ignore limit restrictions

45

- ignore_restrictions: Ignore all restrictions

46

47

Returns:

48

list: List of Host objects matching pattern

49

"""

50

51

def list_hosts(self, pattern="all"):

52

"""

53

List hosts matching pattern.

54

55

Parameters:

56

- pattern: Host pattern string

57

58

Returns:

59

list: List of host names

60

"""

61

62

def get_groups_dict(self):

63

"""

64

Get dictionary representation of all groups.

65

66

Returns:

67

dict: Groups with their hosts and variables

68

"""

69

70

def add_group(self, group):

71

"""

72

Add group to inventory.

73

74

Parameters:

75

- group: Group name or Group object

76

"""

77

78

def add_host(self, host, group=None, port=None):

79

"""

80

Add host to inventory.

81

82

Parameters:

83

- host: Host name or Host object

84

- group: Group to add host to

85

- port: SSH port for host

86

"""

87

```

88

89

### Host Management

90

91

Individual host representation with connection parameters, variables, and group membership tracking.

92

93

```python { .api }

94

class Host:

95

"""

96

Individual host representation with variables and connection info.

97

98

Parameters:

99

- name: Host name or IP address

100

- port: SSH port (default: 22)

101

102

Attributes:

103

- name: Host identifier

104

- address: Connection address (defaults to name)

105

- port: SSH port number

106

- vars: Host-specific variables

107

- groups: List of groups containing this host

108

"""

109

110

def __init__(self, name=None, port=None):

111

"""Initialize host with name and optional port"""

112

113

def get_name(self):

114

"""

115

Get host name.

116

117

Returns:

118

str: Host name

119

"""

120

121

def set_variable(self, varname, value):

122

"""

123

Set host variable.

124

125

Parameters:

126

- varname: Variable name

127

- value: Variable value

128

"""

129

130

def get_vars(self):

131

"""

132

Get all host variables.

133

134

Returns:

135

dict: Host variables

136

"""

137

138

def get_groups(self):

139

"""

140

Get groups containing this host.

141

142

Returns:

143

list: Group objects

144

"""

145

146

def add_group(self, group):

147

"""

148

Add host to group.

149

150

Parameters:

151

- group: Group object

152

"""

153

```

154

155

### Group Management

156

157

Group representation supporting nested groups, group variables, and parent-child relationships for hierarchical inventory organization.

158

159

```python { .api }

160

class Group:

161

"""

162

Host group representation with nested group support.

163

164

Parameters:

165

- name: Group name

166

167

Attributes:

168

- name: Group identifier

169

- hosts: List of hosts in group

170

- child_groups: List of child groups

171

- parent_groups: List of parent groups

172

- vars: Group-specific variables

173

- priority: Group priority for variable precedence

174

"""

175

176

def __init__(self, name=None):

177

"""Initialize group with name"""

178

179

def add_host(self, host):

180

"""

181

Add host to group.

182

183

Parameters:

184

- host: Host object

185

"""

186

187

def remove_host(self, host):

188

"""

189

Remove host from group.

190

191

Parameters:

192

- host: Host object

193

"""

194

195

def get_hosts(self):

196

"""

197

Get all hosts in group (including from child groups).

198

199

Returns:

200

list: Host objects

201

"""

202

203

def add_child_group(self, group):

204

"""

205

Add child group.

206

207

Parameters:

208

- group: Group object

209

"""

210

211

def get_ancestors(self):

212

"""

213

Get all ancestor groups.

214

215

Returns:

216

list: Ancestor Group objects

217

"""

218

219

def set_variable(self, varname, value):

220

"""

221

Set group variable.

222

223

Parameters:

224

- varname: Variable name

225

- value: Variable value

226

"""

227

228

def get_vars(self):

229

"""

230

Get all group variables.

231

232

Returns:

233

dict: Group variables

234

"""

235

```

236

237

### Inventory Data Container

238

239

Core data structure maintaining the complete inventory state including hosts, groups, and their relationships.

240

241

```python { .api }

242

class InventoryData:

243

"""

244

Inventory data container managing hosts and groups.

245

246

Attributes:

247

- groups: Dictionary of all groups

248

- hosts: Dictionary of all hosts

249

- _groups_dict_cache: Cached groups dictionary

250

"""

251

252

def __init__(self):

253

"""Initialize empty inventory data"""

254

255

def add_host(self, host, group=None):

256

"""

257

Add host to inventory data.

258

259

Parameters:

260

- host: Host name or Host object

261

- group: Group to add host to

262

"""

263

264

def add_group(self, group):

265

"""

266

Add group to inventory data.

267

268

Parameters:

269

- group: Group name or Group object

270

"""

271

272

def get_host(self, hostname):

273

"""

274

Get host by name.

275

276

Parameters:

277

- hostname: Host name

278

279

Returns:

280

Host: Host object or None

281

"""

282

283

def get_group(self, groupname):

284

"""

285

Get group by name.

286

287

Parameters:

288

- groupname: Group name

289

290

Returns:

291

Group: Group object or None

292

"""

293

```

294

295

### Host Pattern Processing

296

297

Pattern matching and parsing utilities for flexible host selection supporting ranges, wildcards, regular expressions, and boolean operations.

298

299

```python { .api }

300

def split_host_pattern(pattern):

301

"""

302

Split host pattern into components for processing.

303

304

Parameters:

305

- pattern: Host pattern string

306

307

Returns:

308

list: Pattern components

309

"""

310

311

def detect_range(line):

312

"""

313

Detect numeric or alphabetic ranges in host patterns.

314

315

Parameters:

316

- line: Pattern line to analyze

317

318

Returns:

319

tuple: (start, end, step) if range detected, None otherwise

320

"""

321

322

def expand_hostname_range(range_spec):

323

"""

324

Expand hostname ranges into individual hostnames.

325

326

Parameters:

327

- range_spec: Range specification (e.g., "web[01:10]")

328

329

Returns:

330

list: Expanded hostnames

331

"""

332

```

333

334

## Inventory Sources

335

336

### Static Inventory

337

338

#### INI Format

339

```ini

340

[webservers]

341

web1.example.com

342

web2.example.com

343

344

[databases]

345

db1.example.com

346

db2.example.com

347

348

[webservers:vars]

349

http_port=80

350

nginx_version=1.18

351

352

[databases:vars]

353

mysql_port=3306

354

```

355

356

#### YAML Format

357

```yaml

358

all:

359

children:

360

webservers:

361

hosts:

362

web1.example.com:

363

web2.example.com:

364

vars:

365

http_port: 80

366

nginx_version: 1.18

367

databases:

368

hosts:

369

db1.example.com:

370

db2.example.com:

371

vars:

372

mysql_port: 3306

373

```

374

375

### Dynamic Inventory

376

377

Dynamic inventory plugins can generate inventory from external sources like cloud providers, CMDBs, or custom scripts.

378

379

```python

380

# Example dynamic inventory usage

381

inventory = InventoryManager(

382

loader=loader,

383

sources=['aws_ec2.yml', 'static_inventory']

384

)

385

```

386

387

## Host Patterns

388

389

### Pattern Syntax

390

391

- `all` or `*` - All hosts

392

- `group_name` - All hosts in group

393

- `host1:host2` - Multiple hosts/groups (union)

394

- `host1:!host2` - Exclude hosts/groups

395

- `host1:&group1` - Intersection of hosts and groups

396

- `web*.example.com` - Wildcard matching

397

- `~(web|db).*` - Regular expression matching

398

- `web[01:50]` - Numeric range expansion

399

- `web[a:f]` - Alphabetic range expansion

400

401

### Pattern Examples

402

403

```python

404

# Get all web servers

405

hosts = inventory.get_hosts('webservers')

406

407

# Get hosts in web or db groups

408

hosts = inventory.get_hosts('webservers:databases')

409

410

# Get web servers excluding maintenance

411

hosts = inventory.get_hosts('webservers:!maintenance')

412

413

# Get intersection of web servers and production

414

hosts = inventory.get_hosts('webservers:&production')

415

416

# Get hosts matching regex

417

hosts = inventory.get_hosts('~web[0-9]+\.prod\..*')

418

```

419

420

## Variable Precedence

421

422

Variables are resolved in order of precedence (highest to lowest):

423

424

1. Command line extra variables (`-e`)

425

2. Task variables

426

3. Block variables

427

4. Role variables

428

5. Play variables

429

6. Host facts

430

7. Host variables

431

8. Group variables (child groups override parent groups)

432

9. Default variables

433

434

## Usage Examples

435

436

### Basic Inventory Management

437

438

```python

439

from ansible.inventory.manager import InventoryManager

440

from ansible.parsing.dataloader import DataLoader

441

442

# Initialize components

443

loader = DataLoader()

444

inventory = InventoryManager(loader=loader, sources=['inventory'])

445

446

# Get hosts matching pattern

447

web_hosts = inventory.get_hosts('webservers')

448

449

# Add dynamic host

450

from ansible.inventory.host import Host

451

new_host = Host('dynamic.example.com')

452

new_host.set_variable('role', 'worker')

453

inventory.add_host(new_host, group='workers')

454

455

# List all groups

456

groups = inventory.get_groups_dict()

457

```

458

459

### Host and Group Operations

460

461

```python

462

# Create group with hosts

463

from ansible.inventory.group import Group

464

web_group = Group('webservers')

465

466

# Add hosts to group

467

host1 = Host('web1.example.com')

468

host2 = Host('web2.example.com')

469

web_group.add_host(host1)

470

web_group.add_host(host2)

471

472

# Set group variables

473

web_group.set_variable('http_port', 80)

474

web_group.set_variable('ssl_enabled', True)

475

476

# Create nested groups

477

prod_group = Group('production')

478

prod_group.add_child_group(web_group)

479

```