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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! Ansible playbook execution and management.
//!
//! This module provides the [`Playbook`] struct for executing Ansible playbooks
//! and the [`Play`] enum for representing different types of playbook content.

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

/// Ansible playbook executor with comprehensive configuration options.
///
/// The `Playbook` struct provides a fluent interface for configuring and executing
/// Ansible playbooks. It supports all major ansible-playbook command-line options
/// and provides type-safe configuration.
///
/// # Examples
///
/// ## Basic Playbook Execution
///
/// ```rust,no_run
/// use ansible::{Playbook, Play};
///
/// let mut playbook = Playbook::default();
/// playbook.set_inventory("hosts.yml");
///
/// // Run from file
/// let result = playbook.run(Play::from_file("site.yml"))?;
/// println!("Playbook result: {}", result);
/// # Ok::<(), ansible::AnsibleError>(())
/// ```
///
/// ## Advanced Configuration
///
/// ```rust,no_run
/// use ansible::{Playbook, Play};
///
/// let mut playbook = Playbook::default();
/// playbook
///     .set_inventory("production")
///     .set_verbosity(2)
///     .add_extra_var("env", "production")
///     .add_extra_var("version", "1.2.3")
///     .add_tag("deploy")
///     .add_tag("config")
///     .set_check_mode(true);
///
/// let result = playbook.run(Play::from_file("deploy.yml"))?;
/// # Ok::<(), ansible::AnsibleError>(())
/// ```
///
/// ## Environment Configuration
///
/// ```rust,no_run
/// use ansible::Playbook;
///
/// let mut playbook = Playbook::default();
/// playbook
///     .set_system_envs()
///     .filter_envs(["HOME", "PATH", "USER"])
///     .add_env("ANSIBLE_HOST_KEY_CHECKING", "False")
///     .add_env("ANSIBLE_STDOUT_CALLBACK", "json");
/// # Ok::<(), ansible::AnsibleError>(())
/// ```
#[derive(Debug, Clone)]
pub struct Playbook {
    pub(crate) command: String,
    pub(crate) cfg: CommandConfig,
    pub(crate) inventory: Option<String>,
}

impl Default for Playbook {
    fn default() -> Self {
        Self {
            command: "ansible-playbook".into(),
            cfg: CommandConfig::default(),
            inventory: None,
        }
    }
}

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

        if let Some(ref inventory) = self.inventory {
            if !inventory.is_empty() {
                write!(f, " -i {}", inventory)?;
            }
        }

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

        Ok(())
    }
}

impl Playbook {
    /// Set environment variables from the current system environment.
    ///
    /// This method copies all environment variables from the current process
    /// to be passed to the ansible-playbook command.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Playbook;
    ///
    /// let mut playbook = Playbook::default();
    /// playbook.set_system_envs();
    /// ```
    pub fn set_system_envs(&mut self) -> &mut Self {
        self.cfg.set_system_envs();
        self
    }

    /// Filter environment variables to only include specified keys.
    ///
    /// This method is useful for limiting which environment variables
    /// are passed to ansible-playbook commands.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Playbook;
    ///
    /// let mut playbook = Playbook::default();
    /// playbook
    ///     .set_system_envs()
    ///     .filter_envs(["HOME", "PATH", "USER"]);
    /// ```
    pub fn filter_envs<T, S>(&mut self, iter: T) -> &mut Self
    where
        T: IntoIterator<Item = S>,
        S: AsRef<OsStr> + Display,
    {
        self.cfg.filter_envs(iter);
        self
    }

    /// Add a single environment variable.
    ///
    /// This method adds or overwrites an environment variable that will
    /// be passed to the ansible-playbook command.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Playbook;
    ///
    /// let mut playbook = Playbook::default();
    /// playbook
    ///     .add_env("ANSIBLE_HOST_KEY_CHECKING", "False")
    ///     .add_env("ANSIBLE_STDOUT_CALLBACK", "json");
    /// ```
    pub fn add_env(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
        self.cfg.add_env(key, value);
        self
    }

    /// Add a single command-line argument.
    ///
    /// This method adds a raw command-line argument to the ansible-playbook command.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Playbook;
    ///
    /// let mut playbook = Playbook::default();
    /// playbook
    ///     .arg("--verbose")
    ///     .arg("--check");
    /// ```
    pub fn arg<S: AsRef<OsStr> + Display>(&mut self, arg: S) -> &mut Self {
        self.cfg.args.push(arg.to_string());
        self
    }

