use crate::{AnsibleInventory, AnsibleError, InventoryFormat, InventoryData};
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;
#[derive(Debug, Clone)]
pub struct AsyncAnsibleInventory {
command: String,
cfg: CommandConfig,
inventory: Option<String>,
playbook_dir: Option<String>,
}
impl Default for AsyncAnsibleInventory {
fn default() -> Self {
Self {
command: "ansible-inventory".to_string(),
cfg: CommandConfig::default(),
inventory: None,
playbook_dir: None,
}
}
}
impl AsyncAnsibleInventory {
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 set_inventory(&mut self, inventory: impl Into<String>) -> &mut Self {
self.inventory = Some(inventory.into());
self
}
pub fn set_inventory_file(&mut self, inventory: impl Into<String>) -> &mut Self {
self.set_inventory(inventory)
}
pub fn set_playbook_dir(&mut self, dir: impl Into<String>) -> &mut Self {
self.playbook_dir = Some(dir.into());
self
}
pub fn set_format(&mut self, format: InventoryFormat) -> &mut Self {
self.arg("--output").arg(format.to_string());
self
}
pub async fn list(&self) -> AsyncResult<String> {
self.execute_inventory_command(&["--list"]).await
}
pub async fn host(&self, hostname: impl AsRef<str>) -> AsyncResult<String> {
self.execute_inventory_command(&["--host", hostname.as_ref()]).await
}
pub async fn graph(&self) -> AsyncResult<String> {
self.execute_inventory_command(&["--graph"]).await
}
pub async fn json(&self) -> AsyncResult<String> {
self.execute_inventory_command(&["--list"]).await
}
pub async fn parse_inventory_data(&self) -> AsyncResult<InventoryData> {
let json_output = self.json().await?;
let inventory_data: InventoryData = serde_json::from_str(&json_output)
.map_err(|e| AnsibleError::parsing_failed(&format!("Failed to parse inventory JSON: {}", e)))?;
Ok(inventory_data)
}
async fn execute_inventory_command(&self, args: &[&str]) -> AsyncResult<String> {
let mut cmd = Command::new(&self.command);
cmd.envs(&self.cfg.envs);
cmd.args(&self.cfg.args);
cmd.args(args);
if let Some(ref inventory) = self.inventory {
cmd.arg("--inventory").arg(inventory);
}
if let Some(ref playbook_dir) = self.playbook_dir {
cmd.arg("--playbook-dir").arg(playbook_dir);
}
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 inventory command 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())
}
}
impl AsyncExecute for AsyncAnsibleInventory {
async fn execute_async(&self) -> AsyncResult<String> {
self.list().await
}
}
impl IntoAsync<AsyncAnsibleInventory> for AnsibleInventory {
fn into_async(self) -> AsyncAnsibleInventory {
AsyncAnsibleInventory {
command: self.command,
cfg: self.cfg,
inventory: self.inventory,
playbook_dir: self.playbook_dir,
}
}
}
impl FromAsync<AsyncAnsibleInventory> for AnsibleInventory {
fn from_async(async_inventory: AsyncAnsibleInventory) -> Self {
AnsibleInventory {
command: async_inventory.command,
cfg: async_inventory.cfg,
inventory: async_inventory.inventory,
playbook_dir: async_inventory.playbook_dir,
}
}
}
impl std::fmt::Display for AsyncAnsibleInventory {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.command)
}
}