ansible-rs 1.1.0

A Rust wrapper library for Ansible command-line tools (Linux/Unix only)
Documentation
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! Ansible configuration querying and management.
//!
//! This module provides the [`AnsibleConfig`] struct for querying and managing
//! Ansible configuration settings, along with related enums for type-safe configuration.

use crate::command_config::CommandConfig;
use crate::errors::{AnsibleError, Result};
use std::fmt::{Display, Formatter};
use std::process;

/// Ansible configuration management utility.
///
/// The `AnsibleConfig` struct provides a comprehensive interface for querying
/// and managing Ansible configuration settings. It supports listing, dumping,
/// viewing, initializing, and validating configuration files.
///
/// # Examples
///
/// ## Basic Configuration Queries
///
/// ```rust,no_run
/// use ansible::AnsibleConfig;
///
/// let mut config = AnsibleConfig::new();
///
/// // List all configuration options
/// let config_list = config.list()?;
/// println!("Configuration: {}", config_list);
///
/// // Dump current configuration
/// let config_dump = config.dump()?;
/// println!("Config dump: {}", config_dump);
/// # Ok::<(), ansible::AnsibleError>(())
/// ```
///
/// ## Formatted Output
///
/// ```rust,no_run
/// use ansible::{AnsibleConfig, ConfigFormat};
///
/// let mut config = AnsibleConfig::new();
/// config.set_format(ConfigFormat::Json);
///
/// // Get configuration in JSON format
/// let json_config = config.dump()?;
/// println!("JSON config: {}", json_config);
/// # Ok::<(), ansible::AnsibleError>(())
/// ```
///
/// ## Plugin-Specific Configuration
///
/// ```rust,no_run
/// use ansible::{AnsibleConfig, PluginType};
///
/// let mut config = AnsibleConfig::new();
/// config.set_plugin_type(PluginType::Callback);
///
/// // List only callback plugin configuration
/// let callback_config = config.list()?;
/// println!("Callback plugins: {}", callback_config);
/// # Ok::<(), ansible::AnsibleError>(())
/// ```
///
/// ## Configuration File Management
///
/// ```rust,no_run
/// use ansible::AnsibleConfig;
///
/// let mut config = AnsibleConfig::new();
///
/// // Initialize a new configuration file
/// config.init()?;
///
/// // Validate existing configuration
/// config.validate()?;
///
/// // View specific configuration file
/// config.set_config_file("custom.cfg");
/// let content = config.view()?;
/// # Ok::<(), ansible::AnsibleError>(())
/// ```
#[derive(Debug, Clone)]
pub struct AnsibleConfig {
    pub(crate) command: String,
    pub(crate) cfg: CommandConfig,
    pub(crate) config_file: Option<String>,
    pub(crate) plugin_type: Option<String>,
}

impl Default for AnsibleConfig {
    fn default() -> Self {
        Self {
            command: "ansible-config".into(),
            cfg: CommandConfig::default(),
            config_file: None,
            plugin_type: None,
        }
    }
}

impl Display for AnsibleConfig {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.command)?;

        if let Some(ref config_file) = self.config_file {
            write!(f, " --config {}", config_file)?;
        }

        if let Some(ref plugin_type) = self.plugin_type {
            write!(f, " --type {}", plugin_type)?;
        }

        if !self.cfg.args.is_empty() {
            write!(f, " {}", self.cfg.args.join(" "))?;
        }

        Ok(())
    }
}

impl AnsibleConfig {
    /// Create a new AnsibleConfig instance
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the configuration file path
    pub fn set_config_file(&mut self, file_path: impl Into<String>) -> &mut Self {
        self.config_file = Some(file_path.into());
        self
    }

    /// Set the output format for configuration commands.
    ///
    /// This method sets the format for configuration output.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::{AnsibleConfig, ConfigFormat};
    ///
    /// let mut config = AnsibleConfig::new();
    /// config.set_format(ConfigFormat::Json);
    /// ```
    pub fn set_format(&mut self, format: ConfigFormat) -> &mut Self {
        self.arg("--format").arg(format.to_string());
        self
    }

