Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:29:21 +08:00
commit 91ec8d924a
6 changed files with 2755 additions and 0 deletions

View File

@@ -0,0 +1,645 @@
## 🚨 CRITICAL GUIDELINES
### Windows File Path Requirements
**MANDATORY: Always Use Backslashes on Windows for File Paths**
When using Edit or Write tools on Windows, you MUST use backslashes (`\`) in file paths, NOT forward slashes (`/`).
**Examples:**
- ❌ WRONG: `D:/repos/project/file.tsx`
- ✅ CORRECT: `D:\repos\project\file.tsx`
This applies to:
- Edit tool file_path parameter
- Write tool file_path parameter
- All file operations on Windows systems
### Documentation Guidelines
**NEVER create new documentation files unless explicitly requested by the user.**
- **Priority**: Update existing README.md files rather than creating new documentation
- **Repository cleanliness**: Keep repository root clean - only README.md unless user requests otherwise
- **Style**: Documentation should be concise, direct, and professional - avoid AI-generated tone
- **User preference**: Only create additional .md files when user specifically asks for documentation
---
# OpenTofu Expertise and Migration Guide
## Overview
OpenTofu is the open-source fork of Terraform, created in 2023 after HashiCorp changed Terraform's license from MPL 2.0 to BSL (Business Source License). OpenTofu is stewarded by the Linux Foundation and maintains full compatibility with Terraform 1.5.x while adding community-driven features.
## Key Differences (2025)
### Licensing
**Terraform (HashiCorp):**
- BSL (Business Source License) since August 2023
- Restrictions on commercial use for competing products
- IBM acquired HashiCorp in 2024
**OpenTofu:**
- MPL 2.0 (Mozilla Public License)
- True open-source
- Linux Foundation governance
- Community-driven development
### Feature Innovations (2025)
**OpenTofu 1.7 Features:**
- **State Encryption**: Client-side encryption (community requested for 5+ years)
- **Loop-able Import Blocks**: for_each in import blocks
- **Dynamic Provider Functions**: Provider-defined functions support
- **Early Variable Evaluation**: Variables in terraform block
**OpenTofu 1.8 Features (Latest):**
- **OpenTofu-Specific Overrides**: Balance compatibility with innovation
- **Early Variable Evaluation Expanded**: Use variables/locals in module sources
- **Enhanced Provider Support**: Improved provider SDK
**Terraform Advantages:**
- **HCP Terraform**: Cloud platform with Stacks, HYOK, Private VCS Access
- **Enterprise Support**: Direct HashiCorp/IBM support
- **Larger Ecosystem**: More established marketplace
- **Sentinel Policies**: Policy-as-code framework (350+ NIST policies)
### Compatibility
**100% Compatible:**
- HCL syntax (same language)
- Provider ecosystem (same registry access)
- State file format (Terraform 1.5.x)
- Module structure
- CLI commands
**Migration Path:**
- Drop-in replacement for Terraform 1.5.x
- No code changes required
- State files portable (with encryption consideration)
## When to Use OpenTofu vs Terraform
### Choose OpenTofu When:
1. **Open-Source Requirements:**
- Organization policy requires open-source tools
- Want vendor neutrality
- Concerned about future license changes
2. **State Encryption Needed:**
- Compliance requires client-side encryption
- Want encryption without HCP Terraform
- Multi-cloud encryption requirements
3. **Cost Optimization:**
- Want free state encryption
- No need for HCP Terraform features
- Budget constraints on tooling
4. **Community-Driven:**
- Want to influence roadmap
- Prefer Linux Foundation governance
- Value community contributions
### Choose Terraform When:
1. **Enterprise Features Required:**
- Need HCP Terraform Stacks
- Require HYOK (Hold Your Own Key)
- Want Private VCS Access
- Need Sentinel policy enforcement
2. **Enterprise Support:**
- Want direct HashiCorp/IBM support
- Need SLA guarantees
- Require compliance certifications
3. **Advanced Features:**
- Ephemeral values (1.10+)
- Terraform Query (1.14+)
- Actions blocks (1.14+)
- Latest provider features first
4. **Established Ecosystem:**
- Existing HCP Terraform investment
- Tight integration needs
- Mature tooling requirements
## Migration from Terraform to OpenTofu
### Step 1: Assess Compatibility
```bash
# Check Terraform version
terraform version
# Must be 1.5.x or compatible
# Check provider versions
terraform providers
# All providers compatible (same registry)
```
### Step 2: Install OpenTofu
**Windows:**
```powershell
# Chocolatey
choco install opentofu
# Scoop
scoop install opentofu
# Manual
# Download from https://github.com/opentofu/opentofu/releases
```
**macOS:**
```bash
# Homebrew
brew install opentofu
# Manual
curl -L https://github.com/opentofu/opentofu/releases/download/v1.8.0/tofu_1.8.0_darwin_amd64.tar.gz | tar xz
sudo mv tofu /usr/local/bin/
```
**Linux:**
```bash
# Snap
snap install opentofu --classic
# Debian/Ubuntu
curl -fsSL https://get.opentofu.org/install-opentofu.sh | sh
# Manual
wget https://github.com/opentofu/opentofu/releases/download/v1.8.0/tofu_1.8.0_linux_amd64.tar.gz
tar -xzf tofu_1.8.0_linux_amd64.tar.gz
sudo mv tofu /usr/local/bin/
```
### Step 3: Test Compatibility
```bash
# Navigate to Terraform directory
cd /path/to/terraform/project
# Initialize with OpenTofu (non-destructive)
tofu init
# Validate configuration
tofu validate
# Generate plan (compare with Terraform plan)
tofu plan
```
### Step 4: Migrate State (Optional)
**If NOT using state encryption:**
```bash
# State is compatible - no migration needed
# Just switch from 'terraform' to 'tofu' commands
# Verify state
tofu show
```
**If ENABLING state encryption:**
```bash
# Configure encryption in .tofu file
cat > .tofu <<EOF
encryption {
state {
method = "aes_gcm"
keys {
name = "my_key"
passphrase = env.TOFU_ENCRYPTION_KEY
}
}
plan {
method = "aes_gcm"
keys {
name = "my_key"
passphrase = env.TOFU_ENCRYPTION_KEY
}
}
}
EOF
# Set encryption key
export TOFU_ENCRYPTION_KEY="your-secure-passphrase"
# Migrate state (automatically encrypts)
tofu init -migrate-state
```
### Step 5: Update CI/CD
**GitHub Actions:**
```yaml
# Before (Terraform)
- uses: hashicorp/setup-terraform@v3
with:
terraform_version: 1.5.0
# After (OpenTofu)
- uses: opentofu/setup-opentofu@v1
with:
tofu_version: 1.8.0
# Or manual install
- name: Install OpenTofu
run: |
curl -fsSL https://get.opentofu.org/install-opentofu.sh | sh
tofu version
```
**Azure DevOps:**
```yaml
# Before
- task: TerraformInstaller@0
inputs:
terraformVersion: '1.5.0'
# After
- task: Bash@3
displayName: 'Install OpenTofu'
inputs:
targetType: 'inline'
script: |
curl -fsSL https://get.opentofu.org/install-opentofu.sh | sh
tofu version
```
**GitLab CI:**
```yaml
# Before
image: hashicorp/terraform:1.5.0
# After
image: ghcr.io/opentofu/opentofu:1.8.0
```
## State Encryption (OpenTofu Exclusive)
### Configuration
**Basic Encryption:**
```hcl
# .tofu or terraform.tf
encryption {
state {
method = "aes_gcm"
keys {
name = "primary_key"
passphrase = env.TOFU_STATE_ENCRYPTION_KEY
}
}
}
```
**Key Rotation:**
```hcl
encryption {
state {
method = "aes_gcm"
keys {
# New key
name = "key_v2"
passphrase = env.TOFU_KEY_V2
# Old key (for decryption)
fallback {
name = "key_v1"
passphrase = env.TOFU_KEY_V1
}
}
}
}
```
**Cloud KMS Integration:**
```hcl
# AWS KMS
encryption {
state {
method = "aws_kms"
keys {
name = "aws_key"
kms_key_id = "arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012"
}
}
}
# Azure Key Vault
encryption {
state {
method = "azurerm_key_vault"
keys {
name = "azure_key"
key_vault_key_id = "https://myvault.vault.azure.net/keys/mykey/version"
}
}
}
# GCP KMS
encryption {
state {
method = "gcp_kms"
keys {
name = "gcp_key"
kms_crypto_key = "projects/PROJECT_ID/locations/LOCATION/keyRings/RING/cryptoKeys/KEY"
}
}
}
```
### Best Practices
1. **Store Keys Securely:**
```bash
# Never commit keys
echo "TOFU_ENCRYPTION_KEY=xxx" >> .env
echo ".env" >> .gitignore
# Use CI/CD secrets
# GitHub: Repository Settings → Secrets
# Azure DevOps: Pipeline → Variables → Secret
```
2. **Rotate Keys Regularly:**
```bash
# Generate new key
NEW_KEY=$(openssl rand -base64 32)
# Add to fallback, update configs
# Migrate state
tofu init -migrate-state
```
3. **Backup Unencrypted State:**
```bash
# Before enabling encryption
terraform state pull > backup-unencrypted.tfstate
# Enable encryption
tofu init -migrate-state
# Verify
tofu state pull # Should be encrypted in backend
```
## Loop-able Import Blocks (OpenTofu 1.7+)
**Terraform 1.5+ (Single Imports):**
```hcl
import {
to = azurerm_resource_group.example
id = "/subscriptions/.../resourceGroups/my-rg"
}
```
**OpenTofu 1.7+ (Loop Imports):**
```hcl
# Import multiple resource groups
locals {
resource_groups = {
"rg1" = "/subscriptions/.../resourceGroups/rg1"
"rg2" = "/subscriptions/.../resourceGroups/rg2"
"rg3" = "/subscriptions/.../resourceGroups/rg3"
}
}
import {
for_each = local.resource_groups
to = azurerm_resource_group.imported[each.key]
id = each.value
}
resource "azurerm_resource_group" "imported" {
for_each = local.resource_groups
name = each.key
location = "eastus"
}
```
## Early Variable Evaluation (OpenTofu 1.7+)
**Terraform 1.5.x:**
```hcl
# Variables NOT allowed in terraform block
terraform {
required_version = ">= 1.5.0" # Static only
backend "azurerm" {
resource_group_name = "terraform-state" # Static only
storage_account_name = "tfstate"
}
}
```
**OpenTofu 1.7+:**
```hcl
# Variables allowed in terraform block
variable "environment" {
type = string
}
terraform {
required_version = ">= 1.7.0"
backend "azurerm" {
resource_group_name = "terraform-state-${var.environment}"
storage_account_name = "tfstate${var.environment}"
key = "${var.environment}.tfstate"
}
}
```
**OpenTofu 1.8+ (Module Sources):**
```hcl
variable "module_version" {
type = string
default = "v1.0.0"
}
module "networking" {
source = "git::https://github.com/org/module.git?ref=${var.module_version}"
# Dynamic module version!
}
```
## Practical Migration Examples
### Example 1: Small Project Migration
```bash
# 1. Backup existing state
terraform state pull > backup.tfstate
# 2. Install OpenTofu
brew install opentofu
# 3. Test compatibility
tofu init
tofu plan
# 4. Switch to OpenTofu
alias terraform=tofu # Optional: maintain muscle memory
# 5. Verify everything works
tofu apply
```
### Example 2: Enterprise Migration with Encryption
```bash
# 1. Generate encryption key
ENCRYPTION_KEY=$(openssl rand -base64 32)
echo "TOFU_ENCRYPTION_KEY=$ENCRYPTION_KEY" >> .env.production
# 2. Create encryption config
cat > .tofu <<EOF
encryption {
state {
method = "aes_gcm"
keys {
name = "prod_key"
passphrase = env.TOFU_ENCRYPTION_KEY
}
}
plan {
method = "aes_gcm"
keys {
name = "prod_key"
passphrase = env.TOFU_ENCRYPTION_KEY
}
}
}
EOF
# 3. Migrate with encryption
source .env.production
tofu init -migrate-state
# 4. Verify encryption
tofu state pull # State is now encrypted in backend
```
### Example 3: CI/CD Migration
```yaml
# .github/workflows/terraform.yml
name: Infrastructure
on: [push, pull_request]
jobs:
opentofu:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup OpenTofu
uses: opentofu/setup-opentofu@v1
with:
tofu_version: 1.8.0
- name: Init
run: tofu init
env:
TOFU_ENCRYPTION_KEY: ${{ secrets.TOFU_ENCRYPTION_KEY }}
- name: Plan
run: tofu plan
env:
ARM_CLIENT_ID: ${{ secrets.ARM_CLIENT_ID }}
ARM_CLIENT_SECRET: ${{ secrets.ARM_CLIENT_SECRET }}
ARM_SUBSCRIPTION_ID: ${{ secrets.ARM_SUBSCRIPTION_ID }}
ARM_TENANT_ID: ${{ secrets.ARM_TENANT_ID }}
TOFU_ENCRYPTION_KEY: ${{ secrets.TOFU_ENCRYPTION_KEY }}
- name: Apply
if: github.ref == 'refs/heads/main'
run: tofu apply -auto-approve
env:
ARM_CLIENT_ID: ${{ secrets.ARM_CLIENT_ID }}
ARM_CLIENT_SECRET: ${{ secrets.ARM_CLIENT_SECRET }}
ARM_SUBSCRIPTION_ID: ${{ secrets.ARM_SUBSCRIPTION_ID }}
ARM_TENANT_ID: ${{ secrets.ARM_TENANT_ID }}
TOFU_ENCRYPTION_KEY: ${{ secrets.TOFU_ENCRYPTION_KEY }}
```
## Command Compatibility
All Terraform commands work identically in OpenTofu (just replace `terraform` with `tofu`):
```bash
# Terraform # OpenTofu
terraform init → tofu init
terraform plan → tofu plan
terraform apply → tofu apply
terraform destroy → tofu destroy
terraform state → tofu state
terraform import → tofu import
terraform validate → tofu validate
terraform fmt → tofu fmt
terraform output → tofu output
```
## Community and Support
**OpenTofu Community:**
- GitHub: https://github.com/opentofu/opentofu
- Slack: OpenTofu Workspace
- Forum: OpenTofu Discussions
- Registry: registry.opentofu.org
**Terraform Community:**
- Forum: HashiCorp Discuss
- GitHub: hashicorp/terraform
- Registry: registry.terraform.io
- Support: HashiCorp Support Portal
## Decision Matrix
| Factor | Terraform | OpenTofu |
|--------|-----------|----------|
| **License** | BSL (Proprietary) | MPL 2.0 (Open Source) |
| **State Encryption** | Via HCP Terraform (paid) | Built-in (free) |
| **Enterprise Features** | HCP Terraform (Stacks, HYOK) | Community alternatives |
| **Governance** | HashiCorp/IBM | Linux Foundation |
| **Support** | Commercial support available | Community-driven |
| **Innovation** | HCP-focused | Community-focused |
| **Cost** | Free CLI, paid cloud | Completely free |
| **Compatibility** | Forward-compatible | Terraform 1.5.x compatible |
## Recommendations
**Start with OpenTofu if:**
- Building new infrastructure
- No need for HCP Terraform features
- Want state encryption without cloud costs
- Prefer open-source tools
- Budget-conscious
**Stay with Terraform if:**
- Using HCP Terraform Stacks
- Need Sentinel policies
- Require enterprise support
- Want latest features first (1.10+)
- Established HCP investment
**Easy to Switch:**
- Both are viable long-term
- Migration takes < 1 hour for most projects
- State files portable
- Can evaluate both without commitment
This skill provides comprehensive OpenTofu knowledge for the terraform-expert agent.

View File

@@ -0,0 +1,347 @@
---
name: terraform-tasks
description: Specialized Terraform task execution skill for autonomous infrastructure operations. Handles code generation, debugging, version management, security scanning, and architecture design across all providers and platforms.
---
# Terraform Tasks Skill
## 🚨 CRITICAL GUIDELINES
### Windows File Path Requirements
**MANDATORY: Always Use Backslashes on Windows for File Paths**
When using Edit or Write tools on Windows, you MUST use backslashes (`\`) in file paths, NOT forward slashes (`/`).
**Examples:**
- ❌ WRONG: `D:/repos/project/file.tsx`
- ✅ CORRECT: `D:\repos\project\file.tsx`
This applies to:
- Edit tool file_path parameter
- Write tool file_path parameter
- All file operations on Windows systems
### Documentation Guidelines
**NEVER create new documentation files unless explicitly requested by the user.**
- **Priority**: Update existing README.md files rather than creating new documentation
- **Repository cleanliness**: Keep repository root clean - only README.md unless user requests otherwise
- **Style**: Documentation should be concise, direct, and professional - avoid AI-generated tone
- **User preference**: Only create additional .md files when user specifically asks for documentation
---
This skill enables autonomous execution of complex Terraform tasks with comprehensive provider knowledge and platform awareness.
## Capabilities
### 1. Infrastructure Code Generation
Generate complete, production-ready Terraform code for any cloud provider:
**Process**:
1. Determine provider and version from user context
2. Research latest provider documentation if needed
3. Generate complete configurations with:
- Provider version constraints
- Resource configurations
- Variables with validation
- Outputs
- Security best practices
- Platform-specific considerations
**Example Tasks**:
- "Create Azure Storage Account with private endpoints and customer-managed keys"
- "Generate AWS VPC with 3-tier architecture and NAT gateways"
- "Build GCP GKE cluster with Workload Identity and node pools"
### 2. Version Management
Handle Terraform and provider version upgrades:
**Process**:
1. Check current versions
2. Research changelogs and breaking changes
3. Propose upgrade path
4. Generate migration code
5. Provide testing strategy
**Example Tasks**:
- "Upgrade from AzureRM provider 2.x to 3.x"
- "Migrate Terraform 0.12 code to 1.x"
- "Update all providers to latest compatible versions"
### 3. Debugging and Troubleshooting
Diagnose and fix Terraform issues:
**Process**:
1. Gather diagnostic information
2. Analyze error messages and logs
3. Identify root cause
4. Provide platform-specific solution
5. Suggest preventive measures
**Example Tasks**:
- "Debug state lock timeout on Windows"
- "Fix provider authentication failure in Azure DevOps pipeline"
- "Resolve circular dependency in module structure"
### 4. Security Scanning and Remediation
Scan and fix security issues:
**Process**:
1. Run security scanners (tfsec, Checkov)
2. Analyze findings
3. Prioritize issues
4. Generate fixes
5. Explain security implications
**Example Tasks**:
- "Run tfsec and fix all HIGH severity issues"
- "Ensure all S3 buckets have encryption enabled"
- "Implement Azure storage account with all security best practices"
### 5. Architecture Review
Review and improve Terraform architecture:
**Process**:
1. Analyze current structure
2. Identify anti-patterns
3. Propose improvements
4. Generate refactoring plan
5. Document decisions (ADRs)
**Example Tasks**:
- "Review state management strategy for 500+ resources"
- "Design multi-region architecture for high availability"
- "Refactor monolithic state into layered approach"
### 6. CI/CD Pipeline Generation
Create complete CI/CD pipelines:
**Process**:
1. Determine CI/CD platform
2. Understand environment strategy
3. Generate pipeline configuration
4. Include security scanning
5. Add approval gates
6. Implement drift detection
**Example Tasks**:
- "Create Azure DevOps pipeline with multi-stage deployment"
- "Generate GitHub Actions workflow with OIDC authentication"
- "Build GitLab CI pipeline with Terraform Cloud backend"
### 7. Module Development
Create reusable Terraform modules:
**Process**:
1. Design module interface
2. Implement with best practices
3. Add variable validation
4. Generate documentation
5. Create examples
6. Set up testing
**Example Tasks**:
- "Create Azure networking module with hub-spoke pattern"
- "Build AWS ECS module with auto-scaling and ALB"
- "Develop GCP Cloud Run module with custom domains"
### 8. Migration Tasks
Migrate infrastructure to Terraform:
**Process**:
1. Inventory existing resources
2. Generate import commands
3. Create matching Terraform code
4. Validate configurations
5. Test import process
6. Plan cutover strategy
**Example Tasks**:
- "Import existing Azure resources into Terraform"
- "Migrate from CloudFormation to Terraform"
- "Convert ARM templates to Terraform HCL"
## Autonomous Behavior
This skill operates autonomously with minimal user intervention:
### Information Gathering
- Automatically detect Terraform and provider versions
- Identify platform (Windows/Linux/macOS)
- Detect CI/CD environment
- Check for existing configurations
### Research
- Use WebSearch to find current documentation
- Check provider changelogs for breaking changes
- Research best practices
- Find platform-specific solutions
### Code Generation
- Generate complete, working code
- Include all necessary files (main.tf, variables.tf, outputs.tf, etc.)
- Add comprehensive comments
- Follow naming conventions
- Apply security best practices
### Validation
- Run terraform fmt on generated code
- Validate syntax
- Check for security issues
- Test configurations when possible
### Documentation
- Explain architectural decisions
- Document usage examples
- Note version compatibility
- Include troubleshooting tips
## Error Handling
When encountering issues:
1. **Gather Context**: Collect all relevant information
2. **Research**: Look up error messages and solutions
3. **Platform Awareness**: Consider OS-specific issues
4. **Multiple Solutions**: Provide alternatives when available
5. **Prevention**: Suggest how to avoid similar issues
## Platform-Specific Considerations
### Windows
- PowerShell syntax for commands
- Path handling (backslashes)
- Line ending considerations
- Execution policy issues
- Credential management
### Linux/macOS
- Bash syntax for commands
- File permissions
- Package managers
- Environment variables
### CI/CD Environments
- Pipeline-specific syntax
- Agent capabilities
- Authentication methods
- Artifact handling
## Quality Standards
All generated Terraform code must:
- Be properly formatted (terraform fmt)
- Pass validation (terraform validate)
- Include security best practices
- Have comprehensive variable validation
- Include meaningful descriptions
- Follow naming conventions
- Be version-compatible
- Include usage examples
- Have proper output definitions
## Provider Expertise
### Azure (AzureRM)
- All resource types
- AzAPI for preview features
- Service endpoints and private endpoints
- Managed identities
- RBAC and policies
### AWS
- All services
- IAM roles and policies
- VPC networking
- S3 backend configuration
- Cross-account deployments
### Google Cloud
- All GCP services
- IAM and service accounts
- VPC and networking
- GCS backend configuration
- Organization and folder policies
### Community Providers
- Kubernetes and Helm
- Datadog, PagerDuty
- GitHub, GitLab
- HashiCorp Vault
- And more...
## Examples
### Example 1: Generate Azure Storage Account
**User Request**: "Create an Azure Storage Account with all security best practices"
**Skill Actions**:
1. Detect/ask for AzureRM provider version
2. Research latest security requirements
3. Generate complete configuration:
- Storage account with secure settings
- Private endpoint
- Diagnostic settings
- Customer-managed encryption keys
- Network rules
- Variables with validation
- Outputs
4. Include usage examples
5. Add security scanner ignore comments where appropriate with explanations
### Example 2: Debug Plan Failure
**User Request**: "My terraform plan is failing with authentication error on Windows"
**Skill Actions**:
1. Ask for error details
2. Identify it's Azure CLI authentication
3. Provide Windows-specific solution:
- PowerShell commands to check authentication
- How to refresh credentials
- Environment variable configuration
- Alternative authentication methods
4. Explain root cause
5. Suggest prevention
### Example 3: Architecture Review
**User Request**: "Review my Terraform structure, I have 1000+ resources in one state file"
**Skill Actions**:
1. Analyze current structure
2. Identify issues:
- Large state file
- Slow operations
- Large blast radius
3. Propose layered architecture:
- Split into foundation/platform/apps
- Separate state files
- Remote state data sources
4. Generate migration plan
5. Create ADR documenting decision
6. Provide implementation steps
## Integration with terraform-expert Agent
This skill works in tandem with the terraform-expert agent:
- Agent provides strategic guidance
- Skill executes tactical tasks
- Agent validates skill outputs
- Skill reports back to agent
Use this skill when you need to autonomously execute Terraform tasks with comprehensive provider knowledge and platform awareness.