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
use terraform_wrapper::commands::apply::ApplyCommand;
use terraform_wrapper::commands::destroy::DestroyCommand;
use terraform_wrapper::commands::fmt::FmtCommand;
use terraform_wrapper::commands::init::InitCommand;
use terraform_wrapper::commands::output::{OutputCommand, OutputResult};
use terraform_wrapper::commands::plan::PlanCommand;
use terraform_wrapper::commands::show::{ShowCommand, ShowResult};
use terraform_wrapper::commands::state::StateCommand;
use terraform_wrapper::commands::validate::ValidateCommand;
use terraform_wrapper::commands::workspace::WorkspaceCommand;
use terraform_wrapper::{Terraform, TerraformCommand};

fn setup_terraform(dir: &std::path::Path) -> Option<Terraform> {
    Terraform::builder().working_dir(dir).build().ok()
}

/// Write a minimal Terraform config using null_resource (no cloud provider needed).
fn write_null_config(dir: &std::path::Path) {
    let main_tf = r#"
terraform {
  required_providers {
    null = {
      source  = "hashicorp/null"
      version = "~> 3.0"
    }
  }
}

resource "null_resource" "example" {
  triggers = {
    value = var.trigger_value
  }
}

variable "trigger_value" {
  default = "hello"
}

output "trigger" {
  value = var.trigger_value
}

output "id" {
  value = null_resource.example.id
}
"#;
    std::fs::write(dir.join("main.tf"), main_tf).unwrap();
}

#[tokio::test]
async fn init_plan_apply_output_destroy() {
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path();

    let Some(tf) = setup_terraform(dir) else {
        eprintln!("terraform not found, skipping test");
        return;
    };

    write_null_config(dir);

    // Init
    let init_output = InitCommand::new().execute(&tf).await.unwrap();
    assert!(init_output.success);

    // Plan with detailed exit code (exit code 2 = changes present)
    let plan_output = PlanCommand::new()
        .out("tfplan")
        .detailed_exitcode()
        .execute(&tf)
        .await
        .unwrap();
    assert_eq!(plan_output.exit_code, 2);

    // Apply saved plan
    let apply_output = ApplyCommand::new()
        .plan_file("tfplan")
        .execute(&tf)
        .await
        .unwrap();
    assert!(apply_output.success);

    // Output - JSON all
    let result = OutputCommand::new().json().execute(&tf).await.unwrap();
    match result {
        OutputResult::Json(ref outputs) => {
            assert!(outputs.contains_key("trigger"));
            assert!(outputs.contains_key("id"));
            assert_eq!(
                outputs["trigger"].value,
                serde_json::Value::String("hello".into())
            );
        }
        _ => panic!("expected Json variant"),
    }

    // Output - raw single value
    let result = OutputCommand::new()
        .name("trigger")
        .raw()
        .execute(&tf)
        .await
        .unwrap();
    match result {
        OutputResult::Raw(ref value) => {
            assert_eq!(value, "hello");
        }
        _ => panic!("expected Raw variant"),
    }

    // Plan again (should show no changes)
    let plan_output = PlanCommand::new().execute(&tf).await.unwrap();
    assert_eq!(plan_output.exit_code, 0);

    // Destroy
    let destroy_output = DestroyCommand::new()
        .auto_approve()
        .execute(&tf)
        .await
        .unwrap();
    assert!(destroy_output.success);
}

#[tokio::test]
async fn init_with_upgrade() {
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path();

    let Some(tf) = setup_terraform(dir) else {
        eprintln!("terraform not found, skipping test");
        return;
    };

    write_null_config(dir);

    // First init
    InitCommand::new().execute(&tf).await.unwrap();

    // Init with upgrade
    let output = InitCommand::new().upgrade().execute(&tf).await.unwrap();
    assert!(output.success);
}

#[tokio::test]
async fn apply_with_var_override() {
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path();

    let Some(tf) = setup_terraform(dir) else {
        eprintln!("terraform not found, skipping test");
        return;
    };

    write_null_config(dir);
    InitCommand::new().execute(&tf).await.unwrap();

    ApplyCommand::new()
        .auto_approve()
        .var("trigger_value", "custom")
        .execute(&tf)
        .await
        .unwrap();

    let result = OutputCommand::new()
        .name("trigger")
        .raw()
        .execute(&tf)
        .await
        .unwrap();
    match result {
        OutputResult::Raw(ref value) => assert_eq!(value, "custom"),
        _ => panic!("expected Raw variant"),
    }

    DestroyCommand::new()
        .auto_approve()
        .execute(&tf)
        .await
        .unwrap();
}

