terraform-wrapper 0.4.0

A type-safe Terraform CLI wrapper for Rust
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//! # terraform-wrapper
//!
//! A type-safe Terraform CLI wrapper for Rust.
//!
//! This crate provides an idiomatic Rust interface to the Terraform command-line tool.
//! All commands use a builder pattern and async execution via Tokio.
//!
//! # Quick Start
//!
//! ```no_run
//! use terraform_wrapper::prelude::*;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let tf = Terraform::builder()
//!         .working_dir("./infra")
//!         .build()?;
//!
//!     // Initialize, apply, read outputs, destroy
//!     InitCommand::new().execute(&tf).await?;
//!
//!     ApplyCommand::new()
//!         .auto_approve()
//!         .var("region", "us-west-2")
//!         .execute(&tf)
//!         .await?;
//!
//!     let result = OutputCommand::new()
//!         .name("endpoint")
//!         .raw()
//!         .execute(&tf)
//!         .await?;
//!
//!     if let OutputResult::Raw(value) = result {
//!         println!("Endpoint: {value}");
//!     }
//!
//!     DestroyCommand::new().auto_approve().execute(&tf).await?;
//!
//!     Ok(())
//! }
//! ```
//!
//! # Core Concepts
//!
//! ## The `TerraformCommand` Trait
//!
//! All commands implement [`TerraformCommand`], which provides the
//! [`execute()`](TerraformCommand::execute) method. You must import this trait
//! to call `.execute()`:
//!
//! ```rust
//! use terraform_wrapper::TerraformCommand; // Required for .execute()
//! ```
//!
//! ## Builder Pattern
//!
//! Commands are configured using method chaining:
//!
//! ```rust,no_run
//! # use terraform_wrapper::prelude::*;
//! # async fn example() -> terraform_wrapper::error::Result<()> {
//! # let tf = Terraform::builder().build()?;
//! ApplyCommand::new()
//!     .auto_approve()
//!     .var("region", "us-west-2")
//!     .var_file("prod.tfvars")
//!     .target("module.vpc")
//!     .parallelism(10)
//!     .execute(&tf)
//!     .await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## The `Terraform` Client
//!
//! The [`Terraform`] struct holds shared configuration (binary path, working
//! directory, environment variables) passed to every command:
//!
//! ```rust,no_run
//! # use terraform_wrapper::prelude::*;
//! # fn example() -> terraform_wrapper::error::Result<()> {
//! let tf = Terraform::builder()
//!     .working_dir("./infra")
//!     .env("AWS_REGION", "us-west-2")
//!     .env_var("instance_type", "t3.medium")  // Sets TF_VAR_instance_type
//!     .timeout_secs(300)
//!     .build()?;
//! # Ok(())
//! # }
//! ```
//!
//! Programmatic defaults: `-no-color` and `-input=false` are enabled by default.
//! Override with `.color(true)` and `.input(true)`.
//!
//! ## Error Handling
//!
//! All commands return `Result<T, terraform_wrapper::Error>`. The error type
//! implements `std::error::Error`, so it works with `anyhow` and other error
//! libraries via `?`:
//!
//! ```rust,no_run
//! # use terraform_wrapper::prelude::*;
//! # use terraform_wrapper::Error;
//! # async fn example() -> terraform_wrapper::error::Result<()> {
//! # let tf = Terraform::builder().build()?;
//! match InitCommand::new().execute(&tf).await {
//!     Ok(output) => println!("Initialized: {}", output.stdout),
//!     Err(Error::NotFound) => eprintln!("Terraform binary not found"),
//!     Err(Error::CommandFailed { stderr, .. }) => eprintln!("Failed: {stderr}"),
//!     Err(Error::Timeout { timeout_seconds }) => eprintln!("Timed out after {timeout_seconds}s"),
//!     Err(e) => eprintln!("Error: {e}"),
//! }
//! # Ok(())
//! # }
//! ```
//!
//! # Command Categories
//!
//! ## Lifecycle
//!
//! ```rust
//! use terraform_wrapper::commands::{
//!     InitCommand,     // terraform init
//!     PlanCommand,     // terraform plan
//!     ApplyCommand,    // terraform apply
//!     DestroyCommand,  // terraform destroy
//! };
//! ```
//!
//! ## Inspection
//!
//! ```rust
//! use terraform_wrapper::commands::{
//!     ValidateCommand,  // terraform validate
//!     ShowCommand,      // terraform show (state or plan)
//!     OutputCommand,    // terraform output
//!     FmtCommand,       // terraform fmt
//!     GraphCommand,     // terraform graph (DOT format)
//!     ModulesCommand,   // terraform modules
//!     ProvidersCommand, // terraform providers (lock, mirror, schema)
//!     TestCommand,      // terraform test
//!     VersionCommand,   // terraform version
//! };
//! ```
//!
//! ## State and Workspace Management
//!
//! ```rust
//! use terraform_wrapper::commands::{
//!     StateCommand,       // terraform state (list, show, mv, rm, pull, push, replace-provider)
//!     WorkspaceCommand,   // terraform workspace (list, show, new, select, delete)
//!     ImportCommand,      // terraform import
//!     ForceUnlockCommand, // terraform force-unlock
//!     GetCommand,         // terraform get (download modules)
//!     RefreshCommand,     // terraform refresh (deprecated)
//!     RawCommand,         // any subcommand not covered above
//! };
//! ```
//!
//! # JSON Output Types
//!
//! With the `json` feature (enabled by default), commands return typed structs
//! instead of raw strings:
//!
//! ```rust,no_run
//! # use terraform_wrapper::prelude::*;
//! # async fn example() -> terraform_wrapper::error::Result<()> {
//! # let tf = Terraform::builder().build()?;
//! // Version info
//! let info = tf.version().await?;
//! println!("Terraform {} on {}", info.terraform_version, info.platform);
//!
//! // Validate with diagnostics
//! let result = ValidateCommand::new().execute(&tf).await?;
//! if !result.valid {
//!     for diag in &result.diagnostics {
//!         eprintln!("[{}] {}: {}", diag.severity, diag.summary, diag.detail);
//!     }
//! }
//!
//! // Show state with typed resources
//! let result = ShowCommand::new().execute(&tf).await?;
//! if let ShowResult::State(state) = result {
//!     for resource in &state.values.root_module.resources {
//!         println!("{} ({})", resource.address, resource.resource_type);
//!     }
//! }
//!
//! // Show plan with resource changes
//! let result = ShowCommand::new().plan_file("tfplan").execute(&tf).await?;
//! if let ShowResult::Plan(plan) = result {
//!     for change in &plan.resource_changes {
//!         println!("{}: {:?}", change.address, change.change.actions);
//!     }
//! }
//!
//! // Output values
//! let result = OutputCommand::new().json().execute(&tf).await?;
//! if let OutputResult::Json(outputs) = result {
//!     for (name, val) in &outputs {
//!         println!("{name} = {}", val.value);
//!     }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! # Streaming Output
//!
//! Long-running commands like `apply` and `plan` with `-json` produce streaming
//! NDJSON (one JSON object per line) instead of a single blob. Use
//! [`streaming::stream_terraform`] to process events as they arrive -- useful
//! for progress reporting, logging, or UI updates:
//!
//! ```rust,no_run
//! # use terraform_wrapper::prelude::*;
//! use terraform_wrapper::streaming::{stream_terraform, JsonLogLine};
//!
//! # async fn example() -> terraform_wrapper::error::Result<()> {
//! # let tf = Terraform::builder().build()?;
//! let result = stream_terraform(
//!     &tf,
//!     ApplyCommand::new().auto_approve().json(),
//!     &[0],
//!     |line: JsonLogLine| {
//!         match line.log_type.as_str() {
//!             "apply_start" => println!("Creating: {}", line.message),
//!             "apply_progress" => println!("  {}", line.message),
//!             "apply_complete" => println!("Done: {}", line.message),
//!             "apply_errored" => eprintln!("Error: {}", line.message),
//!             "change_summary" => println!("Summary: {}", line.message),
//!             _ => {}
//!         }
//!     },
//! ).await?;
//! # Ok(())
//! # }
//! ```
//!
//! Common event types: `version`, `planned_change`, `change_summary`,
//! `apply_start`, `apply_progress`, `apply_complete`, `apply_errored`, `outputs`.
//!
//! # Config Builder
//!
//! With the `config` feature, define Terraform configurations entirely in Rust.
//! No `.tf` files needed -- generates `.tf.json` that Terraform processes natively.
//!
//! Available builder methods:
//! [`required_provider`](config::TerraformConfig::required_provider),
//! [`backend`](config::TerraformConfig::backend),
//! [`provider`](config::TerraformConfig::provider),
//! [`variable`](config::TerraformConfig::variable),
//! [`data`](config::TerraformConfig::data),
//! [`resource`](config::TerraformConfig::resource),
//! [`local`](config::TerraformConfig::local),
//! [`module`](config::TerraformConfig::module),
//! [`output`](config::TerraformConfig::output).
//!
//! ```rust
//! # #[cfg(feature = "config")]
//! # fn example() -> std::io::Result<()> {
//! use terraform_wrapper::config::TerraformConfig;
//! use serde_json::json;
//!
//! let config = TerraformConfig::new()
//!     .required_provider("aws", "hashicorp/aws", "~> 5.0")
//!     .backend("s3", json!({
//!         "bucket": "my-tf-state",
//!         "key": "terraform.tfstate",
//!         "region": "us-west-2"
//!     }))
//!     .provider("aws", json!({ "region": "us-west-2" }))
//!     .variable("instance_type", json!({
//!         "type": "string", "default": "t3.micro"
//!     }))
//!     .data("aws_ami", "latest", json!({
//!         "most_recent": true,
//!         "owners": ["amazon"]
//!     }))
//!     .resource("aws_instance", "web", json!({
//!         "ami": "${data.aws_ami.latest.id}",
//!         "instance_type": "${var.instance_type}"
//!     }))
//!     .local("common_tags", json!({
//!         "Environment": "production",
//!         "ManagedBy": "terraform-wrapper"
//!     }))
//!     .module("vpc", json!({
//!         "source": "terraform-aws-modules/vpc/aws",
//!         "version": "~> 5.0",
//!         "cidr": "10.0.0.0/16"
//!     }))
//!     .output("instance_id", json!({
//!         "value": "${aws_instance.web.id}"
//!     }));
//!
//! let dir = config.write_to_tempdir()?;
//! // Terraform::builder().working_dir(dir.path()).build()?;
//! # Ok(())
//! # }
//! ```
//!
//! Enable with:
//! ```toml
//! terraform-wrapper = { version = "0.3", features = ["config"] }
//! ```
//!
//! # Feature Flags
//!
//! | Feature | Default | Description |
//! |---------|---------|-------------|
//! | `json` | Yes | Typed JSON output parsing via `serde` / `serde_json` |
//! | `config` | No | [`TerraformConfig`](config::TerraformConfig) builder for `.tf.json` generation |
//!
//! Disable defaults for raw command output only:
//!
//! ```toml
//! terraform-wrapper = { version = "0.3", default-features = false }
//! ```
//!
//! # OpenTofu Compatibility
//!
//! [OpenTofu](https://opentofu.org/) works out of the box by pointing the client
//! at the `tofu` binary:
//!
//! ```rust,no_run
//! # use terraform_wrapper::prelude::*;
//! # fn example() -> terraform_wrapper::error::Result<()> {
//! let tf = Terraform::builder()
//!     .binary("tofu")
//!     .working_dir("./infra")
//!     .build()?;
//! # Ok(())
//! # }
//! ```
//!
//! # Imports
//!
//! The [`prelude`] module re-exports everything you need:
//!
//! ```rust
//! use terraform_wrapper::prelude::*;
//! ```
//!
//! Or import selectively from [`commands`]:
//!
//! ```rust
//! use terraform_wrapper::{Terraform, TerraformCommand};
//! use terraform_wrapper::commands::{InitCommand, ApplyCommand, OutputCommand, OutputResult};
//! ```

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Duration;

