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
//! Ansible Vault encryption and decryption operations.
//!
//! This module provides the [`AnsibleVault`] struct for managing encrypted files
//! and strings using Ansible Vault, along with specialized error types.

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

/// Ansible Vault encryption and decryption utility.
///
/// The `AnsibleVault` struct provides a comprehensive interface for managing
/// encrypted files and strings using Ansible Vault. It supports all major
/// vault operations including encryption, decryption, viewing, editing, and rekeying.
///
/// # Examples
///
/// ## Basic File Operations
///
/// ```rust,no_run
/// use ansible::AnsibleVault;
///
/// let mut vault = AnsibleVault::new();
/// vault.set_vault_password_file("vault_pass.txt");
///
/// // Encrypt a file
/// vault.encrypt("secrets.yml")?;
///
/// // Decrypt a file
/// vault.decrypt("secrets.yml")?;
///
/// // View encrypted content
/// let content = vault.view("secrets.yml")?;
/// println!("Content: {}", content);
/// # Ok::<(), ansible::AnsibleError>(())
/// ```
///
/// ## String Encryption
///
/// ```rust,no_run
/// use ansible::AnsibleVault;
///
/// let mut vault = AnsibleVault::new();
/// vault.set_vault_password_file("vault_pass.txt");
///
/// // Encrypt a string
/// let encrypted = vault.encrypt_string("my_secret_password")?;
/// println!("Encrypted: {}", encrypted);
/// # Ok::<(), ansible::AnsibleError>(())
/// ```
///
/// ## Multiple Vault IDs
///
/// ```rust,no_run
/// use ansible::AnsibleVault;
///
/// let mut vault = AnsibleVault::new();
/// vault.set_vault_id("prod@vault_pass.txt");
///
/// // Operations will use the specified vault ID
/// vault.encrypt("production_secrets.yml")?;
/// # Ok::<(), ansible::AnsibleError>(())
/// ```
///
/// ## Rekeying Files
///
/// ```rust,no_run
/// use ansible::AnsibleVault;
///
/// let mut vault = AnsibleVault::new();
/// vault
///     .set_vault_password_file("old_pass.txt")
///     .set_new_vault_password_file("new_pass.txt");
///
/// // Change the encryption key
/// vault.rekey("secrets.yml")?;
/// # Ok::<(), ansible::AnsibleError>(())
/// ```
#[derive(Debug, Clone)]
pub struct AnsibleVault {
    pub(crate) command: String,
    pub(crate) cfg: CommandConfig,
    pub(crate) vault_id: Option<String>,
    pub(crate) vault_password_file: Option<String>,
}

impl Default for AnsibleVault {
    fn default() -> Self {
        Self {
            command: "ansible-vault".into(),
            cfg: CommandConfig::default(),
            vault_id: None,
            vault_password_file: None,
        }
    }
}

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

        if let Some(ref vault_id) = self.vault_id {
            write!(f, " --vault-id {}", vault_id)?;
        }

        if let Some(ref password_file) = self.vault_password_file {
            write!(f, " --vault-password-file {}", password_file)?;
        }

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

        Ok(())
    }
}

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

    /// Set vault ID for encryption/decryption
    pub fn set_vault_id(&mut self, vault_id: impl Into<String>) -> &mut Self {
        self.vault_id = Some(vault_id.into());
        self
    }

    /// Set vault password file
    pub fn set_vault_password_file(&mut self, file_path: impl Into<String>) -> &mut Self {
        self.vault_password_file = Some(file_path.into());
        self
    }

    /// Set new vault password file for rekeying operations
    pub fn set_new_vault_password_file(&mut self, file_path: impl Into<String>) -> &mut Self {
        self.arg("--new-vault-password-file").arg(file_path.into());
        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 vault command with the given action and arguments
    fn execute_vault_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 vault-specific options
        if let Some(ref vault_id) = self.vault_id {
            cmd.args(["--vault-id", vault_id]);
        }

        if let Some(ref password_file) = self.vault_password_file {
            cmd.args(["--vault-password-file", password_file]);
        }

        // 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 vault {} 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())
    }

    /// Create and encrypt a new file
    pub fn create(&self, file_path: impl Into<String>) -> Result<String> {
        let file_path = file_path.into();
        self.execute_vault_command("create", &[file_path])
    }

    /// Encrypt an existing file
    pub fn encrypt(&self, file_path: impl Into<String>) -> Result<String> {
        let file_path = file_path.into();
        self.execute_vault_command("encrypt", &[file_path])
    }

    /// Decrypt a file
    pub fn decrypt(&self, file_path: impl Into<String>) -> Result<String> {
        let file_path = file_path.into();
        self.execute_vault_command("decrypt", &[file_path])
    }

    /// Decrypt and view a file without modifying it
    pub fn view(&self, file_path: impl Into<String>) -> Result<String> {
        let file_path = file_path.into();
        self.execute_vault_command("view", &[file_path])
    }

    /// Edit an encrypted file
    pub fn edit(&self, file_path: impl Into<String>) -> Result<String> {
        let file_path = file_path.into();
        self.execute_vault_command("edit", &[file_path])
    }

    /// Re-encrypt a file with a new password
    pub fn rekey(&self, file_path: impl Into<String>) -> Result<String> {
        let file_path = file_path.into();
        self.execute_vault_command("rekey", &[file_path])
    }

    /// Encrypt a string and output it in a format suitable for inclusion in YAML
    pub fn encrypt_string(&self, string_to_encrypt: impl Into<String>) -> Result<String> {
        let string_to_encrypt = string_to_encrypt.into();
        self.execute_vault_command("encrypt_string", &[string_to_encrypt])
    }

    /// Encrypt a string with a variable name
    pub fn encrypt_string_with_name(
        &self,
        string_to_encrypt: impl Into<String>,
        var_name: impl Into<String>,
    ) -> Result<String> {
        let string_to_encrypt = string_to_encrypt.into();
        let var_name = var_name.into();
        self.execute_vault_command("encrypt_string", &[
            "--name".to_string(),
            var_name,
            string_to_encrypt,
        ])
    }

    /// Encrypt a string and prompt for input
    pub fn encrypt_string_prompt(&self) -> Result<String> {
        self.execute_vault_command("encrypt_string", &["--prompt".to_string()])
    }

    /// Encrypt a string with stdin input
    pub fn encrypt_string_stdin(&self, stdin_name: impl Into<String>) -> Result<String> {
        let stdin_name = stdin_name.into();
        self.execute_vault_command("encrypt_string", &[
            "--stdin-name".to_string(),
            stdin_name,
        ])
    }

    /// Decrypt a file to a specific output location
    pub fn decrypt_to_file(
        &self,
        input_file: impl Into<String>,
        output_file: impl Into<String>,
    ) -> Result<String> {
        let input_file = input_file.into();
        let output_file = output_file.into();
        self.execute_vault_command("decrypt", &[
            "--output".to_string(),
            output_file,
            input_file,
        ])
    }

    /// Encrypt a file to a specific output location
    pub fn encrypt_to_file(
        &self,
        input_file: impl Into<String>,
        output_file: impl Into<String>,
    ) -> Result<String> {
        let input_file = input_file.into();
        let output_file = output_file.into();
        self.execute_vault_command("encrypt", &[
            "--output".to_string(),
            output_file,
            input_file,
        ])
    }

    /// Set the vault ID used for encryption (when multiple vault IDs are available)
    pub fn set_encrypt_vault_id(&mut self, vault_id: impl Into<String>) -> &mut Self {
        self.cfg.arg("--encrypt-vault-id");
        self.cfg.arg(vault_id.into());
        self
    }

    /// Ask for vault password interactively
    pub fn ask_vault_password(&mut self) -> &mut Self {
        self.cfg.arg("--ask-vault-password");
        self
    }

    /// 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
    }
}

/// Specialized error types for Ansible Vault operations.
///
/// These errors provide specific context for vault-related failures,
/// making it easier to handle different types of vault errors appropriately.
///
/// # Examples
///
/// ```rust
/// use ansible::{VaultError, AnsibleError};
///
/// // Handle specific vault errors
/// let vault_result: Result<(), AnsibleError> = Ok(());
/// match vault_result {
///     Err(AnsibleError::ConfigError(message)) if message.contains("password") => {
///         eprintln!("Please provide a vault password");
///     }
///     Err(AnsibleError::CommandFailed { message, .. }) if message.contains("decrypt") => {
///         eprintln!("Failed to decrypt - check your password");
///     }
///     _ => {}
/// }
/// ```
#[derive(Debug, Clone)]
pub enum VaultError {
    /// Vault password was not provided when required
    ///
    /// This error occurs when attempting vault operations without
    /// specifying a password file, vault ID, or interactive password.
    NoPassword,

    /// The vault file has an invalid or corrupted format
    ///
    /// This error occurs when the encrypted file doesn't match
    /// the expected Ansible Vault format.
    InvalidFormat,

    /// The specified vault ID was not found
    ///
    /// This error occurs when using multiple vault IDs and the
    /// specified ID is not available or configured.
    VaultIdNotFound,

    /// Decryption operation failed
    ///
    /// This error occurs when the vault password is incorrect
    /// or the encrypted data is corrupted.
    DecryptionFailed,

    /// Encryption operation failed
    ///
    /// This error occurs when the encryption process fails,
    /// possibly due to file permissions or disk space issues.
    EncryptionFailed,
}

impl std::fmt::Display for VaultError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VaultError::NoPassword => write!(f, "Vault password not provided"),
            VaultError::InvalidFormat => write!(f, "Invalid vault file format"),
            VaultError::VaultIdNotFound => write!(f, "Vault ID not found"),
            VaultError::DecryptionFailed => write!(f, "Decryption failed"),
            VaultError::EncryptionFailed => write!(f, "Encryption failed"),
        }
    }
}

impl std::error::Error for VaultError {}