terraform_wrapper/lib.rs
1//! # terraform-wrapper
2//!
3//! A type-safe Terraform CLI wrapper for Rust.
4//!
5//! This crate provides an idiomatic Rust interface to the Terraform command-line tool.
6//! All commands use a builder pattern and async execution via Tokio.
7//!
8//! # Quick Start
9//!
10//! ```no_run
11//! use terraform_wrapper::prelude::*;
12//!
13//! #[tokio::main]
14//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
15//! let tf = Terraform::builder()
16//! .working_dir("./infra")
17//! .build()?;
18//!
19//! // Initialize, apply, read outputs, destroy
20//! InitCommand::new().execute(&tf).await?;
21//!
22//! ApplyCommand::new()
23//! .auto_approve()
24//! .var("region", "us-west-2")
25//! .execute(&tf)
26//! .await?;
27//!
28//! let result = OutputCommand::new()
29//! .name("endpoint")
30//! .raw()
31//! .execute(&tf)
32//! .await?;
33//!
34//! if let OutputResult::Raw(value) = result {
35//! println!("Endpoint: {value}");
36//! }
37//!
38//! DestroyCommand::new().auto_approve().execute(&tf).await?;
39//!
40//! Ok(())
41//! }
42//! ```
43//!
44//! # Core Concepts
45//!
46//! ## The `TerraformCommand` Trait
47//!
48//! All commands implement [`TerraformCommand`], which provides the
49//! [`execute()`](TerraformCommand::execute) method. You must import this trait
50//! to call `.execute()`:
51//!
52//! ```rust
53//! use terraform_wrapper::TerraformCommand; // Required for .execute()
54//! ```
55//!
56//! ## Builder Pattern
57//!
58//! Commands are configured using method chaining:
59//!
60//! ```rust,no_run
61//! # use terraform_wrapper::prelude::*;
62//! # async fn example() -> terraform_wrapper::error::Result<()> {
63//! # let tf = Terraform::builder().build()?;
64//! ApplyCommand::new()
65//! .auto_approve()
66//! .var("region", "us-west-2")
67//! .var_file("prod.tfvars")
68//! .target("module.vpc")
69//! .parallelism(10)
70//! .execute(&tf)
71//! .await?;
72//! # Ok(())
73//! # }
74//! ```
75//!
76//! ## The `Terraform` Client
77//!
78//! The [`Terraform`] struct holds shared configuration (binary path, working
79//! directory, environment variables) passed to every command:
80//!
81//! ```rust,no_run
82//! # use terraform_wrapper::prelude::*;
83//! # fn example() -> terraform_wrapper::error::Result<()> {
84//! let tf = Terraform::builder()
85//! .working_dir("./infra")
86//! .env("AWS_REGION", "us-west-2")
87//! .env_var("instance_type", "t3.medium") // Sets TF_VAR_instance_type
88//! .timeout_secs(300)
89//! .build()?;
90//! # Ok(())
91//! # }
92//! ```
93//!
94//! Programmatic defaults: `-no-color` and `-input=false` are enabled by default.
95//! Override with `.color(true)` and `.input(true)`.
96//!
97//! ## Error Handling
98//!
99//! All commands return `Result<T, terraform_wrapper::Error>`. The error type
100//! implements `std::error::Error`, so it works with `anyhow` and other error
101//! libraries via `?`:
102//!
103//! ```rust,no_run
104//! # use terraform_wrapper::prelude::*;
105//! # use terraform_wrapper::Error;
106//! # async fn example() -> terraform_wrapper::error::Result<()> {
107//! # let tf = Terraform::builder().build()?;
108//! match InitCommand::new().execute(&tf).await {
109//! Ok(output) => println!("Initialized: {}", output.stdout),
110//! Err(Error::NotFound) => eprintln!("Terraform binary not found"),
111//! Err(Error::CommandFailed { stderr, .. }) => eprintln!("Failed: {stderr}"),
112//! Err(Error::Timeout { timeout_seconds }) => eprintln!("Timed out after {timeout_seconds}s"),
113//! Err(e) => eprintln!("Error: {e}"),
114//! }
115//! # Ok(())
116//! # }
117//! ```
118//!
119//! # Command Categories
120//!
121//! ## Lifecycle
122//!
123//! ```rust
124//! use terraform_wrapper::commands::{
125//! InitCommand, // terraform init
126//! PlanCommand, // terraform plan
127//! ApplyCommand, // terraform apply
128//! DestroyCommand, // terraform destroy
129//! };
130//! ```
131//!
132//! ## Inspection
133//!
134//! ```rust
135//! use terraform_wrapper::commands::{
136//! ValidateCommand, // terraform validate
137//! ShowCommand, // terraform show (state or plan)
138//! OutputCommand, // terraform output
139//! FmtCommand, // terraform fmt
140//! VersionCommand, // terraform version
141//! };
142//! ```
143//!
144//! ## State and Workspace Management
145//!
146//! ```rust
147//! use terraform_wrapper::commands::{
148//! StateCommand, // terraform state (list, show, mv, rm, pull, push)
149//! WorkspaceCommand, // terraform workspace (list, show, new, select, delete)
150//! ImportCommand, // terraform import
151//! };
152//! ```
153//!
154//! # JSON Output Types
155//!
156//! With the `json` feature (enabled by default), commands return typed structs
157//! instead of raw strings:
158//!
159//! ```rust,no_run
160//! # use terraform_wrapper::prelude::*;
161//! # async fn example() -> terraform_wrapper::error::Result<()> {
162//! # let tf = Terraform::builder().build()?;
163//! // Version info
164//! let info = tf.version().await?;
165//! println!("Terraform {} on {}", info.terraform_version, info.platform);
166//!
167//! // Validate with diagnostics
168//! let result = ValidateCommand::new().execute(&tf).await?;
169//! if !result.valid {
170//! for diag in &result.diagnostics {
171//! eprintln!("[{}] {}: {}", diag.severity, diag.summary, diag.detail);
172//! }
173//! }
174//!
175//! // Show state with typed resources
176//! let result = ShowCommand::new().execute(&tf).await?;
177//! if let ShowResult::State(state) = result {
178//! for resource in &state.values.root_module.resources {
179//! println!("{} ({})", resource.address, resource.resource_type);
180//! }
181//! }
182//!
183//! // Show plan with resource changes
184//! let result = ShowCommand::new().plan_file("tfplan").execute(&tf).await?;
185//! if let ShowResult::Plan(plan) = result {
186//! for change in &plan.resource_changes {
187//! println!("{}: {:?}", change.address, change.change.actions);
188//! }
189//! }
190//!
191//! // Output values
192//! let result = OutputCommand::new().json().execute(&tf).await?;
193//! if let OutputResult::Json(outputs) = result {
194//! for (name, val) in &outputs {
195//! println!("{name} = {}", val.value);
196//! }
197//! }
198//! # Ok(())
199//! # }
200//! ```
201//!
202//! # Streaming Output
203//!
204//! Long-running commands like `apply` and `plan` with `-json` produce streaming
205//! NDJSON (one JSON object per line) instead of a single blob. Use
206//! [`streaming::stream_terraform`] to process events as they arrive -- useful
207//! for progress reporting, logging, or UI updates:
208//!
209//! ```rust,no_run
210//! # use terraform_wrapper::prelude::*;
211//! use terraform_wrapper::streaming::{stream_terraform, JsonLogLine};
212//!
213//! # async fn example() -> terraform_wrapper::error::Result<()> {
214//! # let tf = Terraform::builder().build()?;
215//! let result = stream_terraform(
216//! &tf,
217//! ApplyCommand::new().auto_approve().json(),
218//! |line: JsonLogLine| {
219//! match line.log_type.as_str() {
220//! "apply_start" => println!("Creating: {}", line.message),
221//! "apply_progress" => println!(" {}", line.message),
222//! "apply_complete" => println!("Done: {}", line.message),
223//! "apply_errored" => eprintln!("Error: {}", line.message),
224//! "change_summary" => println!("Summary: {}", line.message),
225//! _ => {}
226//! }
227//! },
228//! ).await?;
229//! # Ok(())
230//! # }
231//! ```
232//!
233//! Common event types: `version`, `planned_change`, `change_summary`,
234//! `apply_start`, `apply_progress`, `apply_complete`, `apply_errored`, `outputs`.
235//!
236//! # Config Builder
237//!
238//! With the `config` feature, define Terraform configurations entirely in Rust.
239//! No `.tf` files needed -- generates `.tf.json` that Terraform processes natively:
240//!
241//! ```rust
242//! # #[cfg(feature = "config")]
243//! # fn example() -> std::io::Result<()> {
244//! use terraform_wrapper::config::TerraformConfig;
245//! use serde_json::json;
246//!
247//! let config = TerraformConfig::new()
248//! .required_provider("aws", "hashicorp/aws", "~> 5.0")
249//! .provider("aws", json!({ "region": "us-west-2" }))
250//! .resource("aws_instance", "web", json!({
251//! "ami": "ami-0c55b159",
252//! "instance_type": "${var.instance_type}"
253//! }))
254//! .variable("instance_type", json!({
255//! "type": "string", "default": "t3.micro"
256//! }))
257//! .output("id", json!({ "value": "${aws_instance.web.id}" }));
258//!
259//! // Write to a tempdir for ephemeral use
260//! let dir = config.write_to_tempdir()?;
261//! // Terraform::builder().working_dir(dir.path()).build()?;
262//! # Ok(())
263//! # }
264//! ```
265//!
266//! Enable with:
267//! ```toml
268//! terraform-wrapper = { version = "0.1", features = ["config"] }
269//! ```
270//!
271//! # Feature Flags
272//!
273//! | Feature | Default | Description |
274//! |---------|---------|-------------|
275//! | `json` | Yes | Typed JSON output parsing via `serde` / `serde_json` |
276//! | `config` | No | [`TerraformConfig`](config::TerraformConfig) builder for `.tf.json` generation |
277//!
278//! Disable defaults for raw command output only:
279//!
280//! ```toml
281//! terraform-wrapper = { version = "0.1", default-features = false }
282//! ```
283//!
284//! # OpenTofu Compatibility
285//!
286//! [OpenTofu](https://opentofu.org/) works out of the box by pointing the client
287//! at the `tofu` binary:
288//!
289//! ```rust,no_run
290//! # use terraform_wrapper::prelude::*;
291//! # fn example() -> terraform_wrapper::error::Result<()> {
292//! let tf = Terraform::builder()
293//! .binary("tofu")
294//! .working_dir("./infra")
295//! .build()?;
296//! # Ok(())
297//! # }
298//! ```
299//!
300//! # Imports
301//!
302//! The [`prelude`] module re-exports everything you need:
303//!
304//! ```rust
305//! use terraform_wrapper::prelude::*;
306//! ```
307//!
308//! Or import selectively from [`commands`]:
309//!
310//! ```rust
311//! use terraform_wrapper::{Terraform, TerraformCommand};
312//! use terraform_wrapper::commands::{InitCommand, ApplyCommand, OutputCommand, OutputResult};
313//! ```
314
315use std::collections::HashMap;
316use std::path::{Path, PathBuf};
317use std::time::Duration;
318
319pub mod command;
320pub mod commands;
321#[cfg(feature = "config")]
322pub mod config;
323pub mod error;
324pub mod exec;
325pub mod prelude;
326#[cfg(feature = "json")]
327pub mod streaming;
328#[cfg(feature = "json")]
329pub mod types;
330
331pub use command::TerraformCommand;
332pub use error::{Error, Result};
333pub use exec::CommandOutput;
334
335/// Terraform client configuration.
336///
337/// Holds the binary path, working directory, environment variables, and global
338/// arguments shared across all command executions. Construct via
339/// [`Terraform::builder()`].
340#[derive(Debug, Clone)]
341pub struct Terraform {
342 pub(crate) binary: PathBuf,
343 pub(crate) working_dir: Option<PathBuf>,
344 pub(crate) env: HashMap<String, String>,
345 /// Args applied to every subcommand (e.g., `-no-color`).
346 pub(crate) global_args: Vec<String>,
347 /// Whether to add `-input=false` to commands that support it.
348 pub(crate) no_input: bool,
349 /// Default timeout for command execution.
350 pub(crate) timeout: Option<Duration>,
351}
352
353impl Terraform {
354 /// Create a new [`TerraformBuilder`].
355 #[must_use]
356 pub fn builder() -> TerraformBuilder {
357 TerraformBuilder::new()
358 }
359
360 /// Verify terraform is installed and return version info.
361 #[cfg(feature = "json")]
362 pub async fn version(&self) -> Result<types::version::VersionInfo> {
363 commands::version::VersionCommand::new().execute(self).await
364 }
365
366 /// Create a clone of this client with a different working directory.
367 ///
368 /// Useful for running a single command against a different directory
369 /// without modifying the original client:
370 ///
371 /// ```rust,no_run
372 /// # use terraform_wrapper::prelude::*;
373 /// # async fn example() -> terraform_wrapper::error::Result<()> {
374 /// let tf = Terraform::builder()
375 /// .working_dir("./infra/network")
376 /// .build()?;
377 ///
378 /// // Run one command against a different directory
379 /// let compute = tf.with_working_dir("./infra/compute");
380 /// InitCommand::new().execute(&compute).await?;
381 /// # Ok(())
382 /// # }
383 /// ```
384 #[must_use]
385 pub fn with_working_dir(&self, path: impl AsRef<Path>) -> Self {
386 let mut clone = self.clone();
387 clone.working_dir = Some(path.as_ref().to_path_buf());
388 clone
389 }
390}
391
392/// Builder for constructing a [`Terraform`] client.
393///
394/// Defaults:
395/// - Binary: resolved via `TERRAFORM_PATH` env var, or `terraform` on `PATH`
396/// - `-no-color` enabled (disable with `.color(true)`)
397/// - `-input=false` enabled (disable with `.input(true)`)
398#[derive(Debug)]
399pub struct TerraformBuilder {
400 binary: Option<PathBuf>,
401 working_dir: Option<PathBuf>,
402 env: HashMap<String, String>,
403 no_color: bool,
404 input: bool,
405 timeout: Option<Duration>,
406}
407
408impl TerraformBuilder {
409 fn new() -> Self {
410 Self {
411 binary: None,
412 working_dir: None,
413 env: HashMap::new(),
414 no_color: true,
415 input: false,
416 timeout: None,
417 }
418 }
419
420 /// Set an explicit path to the terraform binary.
421 #[must_use]
422 pub fn binary(mut self, path: impl Into<PathBuf>) -> Self {
423 self.binary = Some(path.into());
424 self
425 }
426
427 /// Set the default working directory for all commands.
428 ///
429 /// This is passed as `-chdir=<path>` to terraform.
430 #[must_use]
431 pub fn working_dir(mut self, path: impl AsRef<Path>) -> Self {
432 self.working_dir = Some(path.as_ref().to_path_buf());
433 self
434 }
435
436 /// Set an environment variable for all terraform subprocesses.
437 #[must_use]
438 pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
439 self.env.insert(key.into(), value.into());
440 self
441 }
442
443 /// Set a Terraform variable via environment (`TF_VAR_<name>`).
444 #[must_use]
445 pub fn env_var(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
446 self.env
447 .insert(format!("TF_VAR_{}", name.into()), value.into());
448 self
449 }
450
451 /// Enable or disable color output (default: disabled for programmatic use).
452 #[must_use]
453 pub fn color(mut self, enable: bool) -> Self {
454 self.no_color = !enable;
455 self
456 }
457
458 /// Enable or disable interactive input prompts (default: disabled).
459 #[must_use]
460 pub fn input(mut self, enable: bool) -> Self {
461 self.input = enable;
462 self
463 }
464
465 /// Set a default timeout for all command executions.
466 ///
467 /// Commands that exceed this duration will be terminated and return
468 /// [`Error::Timeout`]. No timeout is set by default.
469 #[must_use]
470 pub fn timeout(mut self, duration: Duration) -> Self {
471 self.timeout = Some(duration);
472 self
473 }
474
475 /// Set a default timeout in seconds for all command executions.
476 #[must_use]
477 pub fn timeout_secs(mut self, seconds: u64) -> Self {
478 self.timeout = Some(Duration::from_secs(seconds));
479 self
480 }
481
482 /// Build the [`Terraform`] client.
483 ///
484 /// Resolves the terraform binary in this order:
485 /// 1. Explicit path set via [`.binary()`](TerraformBuilder::binary)
486 /// 2. `TERRAFORM_PATH` environment variable
487 /// 3. `terraform` found on `PATH`
488 ///
489 /// Returns [`Error::NotFound`] if the binary cannot be located.
490 pub fn build(self) -> Result<Terraform> {
491 let binary = if let Some(path) = self.binary {
492 path
493 } else if let Ok(path) = std::env::var("TERRAFORM_PATH") {
494 PathBuf::from(path)
495 } else {
496 which::which("terraform").map_err(|_| Error::NotFound)?
497 };
498
499 let mut global_args = Vec::new();
500 if self.no_color {
501 global_args.push("-no-color".to_string());
502 }
503
504 Ok(Terraform {
505 binary,
506 working_dir: self.working_dir,
507 env: self.env,
508 global_args,
509 no_input: !self.input,
510 timeout: self.timeout,
511 })
512 }
513}