pub mod command;
pub mod commands;
#[cfg(feature = "config")]
pub mod config;
pub mod error;
pub mod exec;
pub mod prelude;
#[cfg(feature = "json")]
pub mod streaming;
#[cfg(feature = "json")]
pub mod types;

pub use command::TerraformCommand;
pub use error::{Error, Result};
pub use exec::CommandOutput;

/// Terraform client configuration.
///
/// Holds the binary path, working directory, environment variables, and global
/// arguments shared across all command executions. Construct via
/// [`Terraform::builder()`].
#[derive(Debug, Clone)]
pub struct Terraform {
    pub(crate) binary: PathBuf,
    pub(crate) working_dir: Option<PathBuf>,
    pub(crate) env: HashMap<String, String>,
    /// Args applied to every subcommand (e.g., `-no-color`).
    pub(crate) global_args: Vec<String>,
    /// Whether to add `-input=false` to commands that support it.
    pub(crate) no_input: bool,
    /// Default timeout for command execution.
    pub(crate) timeout: Option<Duration>,
}

impl Terraform {
    /// Create a new [`TerraformBuilder`].
    #[must_use]
    pub fn builder() -> TerraformBuilder {
        TerraformBuilder::new()
    }

    /// Verify terraform is installed and return version info.
    #[cfg(feature = "json")]
    pub async fn version(&self) -> Result<types::version::VersionInfo> {
        commands::version::VersionCommand::new().execute(self).await
    }

