Token导航 LogoToken导航TokenDH.com
研究检索external-serviceclawhub未标认证来源可访问clear审计提醒

terraform-skillTerraform 技能

Agent Skill

用于辅助云资源、部署、容器、基础设施和运维自动化任务。它适合让 Agent 检查配置、整理部署步骤、分析资源状态、生成排障思路或辅助云服务接入。使用时需要明确目标环境、账号权限、区域和资源组,区分本地测试与生产操作;涉及删除资源、重启服务、修改网络或权限配置时,应先确认影响范围。

总安装

3,998

周安装

170

GitHub Stars

公开资料未说明

下载量

1,401
OpenClaw

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

MIT-0

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:terraform-skill(Terraform 技能)
来源仓库:https://github.com/jimmy974/terraform-skill
安装命令:
openclaw skills install terraform-skill
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 OpenClaw 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

ClawHubOpenClaw
openclaw skills install terraform-skill

简介

辅助 Terraform 或 OpenTofu 基础设施即代码项目的开发运维。

  • 涵盖模块创建、测试编写、CI/CD 集成及配置审查全流程。
  • 提供本机测试框架支持与安全合规性检查建议。
  • 操作前务必核对目标云平台凭证与环境变量配置准确性。
  • terraform-skill 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

name
terraform-skill
description
Use when working with Terraform or OpenTofu - creating modules, writing tests (native test framework, Terratest), setting up CI/CD pipelines, reviewing configurations, choosing between testing approaches, debugging state issues, implementing security scanning (trivy, checkov), or making infrastructure-as-code architecture decisions
license
Apache-2.0
metadata
author
Anton Babenko
version
1.6.0

Terraform Skill for Claude

Comprehensive Terraform and OpenTofu guidance covering testing, modules, CI/CD, and production patterns. Based on terraform-best-practices.com and enterprise experience.

When to Use This Skill

Activate this skill when:

  • Creating new Terraform or OpenTofu configurations or modules
  • Setting up testing infrastructure for IaC code
  • Deciding between testing approaches (validate, plan, frameworks)
  • Structuring multi-environment deployments
  • Implementing CI/CD for infrastructure-as-code
  • Reviewing or refactoring existing Terraform/OpenTofu projects
  • Choosing between module patterns or state management approaches

Don't use this skill for:

  • Basic Terraform/OpenTofu syntax questions (Claude knows this)
  • Provider-specific API reference (link to docs instead)
  • Cloud platform questions unrelated to Terraform/OpenTofu

Core Principles

1. Code Structure Philosophy

Module Hierarchy:

TypeWhen to UseScope
Resource ModuleSingle logical group of connected resourcesVPC + subnets, Security group + rules
Infrastructure ModuleCollection of resource modules for a purposeMultiple resource modules in one region/account
CompositionComplete infrastructureSpans multiple regions/accounts

Hierarchy: Resource → Resource Module → Infrastructure Module → Composition

Directory Structure:

environments/        # Environment-specific configurations
├── prod/
├── staging/
└── dev/

modules/            # Reusable modules
├── networking/
├── compute/
└── data/

examples/           # Module usage examples (also serve as tests)
├── complete/
└── minimal/

Key principle from terraform-best-practices.com:

  • Separate environments (prod, staging) from modules (reusable components)
  • Use examples/ as both documentation and integration test fixtures
  • Keep modules small and focused (single responsibility)

For detailed module architecture, see: Code Patterns: Module Types & Hierarchy

2. Naming Conventions

Resources:

# Good: Descriptive, contextual
resource "aws_instance" "web_server" { }
resource "aws_s3_bucket" "application_logs" { }

# Good: "this" for singleton resources (only one of that type)
resource "aws_vpc" "this" { }
resource "aws_security_group" "this" { }

# Avoid: Generic names for non-singletons
resource "aws_instance" "main" { }
resource "aws_s3_bucket" "bucket" { }

Singleton Resources:

Use "this" when your module creates only one resource of that type:

✅ DO:

resource "aws_vpc" "this" {}           # Module creates one VPC
resource "aws_security_group" "this" {}  # Module creates one SG

❌ DON'T use "this" for multiple resources:

resource "aws_subnet" "this" {}  # If creating multiple subnets

Use descriptive names when creating multiple resources of the same type.

Variables:

# Prefix with context when needed
var.vpc_cidr_block          # Not just "cidr"
var.database_instance_class # Not just "instance_class"

Files:

  • main.tf - Primary resources
  • variables.tf - Input variables
  • outputs.tf - Output values
  • versions.tf - Provider versions
  • data.tf - Data sources (optional)

Testing Strategy Framework

Decision Matrix: Which Testing Approach?

Your SituationRecommended ApproachToolsCost
Quick syntax checkStatic analysisterraform validate, fmtFree
Pre-commit validationStatic + lintvalidate, tflint, trivy, checkovFree
Terraform 1.6+, simple logicNative test frameworkBuilt-in terraform testFree-Low
Pre-1.6, or Go expertiseIntegration testingTerratestLow-Med
Security/compliance focusPolicy as codeOPA, SentinelFree
Cost-sensitive workflowMock providers (1.7+)Native tests + mockingFree
Multi-cloud, complexFull integrationTerratest + real infraMed-High