    /// Set the plugin type filter.
    ///
    /// This method filters configuration to a specific plugin type.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::{AnsibleConfig, PluginType};
    ///
    /// let mut config = AnsibleConfig::new();
    /// config.set_plugin_type(PluginType::Callback);
    /// ```
    pub fn set_plugin_type(&mut self, plugin_type: PluginType) -> &mut Self {
        self.plugin_type = Some(plugin_type.to_string());
        self
    }

    /// Add a custom argument
    pub fn arg(&mut self, arg: impl Into<String>) -> &mut Self {
        self.cfg.arg(arg.into());
        self
    }

    /// Add multiple arguments
    pub fn args<I, S>(&mut self, args: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let args_vec: Vec<String> = args.into_iter().map(|s| s.into()).collect();
        self.cfg.args(args_vec);
        self
    }

    /// Set environment variables from the system
    pub fn set_system_envs(&mut self) -> &mut Self {
        self.cfg.set_system_envs();
        self
    }

    /// Add an environment variable
    pub fn add_env(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
        self.cfg.add_env(key, value);
        self
    }

    /// Execute a config command with the given action and arguments
    fn execute_config_command(&self, action: &str, args: &[String]) -> Result<String> {
        let mut cmd = process::Command::new(&self.command);
        cmd.envs(&self.cfg.envs);
        cmd.arg(action);

        // Add config-specific options
        if let Some(ref config_file) = self.config_file {
            cmd.args(["--config", config_file]);
        }

        if let Some(ref plugin_type) = self.plugin_type {
            cmd.args(["--type", plugin_type]);
        }

        // Add custom arguments
        cmd.args(&self.cfg.args);

        // Add action-specific arguments
        cmd.args(args);

        let output = cmd.output()?;

        if !output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout).to_string();
            let stderr = String::from_utf8_lossy(&output.stderr).to_string();
            return Err(AnsibleError::command_failed(
                format!("Ansible config {} command failed", action),
                output.status.code(),
                Some(stdout),
                Some(stderr),
            ));
        }

        let result = [output.stdout, "\n".as_bytes().to_vec(), output.stderr].concat();
        let s = String::from_utf8_lossy(&result);

        Ok(s.to_string())
    }

    /// List all available configuration options
    pub fn list(&self) -> Result<String> {
        self.execute_config_command("list", &[])
    }

    /// List configuration options with specific format
    pub fn list_with_format(&self, format: ConfigFormat) -> Result<String> {
        self.execute_config_command("list", &[
            "--format".to_string(),
            format.to_string(),
        ])
    }

    /// Show current configuration settings
    pub fn dump(&self) -> Result<String> {
        self.execute_config_command("dump", &[])
    }

    /// Show current configuration settings with specific format
    pub fn dump_with_format(&self, format: ConfigFormat) -> Result<String> {
        self.execute_config_command("dump", &[
            "--format".to_string(),
            format.to_string(),
        ])
    }

    /// Show only changed configuration settings
    pub fn dump_changed_only(&self) -> Result<String> {
        self.execute_config_command("dump", &["--only-changed".to_string()])
    }

    /// View the current configuration file
    pub fn view(&self) -> Result<String> {
        self.execute_config_command("view", &[])
    }

    /// Initialize a new configuration file
    pub fn init(&self) -> Result<String> {
        self.execute_config_command("init", &[])
    }

    /// Initialize a new configuration file with specific format
    pub fn init_with_format(&self, format: ConfigFormat) -> Result<String> {
        self.execute_config_command("init", &[
            "--format".to_string(),
            format.to_string(),
        ])
    }

    /// Initialize a configuration file with all options disabled (commented out)
    pub fn init_disabled(&self) -> Result<String> {
        self.execute_config_command("init", &["--disabled".to_string()])
    }

    /// Validate the configuration file
    pub fn validate(&self) -> Result<String> {
        self.execute_config_command("validate", &[])
    }

    /// Validate the configuration file with specific format
    pub fn validate_with_format(&self, format: ConfigFormat) -> Result<String> {
        self.execute_config_command("validate", &[
            "--format".to_string(),
            format.to_string(),
        ])
    }

    /// Enable verbose output
    pub fn verbose(&mut self) -> &mut Self {
        self.cfg.arg("-v");
        self
    }

    /// Set multiple levels of verbosity
    pub fn verbosity(&mut self, level: u8) -> &mut Self {
        let v_arg = "-".to_string() + &"v".repeat(level as usize);
        self.cfg.arg(v_arg);
        self
    }

    /// Get a reference to the command configuration (for testing)
    pub fn get_config(&self) -> &CommandConfig {
        &self.cfg
    }
}

