tfmcp 0.1.9

Terraform Model Context Protocol Tool - A CLI tool to manage Terraform through MCP
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
//! State analyzer for Terraform state analysis with drift detection.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Resource statistics grouped by provider
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ProviderStats {
    pub name: String,
    pub resource_count: i32,
    pub resource_types: Vec<String>,
}

/// Resource statistics grouped by type
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TypeStats {
    pub resource_type: String,
    pub count: i32,
    pub addresses: Vec<String>,
}

/// Drift detection result for a single resource
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DriftResult {
    pub address: String,
    pub resource_type: String,
    pub drift_type: DriftType,
    pub details: Option<String>,
}

/// Type of drift detected
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DriftType {
    /// Resource exists in state but may be modified in cloud
    Modified,
    /// Resource exists in state but not in cloud (deleted externally)
    Deleted,
    /// Resource exists in cloud but not in state (created externally)
    Orphaned,
    /// Resource configuration differs from state
    ConfigurationDrift,
}

/// Health check result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthCheck {
    pub name: String,
    pub status: HealthStatus,
    pub message: String,
}

/// Health status
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum HealthStatus {
    Healthy,
    Warning,
    Critical,
}

/// Resource in state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateResource {
    pub address: String,
    pub resource_type: String,
    pub provider: String,
    pub module: Option<String>,
    pub tainted: bool,
    pub attributes: Option<serde_json::Value>,
}

/// Complete state analysis result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateAnalysis {
    pub total_resources: i32,
    pub providers: Vec<ProviderStats>,
    pub types: Vec<TypeStats>,
    pub resources: Vec<StateResource>,
    pub drift_results: Vec<DriftResult>,
    pub health_checks: Vec<HealthCheck>,
    pub state_version: Option<i32>,
    pub terraform_version: Option<String>,
    pub serial: Option<i64>,
}

/// Terraform state JSON structure
#[derive(Debug, Deserialize)]
struct TerraformStateJson {
    version: Option<i32>,
    terraform_version: Option<String>,
    serial: Option<i64>,
    resources: Option<Vec<StateResourceJson>>,
}

#[derive(Debug, Deserialize)]
struct StateResourceJson {
    #[serde(rename = "type")]
    resource_type: String,
    name: String,
    provider: String,
    module: Option<String>,
    instances: Option<Vec<StateInstance>>,
}

#[derive(Debug, Deserialize)]
struct StateInstance {
    attributes: Option<serde_json::Value>,
    #[serde(default)]
    status: Option<String>,
    index_key: Option<serde_json::Value>,
}