Testing Pyramid for Infrastructure

        /\
       /  \          End-to-End Tests (Expensive)
      /____\         - Full environment deployment
     /      \        - Production-like setup
    /________\
   /          \      Integration Tests (Moderate)
  /____________\     - Module testing in isolation
 /              \    - Real resources in test account
/________________\   Static Analysis (Cheap)
                     - validate, fmt, lint
                     - Security scanning

Native Test Best Practices (1.6+)

Before generating test code:

  1. Validate schemas with Terraform MCP:
   Search provider docs → Get resource schema → Identify block types
  1. Choose correct command mode:

- command = plan - Fast, for input validation - command = apply - Required for computed values and set-type blocks

  1. Handle set-type blocks correctly:

- Cannot index with [0] - Use for expressions to iterate - Or use command = apply to materialize

Common patterns:

  • S3 encryption rules: set (use for expressions)
  • Lifecycle transitions: set (use for expressions)
  • IAM policy statements: set (use for expressions)

For detailed testing guides, see:

Code Structure Standards

Resource Block Ordering

Strict ordering for consistency:

  1. count or for_each FIRST (blank line after)
  2. Other arguments
  3. tags as last real argument
  4. depends_on after tags (if needed)
  5. lifecycle at the very end (if needed)
# ✅ GOOD - Correct ordering
resource "aws_nat_gateway" "this" {
  count = var.create_nat_gateway ? 1 : 0

  allocation_id = aws_eip.this[0].id
  subnet_id     = aws_subnet.public[0].id

  tags = {
    Name = "${var.name}-nat"
  }

  depends_on = [aws_internet_gateway.this]

  lifecycle {
    create_before_destroy = true
  }
}

Variable Block Ordering

  1. description (ALWAYS required)
  2. type
  3. default
  4. validation
  5. nullable (when setting to false)
variable "environment" {
  description = "Environment name for resource tagging"
  type        = string
  default     = "dev"

  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "Environment must be one of: dev, staging, prod."
  }

  nullable = false
}

For complete structure guidelines, see: Code Patterns: Block Ordering & Structure

Count vs For_Each: When to Use Each

Quick Decision Guide

ScenarioUseWhy
Boolean condition (create or don't)count = condition ? 1 : 0Simple on/off toggle
Simple numeric replicationcount = 3Fixed number of identical resources
Items may be reordered/removedfor_each = toset(list)Stable resource addresses
Reference by keyfor_each = mapNamed access to resources
Multiple named resourcesfor_eachBetter maintainability

Common Patterns

Boolean conditions:

# ✅ GOOD - Boolean condition
resource "aws_nat_gateway" "this" {
  count = var.create_nat_gateway ? 1 : 0
  # ...
}

Stable addressing with for_each:

# ✅ GOOD - Removing "us-east-1b" only affects that subnet
resource "aws_subnet" "private" {
  for_each = toset(var.availability_zones)

  availability_zone = each.key
  # ...
}

# ❌ BAD - Removing middle AZ recreates all subsequent subnets
resource "aws_subnet" "private" {
  count = length(var.availability_zones)

  availability_zone = var.availability_zones[count.index]
  # ...
}

For migration guides and detailed examples, see: Code Patterns: Count vs For_Each

Locals for Dependency Management

Use locals to ensure correct resource deletion order:

# Problem: Subnets might be deleted after CIDR blocks, causing errors
# Solution: Use try() in locals to hint deletion order

locals {
  # References secondary CIDR first, falling back to VPC
  # Forces Terraform to delete subnets before CIDR association
  vpc_id = try(
    aws_vpc_ipv4_cidr_block_association.this[0].vpc_id,
    aws_vpc.this.id,
    ""
  )
}

resource "aws_vpc" "this" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_vpc_ipv4_cidr_block_association" "this" {
  count = var.add_secondary_cidr ? 1 : 0

  vpc_id     = aws_vpc.this.id
  cidr_block = "10.1.0.0/16"
}

resource "aws_subnet" "public" {
  vpc_id     = local.vpc_id  # Uses local, not direct reference
  cidr_block = "10.1.0.0/24"
}

Why this matters:

  • Prevents deletion errors when destroying infrastructure
  • Ensures correct dependency order without explicit depends_on
  • Particularly useful for VPC configurations with secondary CIDR blocks

For detailed examples, see: Code Patterns: Locals for Dependency Management

Module Development

Standard Module Structure

my-module/
├── README.md           # Usage documentation
├── main.tf             # Primary resources
├── variables.tf        # Input variables with descriptions
├── outputs.tf          # Output values
├── versions.tf         # Provider version constraints
├── examples/
│   ├── minimal/        # Minimal working example
│   └── complete/       # Full-featured example
└── tests/              # Test files
    └── module_test.tftest.hcl  # Or .go

Best Practices Summary

Variables:

  • ✅ Always include description
  • ✅ Use explicit type constraints
  • ✅ Provide sensible default values where appropriate
  • ✅ Add validation blocks for complex constraints
  • ✅ Use sensitive = true for secrets