#[tokio::test]
async fn validate_valid_config() {
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path();

    let Some(tf) = setup_terraform(dir) else {
        eprintln!("terraform not found, skipping test");
        return;
    };

    write_null_config(dir);
    InitCommand::new().execute(&tf).await.unwrap();

    let result = ValidateCommand::new().execute(&tf).await.unwrap();
    assert!(result.valid);
    assert_eq!(result.error_count, 0);
}

#[tokio::test]
async fn validate_invalid_config() {
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path();

    let Some(tf) = setup_terraform(dir) else {
        eprintln!("terraform not found, skipping test");
        return;
    };

    // Write invalid config (reference to nonexistent resource)
    let bad_tf = r#"
output "bad" {
  value = nonexistent_resource.foo.id
}
"#;
    std::fs::write(dir.join("main.tf"), bad_tf).unwrap();

    let result = ValidateCommand::new().execute(&tf).await.unwrap();
    assert!(!result.valid);
    assert!(result.error_count > 0);
    assert!(!result.diagnostics.is_empty());
}

#[tokio::test]
async fn show_current_state() {
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path();

    let Some(tf) = setup_terraform(dir) else {
        eprintln!("terraform not found, skipping test");
        return;
    };

    write_null_config(dir);
    InitCommand::new().execute(&tf).await.unwrap();
    ApplyCommand::new()
        .auto_approve()
        .execute(&tf)
        .await
        .unwrap();

    let result = ShowCommand::new().execute(&tf).await.unwrap();
    match result {
        ShowResult::State(state) => {
            assert_eq!(state.format_version, "1.0");
            assert!(!state.terraform_version.is_empty());
            assert_eq!(state.values.root_module.resources.len(), 1);
            assert_eq!(
                state.values.root_module.resources[0].address,
                "null_resource.example"
            );
            assert!(state.values.outputs.contains_key("trigger"));
        }
        _ => panic!("expected State variant"),
    }

    DestroyCommand::new()
        .auto_approve()
        .execute(&tf)
        .await
        .unwrap();
}

#[tokio::test]
async fn show_saved_plan() {
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path();

    let Some(tf) = setup_terraform(dir) else {
        eprintln!("terraform not found, skipping test");
        return;
    };

    write_null_config(dir);
    InitCommand::new().execute(&tf).await.unwrap();
    PlanCommand::new().out("tfplan").execute(&tf).await.unwrap();

    let result = ShowCommand::new()
        .plan_file("tfplan")
        .execute(&tf)
        .await
        .unwrap();
    match result {
        ShowResult::Plan(plan) => {
            assert!(!plan.terraform_version.is_empty());
            assert_eq!(plan.resource_changes.len(), 1);
            assert_eq!(plan.resource_changes[0].address, "null_resource.example");
            assert_eq!(plan.resource_changes[0].change.actions, vec!["create"]);
            assert!(plan.applyable);
        }
        _ => panic!("expected Plan variant"),
    }
}

#[tokio::test]
async fn fmt_check_formatted() {
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path();

    let Some(tf) = setup_terraform(dir) else {
        eprintln!("terraform not found, skipping test");
        return;
    };

    write_null_config(dir);

    let output = FmtCommand::new().check().execute(&tf).await.unwrap();
    assert_eq!(output.exit_code, 0);
}

#[tokio::test]
async fn fmt_check_unformatted() {
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path();

    let Some(tf) = setup_terraform(dir) else {
        eprintln!("terraform not found, skipping test");
        return;
    };

    let ugly_tf = "resource\"null_resource\"\"x\"{\n}\n";
    std::fs::write(dir.join("main.tf"), ugly_tf).unwrap();

    let output = FmtCommand::new().check().execute(&tf).await.unwrap();
    assert_eq!(output.exit_code, 3);
}

#[tokio::test]
async fn workspace_lifecycle() {
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path();

    let Some(tf) = setup_terraform(dir) else {
        eprintln!("terraform not found, skipping test");
        return;
    };

    write_null_config(dir);
    InitCommand::new().execute(&tf).await.unwrap();

    let output = WorkspaceCommand::show().execute(&tf).await.unwrap();
    assert_eq!(output.stdout.trim(), "default");

    WorkspaceCommand::new_workspace("test-ws")
        .execute(&tf)
        .await
        .unwrap();

    let output = WorkspaceCommand::show().execute(&tf).await.unwrap();
    assert_eq!(output.stdout.trim(), "test-ws");

    let output = WorkspaceCommand::list().execute(&tf).await.unwrap();
    assert!(output.stdout.contains("default"));
    assert!(output.stdout.contains("test-ws"));

    WorkspaceCommand::select("default")
        .execute(&tf)
        .await
        .unwrap();

    WorkspaceCommand::delete("test-ws")
        .execute(&tf)
        .await
        .unwrap();
}