/// Analyze terraform state
pub fn analyze_state(
    state_json: &str,
    resource_type_filter: Option<&str>,
    detect_drift: bool,
) -> anyhow::Result<StateAnalysis> {
    let state: TerraformStateJson = serde_json::from_str(state_json)?;

    let mut resources = Vec::new();
    let mut provider_map: HashMap<String, ProviderStats> = HashMap::new();
    let mut type_map: HashMap<String, TypeStats> = HashMap::new();

    if let Some(state_resources) = state.resources {
        for resource in state_resources {
            // Apply type filter if specified
            if let Some(filter) = resource_type_filter {
                if !resource.resource_type.contains(filter) {
                    continue;
                }
            }

            let provider_name = extract_provider_name(&resource.provider);

            // Process each instance of the resource
            if let Some(instances) = resource.instances {
                for (idx, instance) in instances.iter().enumerate() {
                    let address = if instances.len() == 1 {
                        format_address(&resource.module, &resource.resource_type, &resource.name)
                    } else if let Some(ref key) = instance.index_key {
                        format!(
                            "{}[{}]",
                            format_address(
                                &resource.module,
                                &resource.resource_type,
                                &resource.name
                            ),
                            key
                        )
                    } else {
                        format!(
                            "{}[{}]",
                            format_address(
                                &resource.module,
                                &resource.resource_type,
                                &resource.name
                            ),
                            idx
                        )
                    };

                    let tainted = instance.status.as_ref().is_some_and(|s| s == "tainted");

                    resources.push(StateResource {
                        address: address.clone(),
                        resource_type: resource.resource_type.clone(),
                        provider: provider_name.clone(),
                        module: resource.module.clone(),
                        tainted,
                        attributes: instance.attributes.clone(),
                    });

                    // Update provider stats
                    let provider_stats =
                        provider_map
                            .entry(provider_name.clone())
                            .or_insert_with(|| ProviderStats {
                                name: provider_name.clone(),
                                resource_count: 0,
                                resource_types: Vec::new(),
                            });
                    provider_stats.resource_count += 1;
                    if !provider_stats
                        .resource_types
                        .contains(&resource.resource_type)
                    {
                        provider_stats
                            .resource_types
                            .push(resource.resource_type.clone());
                    }

                    // Update type stats
                    let type_stats = type_map
                        .entry(resource.resource_type.clone())
                        .or_insert_with(|| TypeStats {
                            resource_type: resource.resource_type.clone(),
                            count: 0,
                            addresses: Vec::new(),
                        });
                    type_stats.count += 1;
                    type_stats.addresses.push(address);
                }
            }
        }
    }

    let drift_results = if detect_drift {
        detect_drift_issues(&resources)
    } else {
        Vec::new()
    };

    let health_checks = run_health_checks(&resources, &provider_map);

    let mut providers: Vec<ProviderStats> = provider_map.into_values().collect();
    providers.sort_by(|a, b| b.resource_count.cmp(&a.resource_count));

    let mut types: Vec<TypeStats> = type_map.into_values().collect();
    types.sort_by(|a, b| b.count.cmp(&a.count));

    Ok(StateAnalysis {
        total_resources: resources.len() as i32,
        providers,
        types,
        resources,
        drift_results,
        health_checks,
        state_version: state.version,
        terraform_version: state.terraform_version,
        serial: state.serial,
    })
}

/// Format resource address
fn format_address(module: &Option<String>, resource_type: &str, name: &str) -> String {
    match module {
        Some(m) if !m.is_empty() => format!("{}.{}.{}", m, resource_type, name),
        _ => format!("{}.{}", resource_type, name),
    }
}

/// Extract provider name from provider string (e.g., "provider[\"registry.terraform.io/hashicorp/aws\"]")
fn extract_provider_name(provider: &str) -> String {
    if provider.contains('/') {
        // Extract from full provider path
        provider
            .rsplit('/')
            .next()
            .unwrap_or(provider)
            .trim_end_matches(']')
            .trim_end_matches('"')
            .to_string()
    } else {
        provider.to_string()
    }
}

/// Detect potential drift issues (heuristic-based)
fn detect_drift_issues(resources: &[StateResource]) -> Vec<DriftResult> {
    let mut drift_results = Vec::new();

    for resource in resources {
        // Check for tainted resources
        if resource.tainted {
            drift_results.push(DriftResult {
                address: resource.address.clone(),
                resource_type: resource.resource_type.clone(),
                drift_type: DriftType::Modified,
                details: Some("Resource is marked as tainted".to_string()),
            });
        }

        // Check for resources without attributes (may indicate issues)
        if resource.attributes.is_none() {
            drift_results.push(DriftResult {
                address: resource.address.clone(),
                resource_type: resource.resource_type.clone(),
                drift_type: DriftType::ConfigurationDrift,
                details: Some("Resource has no attributes in state".to_string()),
            });
        }

        // Check for data sources that might have stale data
        if resource.resource_type.starts_with("data.") {
            drift_results.push(DriftResult {
                address: resource.address.clone(),
                resource_type: resource.resource_type.clone(),
                drift_type: DriftType::ConfigurationDrift,
                details: Some(
                    "Data source may have stale data - run refresh to update".to_string(),
                ),
            });
        }
    }

    drift_results
}