Outputs:

  • ✅ Always include description
  • ✅ Mark sensitive outputs with sensitive = true
  • ✅ Consider returning objects for related values
  • ✅ Document what consumers should do with each output

For detailed module patterns, see:

CI/CD Integration

Recommended Workflow Stages

  1. Validate - Format check + syntax validation + linting
  2. Test - Run automated tests (native or Terratest)
  3. Plan - Generate and review execution plan
  4. Apply - Execute changes (with approvals for production)

Cost Optimization Strategy

  1. Use mocking for PR validation (free)
  2. Run integration tests only on main branch (controlled cost)
  3. Implement auto-cleanup (prevent orphaned resources)
  4. Tag all test resources (track spending)

For complete CI/CD templates, see:

Security & Compliance

Essential Security Checks

# Static security scanning
trivy config .
checkov -d .

Common Issues to Avoid

Don't:

  • Store secrets in variables
  • Use default VPC
  • Skip encryption
  • Open security groups to 0.0.0.0/0

Do:

  • Use AWS Secrets Manager / Parameter Store
  • Create dedicated VPCs
  • Enable encryption at rest
  • Use least-privilege security groups

For detailed security guidance, see:

Version Management

Version Constraint Syntax

version = "5.0.0"      # Exact (avoid - inflexible)
version = "~> 5.0"     # Recommended: 5.0.x only
version = ">= 5.0"     # Minimum (risky - breaking changes)

Strategy by Component

ComponentStrategyExample
TerraformPin minor versionrequired_version = "~> 1.9"
ProvidersPin major versionversion = "~> 5.0"
Modules (prod)Pin exact versionversion = "5.1.2"
Modules (dev)Allow patch updatesversion = "~> 5.1"

Update Workflow

# Lock versions initially
terraform init              # Creates .terraform.lock.hcl

# Update to latest within constraints
terraform init -upgrade     # Updates providers

# Review and test
terraform plan

For detailed version management, see: Code Patterns: Version Management

Modern Terraform Features (1.0+)

Feature Availability by Version

FeatureVersionUse Case
try() function0.13+Safe fallbacks, replaces element(concat())
nullable = false1.1+Prevent null values in variables
moved blocks1.1+Refactor without destroy/recreate
optional() with defaults1.3+Optional object attributes
Native testing1.6+Built-in test framework
Mock providers1.7+Cost-free unit testing
Provider functions1.8+Provider-specific data transformation
Cross-variable validation1.9+Validate relationships between variables
Write-only arguments1.11+Secrets never stored in state

Quick Examples

# try() - Safe fallbacks (0.13+)
output "sg_id" {
  value = try(aws_security_group.this[0].id, "")
}

# optional() - Optional attributes with defaults (1.3+)
variable "config" {
  type = object({
    name    = string
    timeout = optional(number, 300)  # Default: 300
  })
}

# Cross-variable validation (1.9+)
variable "environment" { type = string }
variable "backup_days" {
  type = number
  validation {
    condition     = var.environment == "prod" ? var.backup_days >= 7 : true
    error_message = "Production requires backup_days >= 7"
  }
}

For complete patterns and examples, see: Code Patterns: Modern Terraform Features

Version-Specific Guidance

Terraform 1.0-1.5

  • Use Terratest for testing
  • No native testing framework available
  • Focus on static analysis and plan validation

Terraform 1.6+ / OpenTofu 1.6+

  • New: Native terraform test / tofu test command
  • Consider migrating from external frameworks for simple tests
  • Keep Terratest only for complex integration tests

Terraform 1.7+ / OpenTofu 1.7+

  • New: Mock providers for unit testing
  • Reduce cost by mocking external dependencies
  • Use real integration tests for final validation

Terraform vs OpenTofu

Both are fully supported by this skill. For licensing, governance, and feature comparison, see Quick Reference: Terraform vs OpenTofu.

Detailed Guides

This skill uses progressive disclosure - essential information is in this main file, detailed guides are available when needed:

📚 Reference Files:

  • Testing Frameworks - In-depth guide to static analysis, native tests, and Terratest
  • Module Patterns - Module structure, variable/output best practices, ✅ DO vs ❌ DON'T patterns
  • CI/CD Workflows - GitHub Actions, GitLab CI templates, cost optimization, automated cleanup
  • Security & Compliance - Trivy/Checkov integration, secrets management, compliance testing
  • Quick Reference - Command cheat sheets, decision flowcharts, troubleshooting guide

How to use: When you need detailed information on a topic, reference the appropriate guide. Claude will load it on demand to provide comprehensive guidance.

License

This skill is licensed under the Apache License 2.0. See the LICENSE file for full terms.

Copyright © 2026 Anton Babenko

适合场景

01

OpenClaw 用户查找和安装 Skill 时

02

用户想查找某类 Agent Skill 时

03

需要根据任务场景推荐可安装能力包时

04

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

OpenClaw

95.27%
按下载量换算1,335

安全审计

VirusTotal

通过

ClawScan

通过

Static analysis

可疑

权限和风险

external-service

该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills