关于 terraform-generator
terraform-generator 是一项用于按最佳实践生成 Terraform 配置的技能,面向基础设施配置工作。它要求查阅自定义 Provider 或模块文档、加入动态数据源与关键资源保护,并循环验证和修复问题。
主要功能
- 01按需求生成 Terraform 配置
- 02查询自定义 Provider 和模块文档
- 03遵循参考文件与安全实践
- 04加入动态数据源和生命周期保护
- 05运行验证并修复失败项
适用场景
- 01为云资源创建 Terraform 配置
- 02为第三方 Provider 或模块查阅用法
- 03检查配置语法与安全问题
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ akin-ozer/ cc-devops-skills --skill terraform-generator安装后在 Claude Code 中输入/terraform-generator确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
assets/README.mdassets/minimal-project/main.tfoutputs.tfREADME.mdterraform.tfvars.examplevariables.tfversions.tfreferences/common_patterns.mdprovider_examples.mdterraform_best_practices.mdscripts/check_feature_version_consistency.shrun_ci_checks.shtests/test_feature_version_consistency.sh详细介绍
Terraform 生成器
概述
此技能可根据最佳实践和当前标准生成可用于生产环境的 Terraform 配置,并自动集成自定义 provider 和模块的验证及文档查询。
关键要求清单
停止:必须按顺序完成所有步骤。不得跳过任何必需步骤。
| 步骤 | 操作 | 必需 |
|---|---|---|
| 1 | 了解需求(provider、资源、模块) | ✅ 必需 |
| 2 | 检查自定义 provider/模块并查询文档 | ✅ 必需 |
| 3 | 生成前查阅参考文件 | ✅ 必需 |
| 4 | 按照所有最佳实践生成 Terraform 文件 | ✅ 必需 |
| 5 | 为动态值(区域、账户、AMI)添加数据源 | ✅ 必需 |
| 6 | 为关键资源(KMS、数据库)添加生命周期规则 | ✅ 必需 |
| 7 | 调用 Skill(devops-skills:terraform-validator) | ✅ 必需 |
| 8 | 修复所有验证/安全问题并重新验证 | ✅ 必需 |
| 9 | 提供使用说明(文件、后续步骤、安全性) | ✅ 必需 |
重要: 如果验证失败(terraform validate 或安全扫描),必须修复问题并重新运行验证,直到所有检查均通过。检查未通过时,不得继续执行步骤 9。
核心工作流
生成 Terraform 配置时,请遵循以下工作流:
步骤 1:了解需求
分析用户的请求,确定:
- 需要创建哪些基础设施资源
- 需要哪些 Terraform provider(AWS、Azure、GCP、自定义等)
- 是否使用任何模块(官方、社区或自定义)
- provider 和模块的版本约束
- 所需的变量输入和输出
- 状态后端配置(本地、S3、远程等)
步骤 2:检查自定义 Provider/模块
生成配置前,确认是否涉及自定义或第三方 provider/模块:
标准 provider(无需查询):
- hashicorp/aws
- hashicorp/azurerm
- hashicorp/google
- hashicorp/kubernetes
- 其他 HashiCorp 官方 provider
自定义/第三方 provider/模块(需要查询文档):
- 第三方 provider(例如 datadog/datadog、mongodb/mongodbatlas)
- 来自 Terraform Registry 的自定义模块
- 私有或公司专用模块
- 社区模块
检测到自定义 provider/模块时:
-
使用 WebSearch 查找特定版本的文档:
Search query format: "[provider/module name] terraform [version] documentation [specific resource]" Example: "datadog terraform provider v3.30 monitor resource documentation" Example: "terraform-aws-modules vpc version 5.0 documentation" -
搜索重点:
- 官方文档(registry.terraform.io、provider 网站)
- 必需和可选参数
- 属性引用
- 使用示例
- 版本兼容性说明
-
如果 Context7 MCP 可用且支持该 provider/模块,可将其作为替代方案:
mcp__context7__resolve-library-id → mcp__context7__query-docs
步骤 2.5:查阅参考文件(必需)
生成配置前,必须根据以下矩阵查阅参考文件:
| 参考文件 | 要求 | 阅读时机 |
|---|---|---|
terraform_best_practices.md | 必需 | 始终——包含基础必需模式 |
provider_examples.md | 必需 | 生成任何 AWS、Azure、GCP 或 Kubernetes 资源时 |
common_patterns.md | 默认可选,复杂请求时必需 | 多环境、工作区、组合、DR 或条件模式 |
按路径打开参考文件:
devops-skills-plugin/skills/terraform-generator/references/terraform_best_practices.md
devops-skills-plugin/skills/terraform-generator/references/provider_examples.md
devops-skills-plugin/skills/terraform-generator/references/common_patterns.md
第 3 步:生成 Terraform 配置
遵循最佳实践生成 HCL 文件:
文件组织:
terraform-project/
├── main.tf # Primary resource definitions
├── variables.tf # Input variable declarations
├── outputs.tf # Output value declarations
├── versions.tf # Provider version constraints
├── terraform.tfvars # Variable values (optional, for examples)
└── backend.tf # Backend configuration (optional)
遵循以下最佳实践:
-
Provider 配置:
terraform { required_version = ">= 1.10, < 2.0" required_providers { aws = { source = "hashicorp/aws" version = "~> 6.0" # Major pin; verify exact current version when needed } } } provider "aws" { region = var.aws_region } -
资源命名:
- 使用描述性资源名称
- 遵循 snake_case 命名规范
- 在有帮助时,将资源类型包含在名称中
resource "aws_instance" "web_server" { # ... } -
变量声明:
variable "instance_type" { description = "EC2 instance type for web servers" type = string default = "t3.micro" validation { condition = contains(["t3.micro", "t3.small", "t3.medium"], var.instance_type) error_message = "Instance type must be t3.micro, t3.small, or t3.medium." } } -
输出值:
output "instance_public_ip" { description = "Public IP address of the web server" value = aws_instance.web_server.public_ip } -
使用数据源进行引用:
data "aws_ami" "ubuntu" { most_recent = true owners = ["099720109477"] # Canonical filter { name = "name" values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"] } } -
模块用法:
module "vpc" { source = "terraform-aws-modules/vpc/aws" version = "5.0.0" name = "my-vpc" cidr = "10.0.0.0/16" azs = ["us-east-1a", "us-east-1b"] private_subnets = ["10.0.1.0/24", "10.0.2.0/24"] public_subnets = ["10.0.101.0/24", "10.0.102.0/24"] } -
使用 locals 保存计算值:
locals { common_tags = { Environment = var.environment ManagedBy = "Terraform" Project = var.project_name } } -
适当时使用生命周期规则:
resource "aws_instance" "example" { # ... lifecycle { create_before_destroy = true prevent_destroy = true ignore_changes = [tags] } } -
使用动态块处理重复配置:
resource "aws_security_group" "example" { # ... dynamic "ingress" { for_each = var.ingress_rules content { from_port = ingress.value.from_port to_port = ingress.value.to_port protocol = ingress.value.protocol cidr_blocks = ingress.value.cidr_blocks } } } -
注释和文档:
- 添加注释,解释复杂逻辑
- 说明使用特定值的原因
- 在变量描述中加入示例
安全最佳实践:
- 切勿硬编码敏感值(使用变量)
- 使用数据源获取 AMI 和其他动态值
- 实施最小权限 IAM 策略
- 默认启用加密
- 使用安全的后端配置
必需:用于动态值的数据源(因 Provider 而异)
必须包含适用于相应 Provider 的数据查询,以获取动态基础设施值。不要硬编码云、账户、区域或映像 ID。
| Provider | 必需的动态上下文 | 典型数据源 |
|---|---|---|
| AWS | 区域/账户/可用区/映像 ID | aws_region、aws_caller_identity、aws_availability_zones、aws_ami |
| Azure | 租户/订阅/客户端上下文 | azurerm_client_config、azurerm_subscription |
| GCP | 项目/客户端上下文/可用区发现 | google_client_config、google_compute_zones、google_compute_image |
| Kubernetes | 来自可信来源的集群端点/身份验证信息 | 使用模块输出或云数据源;避免硬编码令牌/端点 |
# AWS dynamic context
data "aws_region" "current" {}
data "aws_caller_identity" "current" {}
# Azure dynamic context
data "azurerm_client_config" "current" {}
data "azurerm_subscription" "current" {}
# GCP dynamic context
data "google_client_config" "current" {}
必需:生命周期和删除防护(因 Provider 而异)
必须同时使用 Terraform 生命周期和 Provider 原生防护机制,防止有状态资源和关键资源被意外销毁/删除。
| Provider | 关键资源类别 | 必需的防护机制 |
|---|---|---|
| AWS | KMS、RDS、S3 数据存储桶、DynamoDB、ElastiCache、密钥 | lifecycle { prevent_destroy = true },并在支持时启用特定服务的删除保护 |
| Azure | Key Vault、SQL、Storage、有状态计算资源 | 适当使用 prevent_destroy,并启用 Provider 功能标志/资源删除保护 |
| GCP | Cloud SQL、GKE、存储、有状态计算资源 | 使用 prevent_destroy,并在支持时设置资源级别的 deletion_protection = true |
| Kubernetes | 有状态工作负载和持久化数据 | 避免破坏性替换模式,并保护底层云资源 |
resource "aws_db_instance" "main" {
# ...
deletion_protection = true
lifecycle {
prevent_destroy = true
}
}
resource "google_sql_database_instance" "main" {
# ...
deletion_protection = true
}
必需:对象存储生命周期防护
使用 AWS S3 生命周期配置时,始终加入一条规则,用于中止未完成的分段上传:
resource "aws_s3_bucket_lifecycle_configuration" "main" {
bucket = aws_s3_bucket.main.id
# REQUIRED: Abort incomplete multipart uploads to prevent storage costs
rule {
id = "abort-incomplete-uploads"
status = "Enabled"
# Filter applies to all objects (empty filter = all objects)
filter {}
abort_incomplete_multipart_upload {
days_after_initiation = 7
}
}
# Other lifecycle rules (e.g., transition to IA)
rule {
id = "transition-to-ia"
status = "Enabled"
filter {
prefix = "" # Apply to all objects
}
transition {
days = 90
storage_class = "STANDARD_IA"
}
noncurrent_version_transition {
noncurrent_days = 30
storage_class = "STANDARD_IA"
}
noncurrent_version_expiration {
noncurrent_days = 365
}
}
}
原因? 未完成的分段上传会占用存储空间并产生费用。Checkov 检查
CKV_AWS_300会对此进行强制检查。对于 Azure/GCP 对象存储,请添加相应的生命周期/保留规则,以处理过期对象和旧版本。
步骤 4:验证生成的配置(必需)
生成 Terraform 文件后,始终使用 devops-skills:terraform-validator 技能进行验证:
Invoke: Skill(devops-skills:terraform-validator)
devops-skills:terraform-validator 技能将:
- 使用
terraform fmt -check检查 HCL 语法 - 使用
terraform init初始化配置 - 使用
terraform validate验证配置 - 使用 Checkov 运行安全扫描
- 执行试运行测试(如果有要求),使用
terraform plan
重要:修复并重新验证循环
如果任何验证或安全检查失败,你必须:
- 检查错误——了解失败的内容及原因
- 修复问题——编辑生成的文件以解决问题
- 重新运行验证——再次调用
Skill(devops-skills:terraform-validator) - 重复操作,直到所有检查均通过——检查未通过时,不得继续
┌─────────────────────────────────────────────────────────┐
│ VALIDATION FAILED? │
│ │
│ ┌─────────┐ ┌─────────┐ ┌─────────────────────┐ │
│ │ Fix │───▶│ Re-run │───▶│ All checks pass? │ │
│ │ Issue │ │ Skill │ │ YES → Step 5 │ │
│ └─────────┘ └─────────┘ │ NO → Loop back │ │
│ ▲ └─────────────────────┘ │
│ │ │ │
│ └────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
需要修复的常见验证失败:
| 检查 | 问题 | 修复方法 |
|---|---|---|
CKV_AWS_300 | 缺少中止分段上传的配置 | 添加 abort_incomplete_multipart_upload 规则 |
CKV_AWS_24 | SSH 对 0.0.0.0/0 开放 | 限制为特定 CIDR |
CKV_AWS_16 | RDS 加密已禁用 | 添加 storage_encrypted = true |
terraform validate | 资源参数无效 | 查看提供程序文档 |
如果在验证期间检测到自定义提供程序:
- devops-skills:terraform-validator 技能会自动获取文档
- 使用获取的文档修复任何问题
步骤 5:提供使用说明(必需)
成功生成配置并通过所有检查的验证后,你必须向用户提供:
必需的输出格式:
## Generated Files
| File | Description |
|------|-------------|
| `<actual-file-path>` | What was generated in that file |
Only list files that were actually generated for this request. Do not include placeholder paths or files that do not exist.
## Next Steps
1. Review and customize `terraform.tfvars` with your values
2. Initialize Terraform:
```bash
terraform init
- 查看执行计划:
terraform plan - 应用配置:
terraform apply
自定义说明
- 更新 terraform.tfvars 中的
variable_name - 在 backend.tf 中配置远程状态后端
- 根据需要调整资源名称/标签
安全提醒
⚠️ 应用之前:
- 检查 IAM 策略和权限
- 确保敏感值不会提交到版本控制中
- 配置启用加密的状态后端
- 设置状态锁定,以便团队协作
> **IMPORTANT:** Do NOT skip Step 5. The user needs actionable guidance on how to use the generated configuration.
## Common Generation Patterns
### Pattern 1: Simple Resource Creation
User request: "Create an AWS S3 bucket with versioning"
Generated files:
- `main.tf` - S3 bucket resource with versioning enabled
- `variables.tf` - Bucket name, tags variables
- `outputs.tf` - Bucket ARN and name outputs
- `versions.tf` - AWS provider version constraints
### Pattern 2: Module-Based Infrastructure
User request: "Set up a VPC using the official AWS VPC module"
Actions:
1. Identify module: terraform-aws-modules/vpc/aws
2. Web search for latest version and documentation
3. Generate configuration using module with appropriate inputs
4. Validate with devops-skills:terraform-validator
### Pattern 3: Multi-Provider Configuration
User request: "Create infrastructure across AWS and Datadog"
Actions:
1. Identify standard provider (AWS) and custom provider (Datadog)
2. Web search for Datadog provider documentation with version
3. Generate configuration with both providers properly configured
4. Ensure provider aliases if needed
5. Validate with devops-skills:terraform-validator
### Pattern 4: Complex Resource with Dependencies
User request: "Create an ECS cluster with ALB and auto-scaling"
Generated structure:
- Multiple resource blocks with proper dependencies
- Data sources for AMIs, availability zones, etc.
- Local values for computed configurations
- Comprehensive variables and outputs
- Proper dependency management using implicit references
## Error Handling
**Common Issues and Solutions:**
1. **Provider Not Found:**
- Ensure provider is listed in `required_providers` block
- Verify source address format: `namespace/name`
- Check version constraint syntax
2. **Invalid Resource Arguments:**
- Refer to web search results for custom providers
- Check for required vs optional arguments
- Verify attribute value types (string, number, bool, list, map)
3. **Circular Dependencies:**
- Review resource references
- Use `depends_on` explicit dependencies if needed
- Consider breaking into separate modules
4. **Validation Failures:**
- Run devops-skills:terraform-validator skill to get detailed errors
- Fix issues one at a time
- Re-validate after each fix
## Version Awareness
Always consider version compatibility:
1. **Terraform Version:**
- Use `required_version` constraint with both lower and upper bounds
- If generated configuration includes write-only arguments (`*_wo`): use `required_version = ">= 1.11, < 2.0"`.
- Else if it uses ephemeral constructs (`ephemeral` blocks, ephemeral variables/outputs) without write-only arguments: use `required_version = ">= 1.10, < 2.0"`.
- Else use the project baseline (default `>= 1.8, < 2.0` unless repository policy requires newer).
- Use `>= 1.14, < 2.0` for latest features (actions, query command)
- Document any version-specific features used (see below)
2. **Provider Version Policy (canonical):**
- Pin provider major versions with `~>` constraints (for example `~> 6.0`, `~> 4.0`, `~> 7.0`).
- Do not claim "latest" version unless verified online during the current run.
- Keep cross-provider guidance consistent:
- AWS family: major-pin policy (for example `~> 6.0`)
- AzureRM: major-pin policy (for example `~> 4.0`)
- Google: major-pin policy (for example `~> 7.0`)
- Kubernetes: major/minor pin based on target cluster/provider compatibility
- Use the same provider/version language in `SKILL.md`, `references/terraform_best_practices.md`, and template `assets/minimal-project/versions.tf`.
3. **Module Versions:**
- Always pin module versions
- Review module documentation for version compatibility
- Test module updates in non-production first
### Required Version Decision Table
| Generated Output Contains | Required Version to Emit |
|---------------------------|--------------------------|
| Any write-only argument (`*_wo`) | `>= 1.11, < 2.0` |
| Ephemeral constructs only (no write-only) | `>= 1.10, < 2.0` |
| Neither write-only nor ephemeral | Project baseline (default `>= 1.8, < 2.0`) |
#### Feature-Gating Examples
```hcl
# Positive: write-only usage requires Terraform 1.11+
terraform {
required_version = ">= 1.11, < 2.0"
}
ephemeral "random_password" "db_password" {
length = 16
}
resource "aws_db_instance" "main" {
identifier = "mydb"
instance_class = "db.t3.micro"
allocated_storage = 20
engine = "postgres"
username = "admin"
skip_final_snapshot = true
password_wo = ephemeral.random_password.db_password.result
password_wo_version = 1
}
# Negative: reject this pattern (write-only with Terraform 1.10)
terraform {
required_version = ">= 1.10, < 2.0"
}
resource "aws_db_instance" "invalid" {
password_wo = "do-not-generate-this"
}
Terraform 版本功能矩阵
| 功能 | 最低版本 |
|---|---|
terraform_data 资源 | 1.4+ |
import {} 块 | 1.5+ |
check {} 块 | 1.5+ |
原生测试(.tftest.hcl) | 1.6+ |
| 测试模拟 | 1.7+ |
removed {} 块 | 1.7+ |
| 提供程序定义的函数 | 1.8+ |
| 跨类型重构 | 1.8+ |
| 增强的变量验证 | 1.9+ |
templatestring 函数 | 1.9+ |
| 临时资源 | 1.10+ |
| 只写参数 | 1.11+ |
| S3 原生状态锁定 | 1.11+ |
带 for_each 的导入块 | 1.12+ |
| Actions 块 | 1.14+ |
列出资源(tfquery.hcl) | 1.14+ |
terraform query 命令 | 1.14+ |
现代 Terraform 功能(1.8+)
提供程序定义的函数(Terraform 1.8+)
提供程序定义的函数通过提供程序专属逻辑扩展 Terraform 内置函数。
语法: provider::<provider_name>::<function_name>(arguments)
# AWS Provider Functions (v5.40+)
locals {
# Parse an ARN into components
parsed_arn = provider::aws::arn_parse(aws_instance.web.arn)
account_id = local.parsed_arn.account
region = local.parsed_arn.region
# Build an ARN from components
custom_arn = provider::aws::arn_build({
partition = "aws"
service = "s3"
region = ""
account = ""
resource = "my-bucket/my-key"
})
}
# Google Cloud Provider Functions (v5.23+)
locals {
# Extract region from zone
region = provider::google::region_from_zone(var.zone) # "us-west1-a" → "us-west1"
}
# Kubernetes Provider Functions (v2.28+)
locals {
# Encode HCL to Kubernetes manifest YAML
manifest_yaml = provider::kubernetes::manifest_encode(local.deployment_config)
}
临时资源(Terraform 1.10+)
临时资源提供不会持久保存在状态文件或计划文件中的临时值。它们对于安全处理机密至关重要。
# Generate a password that never touches state
ephemeral "random_password" "db_password" {
length = 16
special = true
override_special = "!#$%&*()-_=+[]{}<>:?"
}
# Fetch secrets ephemerally from AWS Secrets Manager
ephemeral "aws_secretsmanager_secret_version" "api_key" {
secret_id = aws_secretsmanager_secret.api_key.id
}
# Ephemeral variables (declare with ephemeral = true)
variable "temporary_token" {
type = string
ephemeral = true # Value won't be stored in state
}
# Ephemeral outputs
output "session_token" {
value = ephemeral.aws_secretsmanager_secret_version.api_key.secret_string
ephemeral = true # Won't be stored in state
}
只写参数(Terraform 1.11+)
只写参数接受临时值,且不会持久保存。它们使用 _wo 后缀,并要求提供版本属性。
terraform {
required_version = ">= 1.11, < 2.0"
}
# Secure database password handling
ephemeral "random_password" "db_password" {
length = 16
}
resource "aws_db_instance" "main" {
identifier = "mydb"
instance_class = "db.t3.micro"
allocated_storage = 20
engine = "postgres"
username = "admin"
# Write-only password - never stored in state!
password_wo = ephemeral.random_password.db_password.result
password_wo_version = 1 # Increment to trigger password rotation
skip_final_snapshot = true
}
# Secrets Manager with write-only
resource "aws_secretsmanager_secret_version" "db_password" {
secret_id = aws_secretsmanager_secret.db_password.id
# Write-only secret string
secret_string_wo = ephemeral.random_password.db_password.result
secret_string_wo_version = 1
}
增强的变量验证(Terraform 1.9+)
验证条件现在可以引用其他变量、数据源和本地值。
# Reference data sources in validation
data "aws_ec2_instance_type_offerings" "available" {
filter {
name = "location"
values = [var.availability_zone]
}
}
variable "instance_type" {
type = string
description = "EC2 instance type"
validation {
# NEW: Can reference data sources
condition = contains(
data.aws_ec2_instance_type_offerings.available.instance_types,
var.instance_type
)
error_message = "Instance type ${var.instance_type} is not available in the selected AZ."
}
}
# Cross-variable validation
variable "min_instances" {
type = number
default = 1
}
variable "max_instances" {
type = number
default = 10
validation {
# NEW: Can reference other variables
condition = var.max_instances >= var.min_instances
error_message = "max_instances must be >= min_instances"
}
}
S3 原生状态锁定(Terraform 1.11+)
S3 现在支持原生状态锁定,无需 DynamoDB。
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "project/terraform.tfstate"
region = "us-east-1"
encrypt = true
# NEW: S3-native locking (Terraform 1.11+)
use_lockfile = true
# DEPRECATED: DynamoDB locking (still works but no longer required)
# dynamodb_table = "terraform-locks"
}
}
导入块(Terraform 1.5+)
以声明方式导入资源,无需执行命令行操作。
# Import existing resources declaratively
import {
to = aws_instance.web
id = "i-1234567890abcdef0"
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
# ... configuration must match existing resource
}
# Import with for_each
import {
for_each = var.existing_bucket_names
to = aws_s3_bucket.imported[each.key]
id = each.value
}
移动块和移除块
安全地重构资源,而不销毁它们。
# Rename a resource
moved {
from = aws_instance.old_name
to = aws_instance.new_name
}
# Move to a module
moved {
from = aws_vpc.main
to = module.networking.aws_vpc.main
}
# Cross-type refactoring (1.8+)
moved {
from = null_resource.example
to = terraform_data.example
}
# Remove resource from state without destroying (1.7+)
removed {
from = aws_instance.legacy
lifecycle {
destroy = false # Keep the actual resource, just remove from state
}
}
使用 for_each 导入块(Terraform 1.12+)
使用 for_each 元参数导入多个资源。
# Import multiple S3 buckets using a map
locals {
buckets = {
"staging" = "bucket1"
"uat" = "bucket2"
"prod" = "bucket3"
}
}
import {
for_each = local.buckets
to = aws_s3_bucket.this[each.key]
id = each.value
}
resource "aws_s3_bucket" "this" {
for_each = local.buckets
}
# Import across module instances using list of objects
locals {
module_buckets = [
{ group = "one", key = "bucket1", id = "one_1" },
{ group = "one", key = "bucket2", id = "one_2" },
{ group = "two", key = "bucket1", id = "two_1" },
]
}
import {
for_each = local.module_buckets
id = each.value.id
to = module.group[each.value.group].aws_s3_bucket.this[each.value.key]
}
Actions 块(Terraform 1.14+)
Actions 支持在标准 CRUD 模型之外执行由提供程序定义的操作。可用于 Lambda 调用、缓存失效或数据库备份等操作。
# Invoke a Lambda function (example syntax)
action "aws_lambda_invoke" "process_data" {
function_name = aws_lambda_function.processor.function_name
payload = jsonencode({ action = "process" })
}
# Create CloudFront invalidation
action "aws_cloudfront_create_invalidation" "invalidate_cache" {
distribution_id = aws_cloudfront_distribution.main.id
paths = ["/*"]
}
# Actions support for_each
action "aws_lambda_invoke" "batch_process" {
for_each = toset(["task1", "task2", "task3"])
function_name = aws_lambda_function.processor.function_name
payload = jsonencode({ task = each.value })
}
通过生命周期触发 Actions:
在资源的生命周期块中使用 action_trigger,即可自动调用 Actions:
resource "aws_lambda_function" "example" {
function_name = "my-function"
# ... other config ...
lifecycle {
action_trigger {
events = [after_create, after_update]
actions = [action.aws_lambda_invoke.process_data]
}
}
}
action "aws_lambda_invoke" "process_data" {
function_name = aws_lambda_function.example.function_name
payload = jsonencode({ action = "initialize" })
}
手动调用:
也可以通过 CLI 手动调用 Actions:
terraform apply -invoke action.aws_lambda_invoke.process_data
List Resources 和 Query 命令(Terraform 1.14+)
使用 .tfquery.hcl 文件和 terraform query 命令查询并筛选现有基础设施。
# my-resources.tfquery.hcl
# Define list resources to query existing infrastructure
list "aws_instance" "web_servers" {
filter {
name = "tag:Environment"
values = [var.environment]
}
include_resource = true # Include full resource details
}
list "aws_s3_bucket" "data_buckets" {
filter {
name = "tag:Purpose"
values = ["data-storage"]
}
}
# Query infrastructure and output results
terraform query
# Generate import configuration from query results
terraform query -generate-config-out="import_config.tf"
# Output in JSON format
terraform query -json
# Use with variables
terraform query -var 'environment=prod'
前置条件和后置条件(Terraform 1.5+)
在资源生命周期中添加自定义验证。
resource "aws_instance" "example" {
instance_type = "t3.micro"
ami = data.aws_ami.example.id
lifecycle {
# Check before creation
precondition {
condition = data.aws_ami.example.architecture == "x86_64"
error_message = "The selected AMI must be for the x86_64 architecture."
}
# Verify after creation
postcondition {
condition = self.public_dns != ""
error_message = "EC2 instance must be in a VPC that has public DNS hostnames enabled."
}
}
}
# Preconditions on outputs
output "web_url" {
value = "https://${aws_instance.web.public_dns}"
precondition {
condition = aws_instance.web.public_dns != ""
error_message = "Instance must have a public DNS name."
}
}
资源
references/
references/ 目录包含详细的参考文档:
terraform_best_practices.md- 全面的最佳实践指南common_patterns.md- 常见 Terraform 模式和示例provider_examples.md- 主流提供程序的配置示例
可通过相对路径直接打开参考文档:
devops-skills-plugin/skills/terraform-generator/references/[filename].md
assets/
assets/ 目录包含模板文件:
minimal-project/- 最小 Terraform 项目模板
可根据用户的具体需求复制并自定义这些模板。
注意事项
- 生成后务必运行 devops-skills:terraform-validator
- 如需在 CI 中检查功能/版本偏差,请运行
bash scripts/run_ci_checks.sh - 对于自定义提供程序/模块,网络搜索至关重要
- 配置应遵循最小意外原则
- 确保配置易于阅读和维护
- 添加有帮助的注释和文档
- 适时在 terraform.tfvars 中生成切合实际的示例