/// Run health checks on the state
fn run_health_checks(
    resources: &[StateResource],
    providers: &HashMap<String, ProviderStats>,
) -> Vec<HealthCheck> {
    let mut checks = Vec::new();

    // Check for empty state
    if resources.is_empty() {
        checks.push(HealthCheck {
            name: "state_not_empty".to_string(),
            status: HealthStatus::Warning,
            message: "State is empty - no resources are being managed".to_string(),
        });
    } else {
        checks.push(HealthCheck {
            name: "state_not_empty".to_string(),
            status: HealthStatus::Healthy,
            message: format!("State contains {} resources", resources.len()),
        });
    }

    // Check for tainted resources
    let tainted_count = resources.iter().filter(|r| r.tainted).count();
    if tainted_count > 0 {
        checks.push(HealthCheck {
            name: "no_tainted_resources".to_string(),
            status: HealthStatus::Warning,
            message: format!(
                "{} tainted resources found - they will be recreated on next apply",
                tainted_count
            ),
        });
    } else {
        checks.push(HealthCheck {
            name: "no_tainted_resources".to_string(),
            status: HealthStatus::Healthy,
            message: "No tainted resources found".to_string(),
        });
    }

    // Check for resources in modules
    let module_resources = resources.iter().filter(|r| r.module.is_some()).count();
    if module_resources > 0 && resources.len() > 10 {
        let percentage = (module_resources as f64 / resources.len() as f64) * 100.0;
        if percentage < 50.0 {
            checks.push(HealthCheck {
                name: "module_usage".to_string(),
                status: HealthStatus::Warning,
                message: format!(
                    "Only {:.0}% of resources are in modules - consider modularizing",
                    percentage
                ),
            });
        } else {
            checks.push(HealthCheck {
                name: "module_usage".to_string(),
                status: HealthStatus::Healthy,
                message: format!("{:.0}% of resources are organized in modules", percentage),
            });
        }
    }

    // Check for provider diversity (potential complexity)
    if providers.len() > 5 {
        checks.push(HealthCheck {
            name: "provider_count".to_string(),
            status: HealthStatus::Warning,
            message: format!(
                "{} providers in use - consider if all are necessary",
                providers.len()
            ),
        });
    } else {
        checks.push(HealthCheck {
            name: "provider_count".to_string(),
            status: HealthStatus::Healthy,
            message: format!("{} providers in use", providers.len()),
        });
    }

    checks
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_provider_name() {
        assert_eq!(
            extract_provider_name("provider[\"registry.terraform.io/hashicorp/aws\"]"),
            "aws"
        );
        assert_eq!(extract_provider_name("aws"), "aws");
    }

    #[test]
    fn test_format_address() {
        assert_eq!(
            format_address(&None, "aws_instance", "example"),
            "aws_instance.example"
        );
        assert_eq!(
            format_address(&Some("module.vpc".to_string()), "aws_subnet", "public"),
            "module.vpc.aws_subnet.public"
        );
    }

    #[test]
    fn test_analyze_empty_state() {
        let state_json = r#"{"version": 4, "terraform_version": "1.5.0", "resources": []}"#;
        let result = analyze_state(state_json, None, false).unwrap();
        assert_eq!(result.total_resources, 0);
        assert_eq!(result.state_version, Some(4));
    }

    #[test]
    fn test_analyze_state_with_resources() {
        let state_json = r#"{
            "version": 4,
            "terraform_version": "1.5.0",
            "serial": 123,
            "resources": [
                {
                    "type": "aws_instance",
                    "name": "example",
                    "provider": "provider[\"registry.terraform.io/hashicorp/aws\"]",
                    "instances": [
                        {"attributes": {"id": "i-12345"}}
                    ]
                }
            ]
        }"#;
        let result = analyze_state(state_json, None, false).unwrap();
        assert_eq!(result.total_resources, 1);
        assert_eq!(result.resources[0].address, "aws_instance.example");
        assert_eq!(result.resources[0].provider, "aws");
    }

    #[test]
    fn test_type_filter() {
        let state_json = r#"{
            "version": 4,
            "resources": [
                {
                    "type": "aws_instance",
                    "name": "web",
                    "provider": "aws",
                    "instances": [{"attributes": {}}]
                },
                {
                    "type": "aws_s3_bucket",
                    "name": "storage",
                    "provider": "aws",
                    "instances": [{"attributes": {}}]
                }
            ]
        }"#;
        let result = analyze_state(state_json, Some("s3"), false).unwrap();
        assert_eq!(result.total_resources, 1);
        assert!(result.resources[0].resource_type.contains("s3"));
    }
}