#[tokio::test]
async fn state_list_and_show() {
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path();

    let Some(tf) = setup_terraform(dir) else {
        eprintln!("terraform not found, skipping test");
        return;
    };

    write_null_config(dir);
    InitCommand::new().execute(&tf).await.unwrap();
    ApplyCommand::new()
        .auto_approve()
        .execute(&tf)
        .await
        .unwrap();

    let output = StateCommand::list().execute(&tf).await.unwrap();
    assert!(output.stdout.contains("null_resource.example"));

    let output = StateCommand::show("null_resource.example")
        .execute(&tf)
        .await
        .unwrap();
    assert!(output.stdout.contains("null_resource.example"));

    DestroyCommand::new()
        .auto_approve()
        .execute(&tf)
        .await
        .unwrap();
}

#[tokio::test]
async fn timeout_triggers_error() {
    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path();

    // Build client with an impossibly short timeout
    let tf = match Terraform::builder()
        .working_dir(dir)
        .timeout(std::time::Duration::from_nanos(1))
        .build()
    {
        Ok(tf) => tf,
        Err(_) => {
            eprintln!("terraform not found, skipping test");
            return;
        }
    };

    write_null_config(dir);

    let result = InitCommand::new().execute(&tf).await;
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        matches!(err, terraform_wrapper::Error::Timeout { .. }),
        "expected Timeout error, got: {err:?}"
    );
}

#[tokio::test]
async fn with_working_dir_override() {
    let tmp1 = tempfile::tempdir().unwrap();
    let tmp2 = tempfile::tempdir().unwrap();

    let Some(tf) = setup_terraform(tmp1.path()) else {
        eprintln!("terraform not found, skipping test");
        return;
    };

    // Write config only in the second directory
    write_null_config(tmp2.path());

    // Init should fail on tmp1 (no config), but succeed on tmp2 via override
    let tf2 = tf.with_working_dir(tmp2.path());
    let output = InitCommand::new().execute(&tf2).await.unwrap();
    assert!(output.success);

    // Validate the override worked by checking the original is unchanged
    let result = ValidateCommand::new().no_json().execute(&tf).await;
    assert!(result.is_err()); // No config in tmp1
}

#[tokio::test]
async fn streaming_apply() {
    use terraform_wrapper::streaming::{JsonLogLine, stream_terraform};

    let tmp = tempfile::tempdir().unwrap();
    let dir = tmp.path();

    let Some(tf) = setup_terraform(dir) else {
        eprintln!("terraform not found, skipping test");
        return;
    };

    write_null_config(dir);
    InitCommand::new().execute(&tf).await.unwrap();

    let mut events: Vec<JsonLogLine> = Vec::new();
    let result = stream_terraform(
        &tf,
        ApplyCommand::new().auto_approve().json(),
        &[0],
        |line| {
            events.push(line);
        },
    )
    .await
    .unwrap();

    assert!(result.success);
    assert!(!events.is_empty());

    // Should have version, planned_change, change_summary, apply_start, apply_complete, etc.
    let types: Vec<&str> = events.iter().map(|e| e.log_type.as_str()).collect();
    assert!(types.contains(&"version"));
    assert!(types.contains(&"apply_complete"));
    assert!(types.contains(&"change_summary"));

    DestroyCommand::new()
        .auto_approve()
        .execute(&tf)
        .await
        .unwrap();
}

#[cfg(feature = "config")]
#[tokio::test]
async fn config_builder_lifecycle() {
    use terraform_wrapper::config::TerraformConfig;

    let config = TerraformConfig::new()
        .required_provider("null", "hashicorp/null", "~> 3.0")
        .resource(
            "null_resource",
            "example",
            serde_json::json!({ "triggers": { "v": "1" } }),
        )
        .output(
            "id",
            serde_json::json!({ "value": "${null_resource.example.id}" }),
        );

    let dir = config.write_to_tempdir().unwrap();
    let tf = match Terraform::builder().working_dir(dir.path()).build() {
        Ok(tf) => tf,
        Err(_) => {
            eprintln!("terraform not found, skipping test");
            return;
        }
    };

    InitCommand::new().execute(&tf).await.unwrap();
    ApplyCommand::new()
        .auto_approve()
        .execute(&tf)
        .await
        .unwrap();

    let result = OutputCommand::new()
        .name("id")
        .raw()
        .execute(&tf)
        .await
        .unwrap();
    match result {
        OutputResult::Raw(ref id) => assert!(!id.is_empty()),
        _ => panic!("expected Raw variant"),
    }

    DestroyCommand::new()
        .auto_approve()
        .execute(&tf)
        .await
        .unwrap();
}