    /// Create a clone of this client with a different working directory.
    ///
    /// Useful for running a single command against a different directory
    /// without modifying the original client:
    ///
    /// ```rust,no_run
    /// # use terraform_wrapper::prelude::*;
    /// # async fn example() -> terraform_wrapper::error::Result<()> {
    /// let tf = Terraform::builder()
    ///     .working_dir("./infra/network")
    ///     .build()?;
    ///
    /// // Run one command against a different directory
    /// let compute = tf.with_working_dir("./infra/compute");
    /// InitCommand::new().execute(&compute).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn with_working_dir(&self, path: impl AsRef<Path>) -> Self {
        let mut clone = self.clone();
        clone.working_dir = Some(path.as_ref().to_path_buf());
        clone
    }
}

/// Builder for constructing a [`Terraform`] client.
///
/// Defaults:
/// - Binary: resolved via `TERRAFORM_PATH` env var, or `terraform` on `PATH`
/// - `-no-color` enabled (disable with `.color(true)`)
/// - `-input=false` enabled (disable with `.input(true)`)
#[derive(Debug)]
pub struct TerraformBuilder {
    binary: Option<PathBuf>,
    working_dir: Option<PathBuf>,
    env: HashMap<String, String>,
    no_color: bool,
    input: bool,
    timeout: Option<Duration>,
}

