name: terraform-analyzer description: 用于分析Terraform配置的专项技能。支持解析、安全扫描(tfsec、checkov)、成本估算(infracost)、漂移检测以及跨AWS、Azure和GCP的计划可视化。 allowed-tools: Bash(*) Read Write Edit Glob Grep WebFetch metadata: author: babysitter-sdk version: “1.0.0” category: infrastructure-as-code backlog-id: SK-SA-005
terraform-analyzer
您是 terraform-analyzer - 一个用于分析Terraform配置和基础设施即代码的专项技能。此技能支持对基础设施进行AI驱动的安全、成本和合规性分析。
概述
此技能支持全面的Terraform分析,包括:
- 解析和验证Terraform配置
- 使用tfsec、checkov、terrascan进行安全扫描
- 使用infracost进行成本估算
- 检测状态与实际配置之间的漂移
- 计划可视化和变更分析
- 支持AWS、Azure、GCP提供商
先决条件
- 已安装Terraform CLI(v1.0+)
- 可选:tfsec、checkov、terrascan、infracost
- 用于计划/应用的提供商凭据
能力
1. Terraform配置解析
解析和分析Terraform配置:
# 正在分析的示例配置
resource "aws_instance" "web" {
ami = var.ami_id
instance_type = var.instance_type
vpc_security_group_ids = [aws_security_group.web.id]
subnet_id = aws_subnet.private.id
root_block_device {
volume_size = 100
volume_type = "gp3"
encrypted = true
}
tags = {
Name = "web-server"
Environment = var.environment
}
}
resource "aws_security_group" "web" {
name = "web-sg"
description = "Web服务器的安全组"
vpc_id = aws_vpc.main.id
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"] # 安全发现:对全世界开放
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
2. 安全扫描
tfsec分析
# 运行tfsec安全扫描
tfsec . --format json --out tfsec-report.json
# 示例发现
{
"results": [
{
"rule_id": "aws-vpc-no-public-ingress-sgr",
"severity": "CRITICAL",
"description": "安全组规则允许来自公共互联网的入口流量",
"resource": "aws_security_group.web",
"location": {
"filename": "security.tf",
"start_line": 15
},
"resolution": "将入口流量限制到特定的CIDR块"
}
]
}
Checkov分析
# 运行Checkov安全和合规性扫描
checkov -d . --output json > checkov-report.json
# 示例发现
{
"passed": 45,
"failed": 3,
"skipped": 0,
"results": {
"failed_checks": [
{
"check_id": "CKV_AWS_23",
"check_name": "确保每个安全组规则都有描述",
"resource": "aws_security_group.web",
"guideline": "https://docs.bridgecrew.io/docs/..."
},
{
"check_id": "CKV_AWS_24",
"check_name": "确保没有安全组允许从0.0.0.0:0到端口22的入口流量",
"resource": "aws_security_group.web"
}
]
}
}
Terrascan分析
# 运行Terrascan策略扫描
terrascan scan -d . -o json > terrascan-report.json
3. 成本估算
使用Infracost进行成本分析:
# 生成成本明细
infracost breakdown --path . --format json > cost-report.json
# 示例输出
{
"version": "0.2",
"currency": "USD",
"projects": [
{
"name": "production",
"breakdown": {
"resources": [
{
"name": "aws_instance.web",
"monthlyQuantity": 730,
"unit": "hours",
"hourlyRate": "0.0416",
"monthlyCost": "30.37"
},
{
"name": "aws_ebs_volume.data",
"monthlyQuantity": 100,
"unit": "GB",
"monthlyCost": "10.00"
}
],
"totalMonthlyCost": "540.37",
"totalHourlyCost": "0.74"
}
}
],
"totalMonthlyCost": "540.37"
}
4. 漂移检测
检测配置漂移:
# 刷新并检查漂移
terraform plan -refresh-only -json > drift-report.json
# 示例漂移检测
{
"resource_drift": [
{
"resource": "aws_instance.web",
"address": "aws_instance.web",
"changes": {
"before": {
"instance_type": "t3.medium"
},
"after": {
"instance_type": "t3.large"
},
"drift_reason": "通过控制台手动更改"
}
}
],
"summary": {
"total_resources": 45,
"drifted_resources": 1,
"unchanged_resources": 44
}
}
5. 计划可视化
分析和可视化Terraform计划:
# 生成计划
terraform plan -out=tfplan
terraform show -json tfplan > plan.json
# 计划分析输出
{
"format_version": "1.0",
"resource_changes": [
{
"address": "aws_instance.web",
"mode": "managed",
"type": "aws_instance",
"name": "web",
"change": {
"actions": ["update"],
"before": {
"instance_type": "t3.small"
},
"after": {
"instance_type": "t3.medium"
}
}
}
],
"summary": {
"add": 2,
"change": 1,
"destroy": 0
}
}
6. 模块分析
分析Terraform模块结构:
// 模块依赖分析
{
"modules": {
"root": {
"path": ".",
"source": "local",
"version": null,
"dependencies": ["./modules/vpc", "./modules/compute"]
},
"vpc": {
"path": "./modules/vpc",
"source": "local",
"resources": ["aws_vpc", "aws_subnet", "aws_route_table"]
},
"compute": {
"path": "./modules/compute",
"source": "local",
"resources": ["aws_instance", "aws_autoscaling_group"],
"depends_on": ["vpc"]
}
},
"external_modules": [
{
"source": "terraform-aws-modules/vpc/aws",
"version": "5.0.0",
"registry": "registry.terraform.io"
}
]
}
7. 合规性检查
检查是否符合组织策略:
# 策略定义
policies:
- name: require-encryption
description: 所有存储必须加密
resource_types: [aws_ebs_volume, aws_rds_instance, aws_s3_bucket]
rules:
- attribute: encrypted
value: true
- attribute: storage_encrypted
value: true
- name: require-tags
description: 所有资源必须具有必需的标签
rules:
- attribute: tags
contains: [Environment, Owner, CostCenter]
- name: restrict-instance-types
description: 仅允许批准的实例类型
resource_types: [aws_instance]
rules:
- attribute: instance_type
allowed_values: [t3.micro, t3.small, t3.medium, t3.large]
MCP服务器集成
此技能可以利用以下MCP服务器:
| 服务器 | 描述 | 安装 |
|---|---|---|
| Terraform MCP服务器 (HashiCorp) | 官方Terraform注册表集成 | GitHub |
| AWS Terraform MCP服务器 | 带有Checkov和AWS最佳实践的Terraform | AWS Labs |
最佳实践
安全扫描工作流
workflow:
pre_commit:
- terraform fmt -check
- terraform validate
- tfsec --minimum-severity HIGH
ci_pipeline:
- terraform init
- terraform validate
- tfsec --format sarif
- checkov -d . --output sarif
- infracost breakdown --path .
pre_deploy:
- terraform plan -out=tfplan
- infracost diff --path tfplan
- manual_review_required: true
推荐阈值
security_thresholds:
tfsec:
max_critical: 0
max_high: 0
max_medium: 5
checkov:
min_passed_percentage: 90
infracost:
max_monthly_increase_percentage: 20
require_approval_above: 1000 # 美元
流程集成
此技能与以下流程集成:
iac-review.js- 主要的IaC分析工作流cloud-architecture-design.js- 架构验证devops-architecture-alignment.js- DevOps集成
输出格式
分析配置时,提供结构化输出:
{
"operation": "analyze",
"status": "completed",
"configuration": {
"path": "./infrastructure",
"provider": "aws",
"resources": 45,
"modules": 5
},
"security": {
"tool": "tfsec",
"findings": {
"critical": 0,
"high": 2,
"medium": 5,
"low": 8
},
"passed": true,
"threshold_exceeded": false
},
"compliance": {
"tool": "checkov",
"passed": 42,
"failed": 3,
"skipped": 0,
"passed_percentage": 93.3
},
"cost": {
"tool": "infracost",
"monthly_estimate": "$540.37",
"hourly_estimate": "$0.74",
"change_from_baseline": "+$45.00"
},
"drift": {
"detected": true,
"resources_drifted": 1,
"total_resources": 45
},
"artifacts": [
"tfsec-report.json",
"checkov-report.json",
"cost-report.json"
],
"recommendations": [
{
"priority": "high",
"category": "security",
"description": "限制安全组入口规则",
"resource": "aws_security_group.web"
}
]
}
错误处理
常见错误
| 错误 | 原因 | 解决方案 |
|---|---|---|
Provider not configured |
缺少凭据 | 配置提供商凭据 |
Module not found |
无效的源路径 | 检查模块源配置 |
State lock error |
并发访问 | 等待或强制解锁 |
Validation failed |
无效的HCL语法 | 修复语法错误 |
约束
- 每次变更都运行安全扫描
- 生产环境需要成本估算
- 阻止具有严重发现的部署
- 记录所有策略例外
- 定期审查漂移报告