    /// Add multiple command-line arguments.
    ///
    /// This method adds multiple raw command-line arguments to the ansible-playbook command.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Playbook;
    ///
    /// let mut playbook = Playbook::default();
    /// playbook.args(["--verbose", "--check", "--diff"]);
    /// ```
    pub fn args<T, S>(&mut self, args: T) -> &mut Self
    where
        T: IntoIterator<Item = S>,
        S: AsRef<OsStr> + Display,
    {
        for arg in args {
            self.arg(arg);
        }
        self
    }

    /// Set the inventory file or directory.
    ///
    /// This method specifies the inventory file or directory to use
    /// for host and group information.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Playbook;
    ///
    /// let mut playbook = Playbook::default();
    /// playbook.set_inventory("hosts.yml");
    /// playbook.set_inventory("/etc/ansible/hosts");
    /// playbook.set_inventory("production");
    /// ```
    pub fn set_inventory(&mut self, s: &str) -> &mut Self {
        self.inventory = Some(s.to_string());
        self
    }

    /// Configure output to use JSON format.
    ///
    /// This method sets environment variables to configure ansible-playbook
    /// to output results in JSON format.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Playbook;
    ///
    /// let mut playbook = Playbook::default();
    /// playbook.set_output_json();
    /// ```
    pub fn set_output_json(&mut self) -> &mut Self {
        self.cfg
            .add_env("ANSIBLE_STDOUT_CALLBACK", "json")
            .add_env("ANSIBLE_LOAD_CALLBACK_PLUGINS", "True");
        self
    }

    /// Set the verbosity level for playbook execution.
    ///
    /// This method sets the verbosity level for ansible-playbook output.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Playbook;
    ///
    /// let mut playbook = Playbook::default();
    /// playbook.set_verbosity(2); // -vv
    /// ```
    pub fn set_verbosity(&mut self, level: u8) -> &mut Self {
        let verbose_arg = format!("-{}", "v".repeat(level as usize));
        self.arg(verbose_arg);
        self
    }

    /// Add an extra variable for playbook execution.
    ///
    /// This method adds extra variables that will be passed to the playbook.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Playbook;
    ///
    /// let mut playbook = Playbook::default();
    /// playbook
    ///     .add_extra_var("env", "production")
    ///     .add_extra_var("version", "1.2.3");
    /// ```
    pub fn add_extra_var(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
        let var_string = format!("{}={}", key.into(), value.into());
        self.arg("--extra-vars").arg(var_string);
        self
    }

    /// Add a tag to limit playbook execution.
    ///
    /// This method adds tags to limit which tasks are executed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Playbook;
    ///
    /// let mut playbook = Playbook::default();
    /// playbook
    ///     .add_tag("deploy")
    ///     .add_tag("config");
    /// ```
    pub fn add_tag(&mut self, tag: impl Into<String>) -> &mut Self {
        self.arg("--tags").arg(tag.into());
        self
    }

    /// Enable check mode (dry run).
    ///
    /// This method enables check mode for the playbook execution.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Playbook;
    ///
    /// let mut playbook = Playbook::default();
    /// playbook.set_check_mode(true);
    /// ```
    pub fn set_check_mode(&mut self, enabled: bool) -> &mut Self {
        if enabled {
            self.arg("--check");
        }
        self
    }