impl TerraformBuilder {
    fn new() -> Self {
        Self {
            binary: None,
            working_dir: None,
            env: HashMap::new(),
            no_color: true,
            input: false,
            timeout: None,
        }
    }

    /// Set an explicit path to the terraform binary.
    #[must_use]
    pub fn binary(mut self, path: impl Into<PathBuf>) -> Self {
        self.binary = Some(path.into());
        self
    }

    /// Set the default working directory for all commands.
    ///
    /// This is passed as `-chdir=<path>` to terraform.
    #[must_use]
    pub fn working_dir(mut self, path: impl AsRef<Path>) -> Self {
        self.working_dir = Some(path.as_ref().to_path_buf());
        self
    }

    /// Set an environment variable for all terraform subprocesses.
    #[must_use]
    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.env.insert(key.into(), value.into());
        self
    }

    /// Set a Terraform variable via environment (`TF_VAR_<name>`).
    #[must_use]
    pub fn env_var(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.env
            .insert(format!("TF_VAR_{}", name.into()), value.into());
        self
    }

    /// Enable or disable color output (default: disabled for programmatic use).
    #[must_use]
    pub fn color(mut self, enable: bool) -> Self {
        self.no_color = !enable;
        self
    }

    /// Enable or disable interactive input prompts (default: disabled).
    #[must_use]
    pub fn input(mut self, enable: bool) -> Self {
        self.input = enable;
        self
    }

    /// Set a default timeout for all command executions.
    ///
    /// Commands that exceed this duration will be terminated and return
    /// [`Error::Timeout`]. No timeout is set by default.
    #[must_use]
    pub fn timeout(mut self, duration: Duration) -> Self {
        self.timeout = Some(duration);
        self
    }

    /// Set a default timeout in seconds for all command executions.
    #[must_use]
    pub fn timeout_secs(mut self, seconds: u64) -> Self {
        self.timeout = Some(Duration::from_secs(seconds));
        self
    }

    /// Build the [`Terraform`] client.
    ///
    /// Resolves the terraform binary in this order:
    /// 1. Explicit path set via [`.binary()`](TerraformBuilder::binary)
    /// 2. `TERRAFORM_PATH` environment variable
    /// 3. `terraform` found on `PATH`
    ///
    /// Returns [`Error::NotFound`] if the binary cannot be located.
    pub fn build(self) -> Result<Terraform> {
        let binary = if let Some(path) = self.binary {
            path
        } else if let Ok(path) = std::env::var("TERRAFORM_PATH") {
            PathBuf::from(path)
        } else {
            which::which("terraform").map_err(|_| Error::NotFound)?
        };

        let mut global_args = Vec::new();
        if self.no_color {
            global_args.push("-no-color".to_string());
        }

        Ok(Terraform {
            binary,
            working_dir: self.working_dir,
            env: self.env,
            global_args,
            no_input: !self.input,
            timeout: self.timeout,
        })
    }
}