/// Configuration output formats for ansible-config commands.
///
/// Specifies the format for configuration output when using dump, list,
/// or view operations.
///
/// # Examples
///
/// ```rust
/// use ansible::{AnsibleConfig, ConfigFormat};
///
/// let mut config = AnsibleConfig::new();
/// config.set_format(ConfigFormat::Json);
///
/// // All available formats
/// let formats = ConfigFormat::all();
/// assert_eq!(formats.len(), 3);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigFormat {
    /// JSON format - structured data suitable for programmatic processing
    Json,
    /// YAML format - human-readable structured format
    Yaml,
    /// Display format - human-readable text format with descriptions
    Display,
}

impl Display for ConfigFormat {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            ConfigFormat::Json => write!(f, "json"),
            ConfigFormat::Yaml => write!(f, "yaml"),
            ConfigFormat::Display => write!(f, "display"),
        }
    }
}

impl ConfigFormat {
    /// Get all available formats
    pub fn all() -> Vec<ConfigFormat> {
        vec![ConfigFormat::Json, ConfigFormat::Yaml, ConfigFormat::Display]
    }
}

/// Plugin types for filtering configuration queries.
///
/// Ansible supports various plugin types, each with their own configuration
/// options. This enum allows filtering configuration queries to specific
/// plugin types.
///
/// # Examples
///
/// ```rust
/// use ansible::{AnsibleConfig, PluginType};
///
/// let mut config = AnsibleConfig::new();
/// config.set_plugin_type(PluginType::Callback);
///
/// // Get all available plugin types
/// let types = PluginType::all();
/// assert_eq!(types.len(), 11);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PluginType {
    /// Become plugins - handle privilege escalation (sudo, su, etc.)
    Become,
    /// Cache plugins - cache facts and inventory data
    Cache,
    /// Callback plugins - handle output and notifications
    Callback,
    /// Connection plugins - handle connections to remote hosts
    Connection,
    /// HTTP API plugins - handle HTTP-based API connections
    Httpapi,
    /// Inventory plugins - parse and provide inventory data
    Inventory,
    /// Lookup plugins - retrieve data from external sources
    Lookup,
    /// NETCONF plugins - handle NETCONF protocol connections
    Netconf,
    /// Shell plugins - handle shell command execution
    Shell,
    /// Strategy plugins - control task execution strategies
    Strategy,
    /// Vars plugins - provide additional variables
    Vars,
}

impl Display for PluginType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            PluginType::Become => write!(f, "become"),
            PluginType::Cache => write!(f, "cache"),
            PluginType::Callback => write!(f, "callback"),
            PluginType::Connection => write!(f, "connection"),
            PluginType::Httpapi => write!(f, "httpapi"),
            PluginType::Inventory => write!(f, "inventory"),
            PluginType::Lookup => write!(f, "lookup"),
            PluginType::Netconf => write!(f, "netconf"),
            PluginType::Shell => write!(f, "shell"),
            PluginType::Strategy => write!(f, "strategy"),
            PluginType::Vars => write!(f, "vars"),
        }
    }
}

impl PluginType {
    /// Get all available plugin types
    pub fn all() -> Vec<PluginType> {
        vec![
            PluginType::Become,
            PluginType::Cache,
            PluginType::Callback,
            PluginType::Connection,
            PluginType::Httpapi,
            PluginType::Inventory,
            PluginType::Lookup,
            PluginType::Netconf,
            PluginType::Shell,
            PluginType::Strategy,
            PluginType::Vars,
        ]
    }
}