use crate::{Playbook, Play, AnsibleError};
use crate::command_config::CommandConfig;
use crate::async_support::{AsyncResult, AsyncExecute, IntoAsync, FromAsync};
use std::ffi::OsStr;
use std::fmt::Display;
use tokio::process::Command;
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
#[derive(Debug, Clone)]
pub struct AsyncPlaybook {
command: String,
cfg: CommandConfig,
inventory: Option<String>,
}
impl Default for AsyncPlaybook {
fn default() -> Self {
Self {
command: "ansible-playbook".to_string(),
cfg: CommandConfig::default(),
inventory: None,
}
}
}
impl AsyncPlaybook {
pub fn new() -> Self {
Self::default()
}
pub fn set_system_envs(&mut self) -> &mut Self {
self.cfg.set_system_envs();
self
}
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
}
pub fn add_env(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
self.cfg.add_env(key, value);
self
}
pub fn arg<S: AsRef<OsStr> + Display>(&mut self, arg: S) -> &mut Self {
self.cfg.arg(arg);
self
}
pub fn args<T, S>(&mut self, args: T) -> &mut Self
where
T: IntoIterator<Item = S>,
S: AsRef<OsStr> + Display,
{
self.cfg.args(args);
self
}
pub fn set_inventory(&mut self, inventory: &str) -> &mut Self {
self.inventory = Some(inventory.to_string());
self
}
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
}
pub fn set_verbosity(&mut self, level: u8) -> &mut Self {
let verbose_arg = format!("-{}", "v".repeat(level as usize));
self.arg(verbose_arg);
self
}
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
}
pub fn add_tag(&mut self, tag: impl Into<String>) -> &mut Self {
self.arg("--tags").arg(tag.into());
self
}
pub fn set_check_mode(&mut self, enabled: bool) -> &mut Self {
if enabled {
self.arg("--check");
}
self
}
pub async fn run(&self, play: AsyncPlay) -> AsyncResult<String> {
let playbook_path = match &play.inner {
Play::File(path) => path.clone(),
Play::Content(content) => {
let temp_file = tempfile::NamedTempFile::new()
.map_err(|e| AnsibleError::io_error(&format!("Failed to create temp file: {}", e)))?;
let temp_path = temp_file.path().to_string_lossy().to_string();
let mut file = File::create(&temp_path).await
.map_err(|e| AnsibleError::io_error(&format!("Failed to create playbook file: {}", e)))?;
file.write_all(content.as_bytes()).await
.map_err(|e| AnsibleError::io_error(&format!("Failed to write playbook content: {}", e)))?;
file.flush().await
.map_err(|e| AnsibleError::io_error(&format!("Failed to flush playbook file: {}", e)))?;
temp_path
}
};
let full_cmd = self.to_string();
let cmd_vec: Vec<&str> = full_cmd.split_whitespace().collect();
let mut cmd = 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().await?;
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 s = String::from_utf8_lossy(&result);
Ok(s.to_string())
}
fn to_string(&self) -> String {
let mut parts = vec![self.command.clone()];
if let Some(ref inventory) = self.inventory {
parts.push("-i".to_string());
parts.push(inventory.clone());
}
for arg in &self.cfg.args {
parts.push(arg.to_string());
}
parts.join(" ")
}
}
#[derive(Debug, Clone)]
pub struct AsyncPlay {
inner: Play,
}
impl AsyncPlay {
pub fn from_file(path: impl Into<String>) -> Self {
Self {
inner: Play::from_file(path),
}
}
pub fn from_content(content: impl Into<String>) -> Self {
Self {
inner: Play::from_content(content),
}
}
}
impl AsyncExecute for AsyncPlaybook {
async fn execute_async(&self) -> AsyncResult<String> {
let ping_playbook = r#"
---
- hosts: all
gather_facts: no
tasks:
- name: Test connection
ping:
"#;
self.run(AsyncPlay::from_content(ping_playbook)).await
}
}
impl IntoAsync<AsyncPlaybook> for Playbook {
fn into_async(self) -> AsyncPlaybook {
AsyncPlaybook {
command: self.command,
cfg: self.cfg,
inventory: self.inventory,
}
}
}
impl FromAsync<AsyncPlaybook> for Playbook {
fn from_async(async_playbook: AsyncPlaybook) -> Self {
Playbook {
command: async_playbook.command,
cfg: async_playbook.cfg,
inventory: async_playbook.inventory,
}
}
}
impl IntoAsync<AsyncPlay> for Play {
fn into_async(self) -> AsyncPlay {
AsyncPlay { inner: self }
}
}
impl FromAsync<AsyncPlay> for Play {
fn from_async(async_play: AsyncPlay) -> Self {
async_play.inner
}
}
impl std::fmt::Display for AsyncPlaybook {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.to_string())
}
}