0
# Configuration and Runner Classes
1
2
Core classes for advanced use cases requiring fine-grained control over execution parameters, event handling, and process management. These classes provide the foundation for all ansible-runner operations and enable custom integration patterns.
3
4
## Capabilities
5
6
### Runner Class
7
8
The main execution class that handles Ansible operations, event processing, and result management.
9
10
```python { .api }
11
class Runner:
12
def __init__(
13
self,
14
config,
15
cancel_callback: callable = None,
16
remove_partials: bool = True,
17
event_handler: callable = None,
18
artifacts_handler: callable = None,
19
finished_callback: callable = None,
20
status_handler: callable = None
21
)
22
```
23
24
Properties:
25
- **config**: Configuration object (RunnerConfig, CommandConfig, etc.)
26
- **status** (str): Current execution status ('unstarted', 'running', 'successful', 'failed', 'error', 'canceled')
27
- **rc** (int): Return code from execution
28
- **canceled** (bool): Whether execution was canceled
29
- **timed_out** (bool): Whether execution timed out
30
- **errored** (bool): Whether execution encountered an error
31
- **events**: Iterator over execution events
32
- **stdout**: Iterator over stdout output
33
34
Methods:
35
```python { .api }
36
def run(self) -> str:
37
"""Execute the configured operation and return final status"""
38
39
def cancel(self) -> None:
40
"""Cancel the running operation"""
41
42
def event_callback(self, event_data: dict) -> None:
43
"""Handle individual event data (internal use)"""
44
```
45
46
Usage example:
47
48
```python
49
import ansible_runner
50
from ansible_runner.config.runner import RunnerConfig
51
52
# Create configuration
53
config = RunnerConfig(
54
private_data_dir='/tmp/demo',
55
playbook='site.yml',
56
inventory='hosts'
57
)
58
59
# Create runner instance
60
runner = Runner(config)
61
62
# Execute
63
status = runner.run()
64
65
print(f"Execution completed with status: {status}")
66
print(f"Return code: {runner.rc}")
67
68
# Process events
69
for event in runner.events:
70
if event['event'] == 'playbook_on_task_start':
71
print(f"Starting task: {event['event_data']['task']}")
72
```
73
74
### RunnerConfig Class
75
76
Configuration class for playbook execution with comprehensive parameter support.
77
78
```python { .api }
79
class RunnerConfig:
80
def __init__(
81
self,
82
private_data_dir: str = None,
83
playbook: str = None,
84
inventory: str = None,
85
roles_path: str = None,
86
verbosity: int = None,
87
quiet: bool = False,
88
artifact_dir: str = None,
89
project_dir: str = None,
90
ident: str = None,
91
rotate_artifacts: int = 0,
92
json_mode: bool = False,
93
check: bool = False,
94
tags: str = None,
95
skip_tags: str = None,
96
limit: str = None,
97
module_path: str = None,
98
forks: int = None,
99
vault_ids: list = None,
100
vault_password_file: str = None,
101
extravars: dict = None,
102
suppress_ansible_output: bool = False,
103
ssh_key: str = None,
104
process_isolation: bool = False,
105
process_isolation_executable: str = None,
106
process_isolation_path: str = None,
107
process_isolation_hide_paths: list = None,
108
process_isolation_show_paths: list = None,
109
process_isolation_ro_paths: list = None,
110
container_image: str = None,
111
container_volume_mounts: list = None,
112
container_options: list = None,
113
directory_isolation_base_path: str = None,
114
envvars: dict = None,
115
passwords: dict = None,
116
timeout: int = None,
117
job_timeout: int = None,
118
idle_timeout: int = None,
119
pexpect_timeout: int = None,
120
pexpect_use_poll: bool = True,
121
runner_mode: str = 'pexpect',
122
host_cwd: str = None,
123
fact_cache: str = None,
124
fact_cache_type: str = None,
125
cmdline: str = None,
126
start_at_task: str = None,
127
step: bool = False
128
)
129
```
130
131
Usage example:
132
133
```python
134
from ansible_runner.config.runner import RunnerConfig
135
from ansible_runner import Runner
136
137
# Create detailed configuration
138
config = RunnerConfig(
139
private_data_dir='/path/to/project',
140
playbook='deploy.yml',
141
inventory='production/hosts',
142
extravars={
143
'app_version': '2.1.0',
144
'environment': 'production'
145
},
146
verbosity=2,
147
limit='webservers',
148
tags='deploy,configure',
149
process_isolation=True,
150
container_image='quay.io/ansible/ansible-runner:latest',
151
timeout=3600
152
)
153
154
# Create and run
155
runner = Runner(config)
156
status = runner.run()
157
```
158
159
### CommandConfig Class
160
161
Configuration class for executing Ansible command-line tools.
162
163
```python { .api }
164
class CommandConfig:
165
def __init__(
166
self,
167
executable_cmd: str,
168
cmdline_args: list = None,
169
private_data_dir: str = None,
170
input_fd: object = None,
171
output_fd: object = None,
172
error_fd: object = None,
173
artifact_dir: str = None,
174
ident: str = None,
175
rotate_artifacts: int = 0,
176
quiet: bool = False,
177
timeout: int = None,
178
runner_mode: str = 'pexpect',
179
process_isolation: bool = False,
180
process_isolation_executable: str = None,
181
process_isolation_path: str = None,
182
process_isolation_hide_paths: list = None,
183
process_isolation_show_paths: list = None,
184
process_isolation_ro_paths: list = None,
185
container_image: str = None,
186
container_volume_mounts: list = None,
187
container_options: list = None,
188
directory_isolation_base_path: str = None,
189
envvars: dict = None
190
)
191
```
192
193
Usage example:
194
195
```python
196
from ansible_runner.config.command import CommandConfig
197
from ansible_runner import Runner
198
199
# Configure command execution
200
config = CommandConfig(
201
executable_cmd='ansible-playbook',
202
cmdline_args=[
203
'site.yml',
204
'-i', 'inventory',
205
'--check',
206
'--diff'
207
],
208
private_data_dir='/project',
209
timeout=1800
210
)
211
212
# Execute command
213
runner = Runner(config)
214
status = runner.run()
215
216
print(f"Command completed: {status}")
217
print(f"Return code: {runner.rc}")
218
```
219
220
### InventoryConfig Class
221
222
Configuration class for inventory operations.
223
224
```python { .api }
225
class InventoryConfig:
226
def __init__(
227
self,
228
action: str,
229
inventories: list,
230
response_format: str = None,
231
host: str = None,
232
playbook_dir: str = None,
233
private_data_dir: str = None,
234
artifact_dir: str = None,
235
ident: str = None,
236
rotate_artifacts: int = 0,
237
timeout: int = None,
238
process_isolation: bool = False,
239
process_isolation_executable: str = None,
240
container_image: str = None,
241
envvars: dict = None
242
)
243
```
244
245
Usage example:
246
247
```python
248
from ansible_runner.config.inventory import InventoryConfig
249
from ansible_runner import Runner
250
251
# Configure inventory listing
252
config = InventoryConfig(
253
action='list',
254
inventories=['production/hosts', 'production/groups'],
255
response_format='json'
256
)
257
258
runner = Runner(config)
259
status = runner.run()
260
261
if status == 'successful':
262
# Process inventory data from artifacts
263
print("Inventory retrieved successfully")
264
```
265
266
### DocConfig Class
267
268
Configuration class for plugin documentation operations.
269
270
```python { .api }
271
class DocConfig:
272
def __init__(
273
self,
274
plugin_names: list,
275
plugin_type: str = None,
276
response_format: str = None,
277
snippet: bool = False,
278
playbook_dir: str = None,
279
module_path: str = None,
280
private_data_dir: str = None,
281
artifact_dir: str = None,
282
ident: str = None,
283
rotate_artifacts: int = 0,
284
timeout: int = None,
285
process_isolation: bool = False,
286
process_isolation_executable: str = None,
287
container_image: str = None,
288
envvars: dict = None
289
)
290
```
291
292
Usage example:
293
294
```python
295
from ansible_runner.config.doc import DocConfig
296
from ansible_runner import Runner
297
298
# Configure plugin documentation retrieval
299
config = DocConfig(
300
plugin_names=['copy', 'template', 'file'],
301
plugin_type='module',
302
response_format='json',
303
snippet=False
304
)
305
306
runner = Runner(config)
307
status = runner.run()
308
```
309
310
### AnsibleCfgConfig Class
311
312
Configuration class for Ansible configuration operations.
313
314
```python { .api }
315
class AnsibleCfgConfig:
316
def __init__(
317
self,
318
action: str,
319
config_file: str = None,
320
only_changed: bool = None,
321
private_data_dir: str = None,
322
artifact_dir: str = None,
323
ident: str = None,
324
rotate_artifacts: int = 0,
325
timeout: int = None,
326
process_isolation: bool = False,
327
process_isolation_executable: str = None,
328
container_image: str = None,
329
envvars: dict = None
330
)
331
```
332
333
Usage example:
334
335
```python
336
from ansible_runner.config.ansible_cfg import AnsibleCfgConfig
337
from ansible_runner import Runner
338
339
# Configure ansible configuration dump
340
config = AnsibleCfgConfig(
341
action='dump',
342
only_changed=True
343
)
344
345
runner = Runner(config)
346
status = runner.run()
347
```
348
349
## Advanced Usage Patterns
350
351
### Custom Event Handling
352
353
```python
354
class CustomRunner:
355
def __init__(self, config):
356
self.events = []
357
self.runner = Runner(
358
config,
359
event_handler=self.handle_event,
360
status_handler=self.handle_status,
361
finished_callback=self.handle_finished
362
)
363
364
def handle_event(self, event):
365
# Custom event processing
366
self.events.append(event)
367
if event['event'] == 'runner_on_failed':
368
print(f"Task failed: {event['event_data']}")
369
return True
370
371
def handle_status(self, data, config):
372
print(f"Status changed: {data['status']}")
373
374
def handle_finished(self, runner):
375
print(f"Execution finished: {runner.status}")
376
self.analyze_results()
377
378
def analyze_results(self):
379
failed_tasks = [e for e in self.events if e['event'] == 'runner_on_failed']
380
print(f"Found {len(failed_tasks)} failed tasks")
381
382
def run(self):
383
return self.runner.run()
384
385
# Usage
386
config = RunnerConfig(
387
private_data_dir='/project',
388
playbook='site.yml'
389
)
390
custom_runner = CustomRunner(config)
391
status = custom_runner.run()
392
```
393
394
### Configuration Chaining
395
396
```python
397
def create_production_config(playbook, **overrides):
398
"""Create standardized production configuration"""
399
base_config = {
400
'private_data_dir': '/production/ansible',
401
'inventory': 'production/hosts',
402
'verbosity': 1,
403
'process_isolation': True,
404
'container_image': 'quay.io/ansible/ansible-runner:latest',
405
'timeout': 3600,
406
'envvars': {
407
'ANSIBLE_HOST_KEY_CHECKING': 'False',
408
'ANSIBLE_GATHERING': 'smart'
409
}
410
}
411
412
# Apply overrides
413
base_config.update(overrides)
414
base_config['playbook'] = playbook
415
416
return RunnerConfig(**base_config)
417
418
# Usage
419
deploy_config = create_production_config(
420
'deploy.yml',
421
limit='webservers',
422
extravars={'version': '2.1.0'}
423
)
424
425
maintenance_config = create_production_config(
426
'maintenance.yml',
427
tags='maintenance',
428
check=True
429
)
430
```
431
432
### Result Processing
433
434
```python
435
def process_runner_results(runner):
436
"""Comprehensive result processing"""
437
results = {
438
'status': runner.status,
439
'return_code': runner.rc,
440
'events': [],
441
'failed_hosts': set(),
442
'changed_hosts': set(),
443
'unreachable_hosts': set()
444
}
445
446
# Process events
447
for event in runner.events:
448
event_type = event['event']
449
results['events'].append(event)
450
451
if event_type == 'runner_on_failed':
452
results['failed_hosts'].add(event['event_data']['host'])
453
elif event_type == 'runner_on_ok' and event['event_data'].get('changed'):
454
results['changed_hosts'].add(event['event_data']['host'])
455
elif event_type == 'runner_on_unreachable':
456
results['unreachable_hosts'].add(event['event_data']['host'])
457
458
return results
459
460
# Usage
461
config = RunnerConfig(private_data_dir='/project', playbook='site.yml')
462
runner = Runner(config)
463
status = runner.run()
464
results = process_runner_results(runner)
465
466
print(f"Execution summary:")
467
print(f" Status: {results['status']}")
468
print(f" Failed hosts: {len(results['failed_hosts'])}")
469
print(f" Changed hosts: {len(results['changed_hosts'])}")
470
print(f" Unreachable hosts: {len(results['unreachable_hosts'])}")
471
```