0
# Configuration Management
1
2
Ansible Core's configuration system provides centralized management of all settings through multiple sources including configuration files, environment variables, and command-line options with comprehensive validation and runtime access.
3
4
## Capabilities
5
6
### Configuration Manager
7
8
Central configuration system coordinating multiple configuration sources with precedence handling, validation, and runtime access to all Ansible settings.
9
10
```python { .api }
11
class ConfigManager:
12
"""
13
Central configuration manager handling multiple sources and precedence.
14
15
Attributes:
16
- _base_defs: Base configuration definitions
17
- _config_file: Current configuration file path
18
- _changed_keys: Keys that have been modified
19
"""
20
21
def __init__(self, conf_file=None, defs_file=None):
22
"""Initialize configuration manager"""
23
24
def get_config_value(self, config_key, origin=None):
25
"""
26
Get configuration value by key.
27
28
Parameters:
29
- config_key: Configuration key name
30
- origin: Configuration origin (file, env, cli)
31
32
Returns:
33
object: Configuration value
34
"""
35
36
def get_config_value_and_origin(self, config_key):
37
"""
38
Get configuration value and its origin.
39
40
Parameters:
41
- config_key: Configuration key name
42
43
Returns:
44
tuple: (value, origin)
45
"""
46
47
def update_config_data(self, defs=None, configfile=None):
48
"""
49
Update configuration data from sources.
50
51
Parameters:
52
- defs: Configuration definitions
53
- configfile: Configuration file path
54
"""
55
56
def get_config_keys(self):
57
"""
58
Get all available configuration keys.
59
60
Returns:
61
list: Configuration key names
62
"""
63
64
# Global configuration instance
65
config: ConfigManager # Global configuration manager
66
```
67
68
### Configuration Constants
69
70
Core configuration constants and default values used throughout Ansible Core for consistent behavior and customization points.
71
72
```python { .api }
73
# Global configuration access
74
config: ConfigManager # Global configuration manager instance
75
76
# Color codes for output formatting
77
COLOR_CODES: dict = {
78
'black': '0;30',
79
'blue': '0;34',
80
'green': '0;32',
81
'cyan': '0;36',
82
'red': '0;31',
83
'purple': '0;35',
84
'yellow': '0;33',
85
'white': '1;37',
86
'normal': '0'
87
}
88
89
# Boolean true values
90
BOOL_TRUE: list # Values considered True in configuration
91
92
# Plugin configuration
93
CONFIGURABLE_PLUGINS: tuple = (
94
'become', 'cache', 'callback', 'cliconf', 'connection',
95
'httpapi', 'inventory', 'lookup', 'netconf', 'shell', 'vars'
96
)
97
98
DOCUMENTABLE_PLUGINS: tuple = CONFIGURABLE_PLUGINS + (
99
'module', 'strategy', 'test', 'filter'
100
)
101
102
# File extensions and patterns
103
REJECT_EXTS: list # File extensions to ignore
104
DOC_EXTENSIONS: tuple # Documentation file extensions
105
IGNORE_FILES: tuple # Files to ignore during module search
106
107
# Default values
108
DEFAULT_PASSWORD_CHARS: str # Characters for auto-generated passwords
109
DEFAULT_REMOTE_PASS: None # Default remote password
110
DEFAULT_BECOME_PASS: None # Default become password
111
DEFAULT_SUBSET: None # Default host subset
112
```
113
114
### Configuration Definitions
115
116
```python { .api }
117
class Setting:
118
"""
119
Configuration setting definition with validation and metadata.
120
121
Attributes:
122
- name: Setting name
123
- default: Default value
124
- description: Setting description
125
- type: Expected value type
126
- choices: Valid choices (if applicable)
127
"""
128
129
def __init__(self, name, default=None, description='', type=str, choices=None):
130
"""Initialize configuration setting"""
131
132
def validate(self, value):
133
"""
134
Validate configuration value.
135
136
Parameters:
137
- value: Value to validate
138
139
Returns:
140
object: Validated value
141
142
Raises:
143
AnsibleOptionsError: If validation fails
144
"""
145
```
146
147
## Configuration Sources
148
149
### Configuration File Precedence
150
151
Ansible reads configuration from multiple sources in order of precedence (highest to lowest):
152
153
1. **Command line options** (`-v`, `--inventory`, etc.)
154
2. **Environment variables** (`ANSIBLE_*`)
155
3. **ansible.cfg in current directory**
156
4. **~/.ansible.cfg** (user configuration)
157
5. **/etc/ansible/ansible.cfg** (system configuration)
158
6. **Built-in defaults**
159
160
### Configuration File Format
161
162
```ini
163
[defaults]
164
# Basic configuration
165
inventory = ./inventory
166
remote_user = ansible
167
host_key_checking = False
168
retry_files_enabled = False
169
gathering = implicit
170
fact_caching = memory
171
172
# Output and logging
173
stdout_callback = yaml
174
log_path = /var/log/ansible.log
175
display_skipped_hosts = False
176
display_ok_hosts = True
177
178
# Connection settings
179
timeout = 30
180
forks = 5
181
transport = ssh
182
183
# Privilege escalation
184
become = True
185
become_method = sudo
186
become_user = root
187
become_ask_pass = False
188
189
[inventory]
190
# Inventory plugin settings
191
enable_plugins = host_list, script, auto, yaml, ini, toml
192
193
[ssh_connection]
194
# SSH-specific settings
195
ssh_args = -o ControlMaster=auto -o ControlPersist=60s
196
pipelining = True
197
control_path = ~/.ansible/cp/%%h-%%p-%%r
198
199
[colors]
200
# Output coloring
201
highlight = white
202
verbose = blue
203
warn = bright purple
204
error = red
205
debug = dark gray
206
deprecate = purple
207
skip = cyan
208
unreachable = red
209
ok = green
210
changed = yellow
211
diff_add = green
212
diff_remove = red
213
diff_lines = cyan
214
```
215
216
### Environment Variables
217
218
```bash
219
# Core settings
220
export ANSIBLE_CONFIG=/path/to/ansible.cfg
221
export ANSIBLE_INVENTORY=/path/to/inventory
222
export ANSIBLE_REMOTE_USER=ansible
223
export ANSIBLE_BECOME=true
224
export ANSIBLE_BECOME_USER=root
225
226
# Connection settings
227
export ANSIBLE_HOST_KEY_CHECKING=false
228
export ANSIBLE_SSH_ARGS='-o ControlMaster=auto'
229
export ANSIBLE_TIMEOUT=30
230
export ANSIBLE_FORKS=10
231
232
# Output and logging
233
export ANSIBLE_STDOUT_CALLBACK=yaml
234
export ANSIBLE_LOG_PATH=/var/log/ansible.log
235
export ANSIBLE_DISPLAY_SKIPPED_HOSTS=false
236
237
# Vault settings
238
export ANSIBLE_VAULT_PASSWORD_FILE=/path/to/vault-pass
239
export ANSIBLE_VAULT_IDENTITY_LIST=default@/path/to/pass
240
241
# Plugin paths
242
export ANSIBLE_LIBRARY=/path/to/modules
243
export ANSIBLE_ACTION_PLUGINS=/path/to/action_plugins
244
export ANSIBLE_CALLBACK_PLUGINS=/path/to/callback_plugins
245
```
246
247
## Common Configuration Settings
248
249
### Connection Settings
250
251
```python { .api }
252
# Access configuration values
253
remote_user = config.get_config_value('DEFAULT_REMOTE_USER')
254
timeout = config.get_config_value('DEFAULT_TIMEOUT')
255
forks = config.get_config_value('DEFAULT_FORKS')
256
host_key_checking = config.get_config_value('HOST_KEY_CHECKING')
257
```
258
259
Key connection settings:
260
- `DEFAULT_REMOTE_USER` - Default SSH user
261
- `DEFAULT_TIMEOUT` - Connection timeout in seconds
262
- `DEFAULT_FORKS` - Number of parallel processes
263
- `HOST_KEY_CHECKING` - SSH host key verification
264
- `DEFAULT_TRANSPORT` - Connection transport method
265
266
### Privilege Escalation Settings
267
268
```python { .api }
269
# Become settings
270
become = config.get_config_value('DEFAULT_BECOME')
271
become_method = config.get_config_value('DEFAULT_BECOME_METHOD')
272
become_user = config.get_config_value('DEFAULT_BECOME_USER')
273
```
274
275
Key become settings:
276
- `DEFAULT_BECOME` - Enable privilege escalation
277
- `DEFAULT_BECOME_METHOD` - Escalation method (sudo, su, etc.)
278
- `DEFAULT_BECOME_USER` - Target user for escalation
279
- `DEFAULT_BECOME_ASK_PASS` - Prompt for become password
280
281
### Output and Logging Settings
282
283
```python { .api }
284
# Output settings
285
stdout_callback = config.get_config_value('STDOUT_CALLBACK')
286
log_path = config.get_config_value('DEFAULT_LOG_PATH')
287
display_skipped = config.get_config_value('DISPLAY_SKIPPED_HOSTS')
288
```
289
290
Key output settings:
291
- `STDOUT_CALLBACK` - Output format plugin
292
- `DEFAULT_LOG_PATH` - Log file location
293
- `DISPLAY_SKIPPED_HOSTS` - Show skipped tasks
294
- `DEFAULT_VERBOSITY` - Default verbosity level
295
296
### Plugin Settings
297
298
```python { .api }
299
# Plugin configuration
300
callback_plugins = config.get_config_value('DEFAULT_CALLBACK_PLUGIN_PATH')
301
action_plugins = config.get_config_value('DEFAULT_ACTION_PLUGIN_PATH')
302
library_path = config.get_config_value('DEFAULT_MODULE_PATH')
303
```
304
305
Key plugin settings:
306
- Plugin search paths for each plugin type
307
- Plugin whitelist/blacklist configuration
308
- Collection search paths
309
- Plugin-specific configuration options
310
311
## Configuration Validation
312
313
### Setting Types and Validation
314
315
```python
316
# Example configuration validation
317
from ansible.config.manager import ConfigManager
318
319
config = ConfigManager()
320
321
# Get with validation
322
try:
323
forks = config.get_config_value('DEFAULT_FORKS')
324
if not isinstance(forks, int) or forks < 1:
325
raise ValueError("Forks must be positive integer")
326
except Exception as e:
327
print(f"Configuration error: {e}")
328
```
329
330
### Custom Configuration
331
332
```python
333
# Programmatic configuration
334
from ansible.constants import set_constant
335
336
# Set custom constant
337
set_constant('CUSTOM_TIMEOUT', 60)
338
339
# Update configuration at runtime
340
config.update_config_data()
341
```
342
343
## Usage Examples
344
345
### Reading Configuration
346
347
```python
348
from ansible.constants import config
349
350
# Get basic settings
351
inventory_path = config.get_config_value('DEFAULT_HOST_LIST')
352
remote_user = config.get_config_value('DEFAULT_REMOTE_USER')
353
become_enabled = config.get_config_value('DEFAULT_BECOME')
354
355
# Get setting with origin
356
value, origin = config.get_config_value_and_origin('DEFAULT_FORKS')
357
print(f"Forks: {value} (from {origin})")
358
359
# List all available settings
360
all_keys = config.get_config_keys()
361
for key in sorted(all_keys):
362
value = config.get_config_value(key)
363
print(f"{key}: {value}")
364
```
365
366
### Configuration in Plugins
367
368
```python
369
# Using configuration in custom plugins
370
from ansible.plugins.action import ActionBase
371
from ansible.constants import config
372
373
class ActionModule(ActionBase):
374
def run(self, tmp=None, task_vars=None):
375
# Access configuration
376
timeout = config.get_config_value('DEFAULT_TIMEOUT')
377
remote_user = config.get_config_value('DEFAULT_REMOTE_USER')
378
379
# Use configuration in plugin logic
380
result = {'changed': False}
381
return result
382
```
383
384
### Dynamic Configuration
385
386
```python
387
# Configuration testing and debugging
388
import os
389
from ansible.config.manager import ConfigManager
390
391
# Test different configuration sources
392
os.environ['ANSIBLE_FORKS'] = '20'
393
394
config = ConfigManager()
395
forks_value, forks_origin = config.get_config_value_and_origin('DEFAULT_FORKS')
396
print(f"Forks: {forks_value} from {forks_origin}") # Should show environment
397
398
# Reset and test file configuration
399
del os.environ['ANSIBLE_FORKS']
400
config.update_config_data()
401
```