    /// Execute an Ansible playbook.
    ///
    /// This method executes an Ansible playbook from either a file or string content.
    /// It handles temporary file creation for string content and cleanup afterwards.
    ///
    /// # Arguments
    ///
    /// * `play` - The playbook source (file path or content)
    ///
    /// # Returns
    ///
    /// Returns the combined stdout and stderr output from the ansible-playbook command.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The playbook file cannot be read or created
    /// - The ansible-playbook command fails to execute
    /// - The command returns a non-zero exit code
    ///
    /// # Examples
    ///
    /// ## Running from File
    ///
    /// ```rust,no_run
    /// use ansible::{Playbook, Play};
    ///
    /// let mut playbook = Playbook::default();
    /// playbook.set_inventory("hosts.yml");
    ///
    /// let result = playbook.run(Play::from_file("site.yml"))?;
    /// println!("Playbook result: {}", result);
    /// # Ok::<(), ansible::AnsibleError>(())
    /// ```
    ///
    /// ## Running from Content
    ///
    /// ```rust,no_run
    /// use ansible::{Playbook, Play};
    ///
    /// let yaml_content = r#"
    /// - hosts: all
    ///   tasks:
    ///     - name: Ensure nginx is installed
    ///       package:
    ///         name: nginx
    ///         state: present
    /// "#;
    ///
    /// let mut playbook = Playbook::default();
    /// let result = playbook.run(Play::from_content(yaml_content))?;
    /// # Ok::<(), ansible::AnsibleError>(())
    /// ```
    pub fn run(&self, play: Play) -> Result<String> {
        let (playbook_path, is_temp) = match play {
            Play::File(path) => (path, false),
            Play::Content(content) => {
                let temp_dir = std::env::temp_dir();
                let temp_file = temp_dir.join("ansible_playbook.yaml");
                let mut f = std::fs::File::create(&temp_file)?;
                write!(f, "{}", content)?;
                (temp_file.to_string_lossy().to_string(), true)
            }
        };
        let full_cmd = self.to_string();
        let cmd_vec: Vec<&str> = full_cmd.split_whitespace().collect();
        let mut cmd = process::Command::new(&self.command);
        cmd.envs(&self.cfg.envs);
        cmd.args(&cmd_vec.as_slice()[1..]);
        cmd.args(&self.cfg.args);
        cmd.arg(&playbook_path);
        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(
                "Ansible playbook execution failed",
                output.status.code(),
                Some(stdout),
                Some(stderr),
            ));
        }

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

        // Clean up temporary file if it was created
        if is_temp {
            std::fs::remove_file(&playbook_path)?;
        }

        Ok(output_str)
    }
}

/// Represents different sources of playbook content.
///
/// The `Play` enum allows you to specify playbook content either from
/// a file on disk or from a string containing YAML content.
///
/// # Examples
///
/// ## From File
///
/// ```rust
/// use ansible::Play;
///
/// let play = Play::from_file("site.yml");
/// let play = Play::from_file("/path/to/playbook.yml");
/// ```
///
/// ## From Content
///
/// ```rust
/// use ansible::Play;
///
/// let yaml_content = r#"
/// - hosts: all
///   tasks:
///     - name: Ensure nginx is installed
///       package:
///         name: nginx
///         state: present
/// "#;
///
/// let play = Play::from_content(yaml_content);
/// ```
#[derive(Debug, Clone)]
pub enum Play {
    /// Playbook content loaded from a file path
    ///
    /// The file should contain valid YAML playbook content.
    File(String),

    /// Playbook content provided as a string
    ///
    /// The string should contain valid YAML playbook content.
    Content(String),
}

impl Play {
    /// Create a Play from a file path.
    ///
    /// This method creates a Play that will read playbook content from
    /// the specified file when executed.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the playbook file (relative or absolute)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Play;
    ///
    /// let play = Play::from_file("site.yml");
    /// let play = Play::from_file("/path/to/playbook.yml");
    /// let play = Play::from_file("playbooks/deploy.yml");
    /// ```
    pub fn from_file(path: impl Into<String>) -> Self {
        Play::File(path.into())
    }

    /// Create a Play from string content.
    ///
    /// This method creates a Play from YAML content provided as a string.
    /// The content will be written to a temporary file when executed.
    ///
    /// # Arguments
    ///
    /// * `content` - YAML playbook content as a string
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansible::Play;
    ///
    /// let yaml_content = r#"
    /// - hosts: all
    ///   become: yes
    ///   tasks:
    ///     - name: Update package cache
    ///       apt:
    ///         update_cache: yes
    ///       when: ansible_os_family == "Debian"
    ///
    ///     - name: Install essential packages
    ///       package:
    ///         name:
    ///           - curl
    ///           - wget
    ///           - git
    ///         state: present
    /// "#;
    ///
    /// let play = Play::from_content(yaml_content);
    /// ```
    pub fn from_content(content: impl Into<String>) -> Self {
        Play::Content(content.into())
    }
}