# Skill: terraform

## Metadata

| Field | Value |
|-------|-------|
| **Name** | `terraform` |
| **Version** | `1.0.0` |
| **Package** | `oclawma-skill-terraform` |
| **Category** | `infrastructure` |
| **Author** | `OpenClaw Team` |
| **License** | `MIT` |
| **Python** | `>=3.9` |

## Description

Official Terraform skill for OCLAWMA providing comprehensive infrastructure as code management capabilities.

### Features

- **Lifecycle Commands** - init, validate, plan, apply, destroy
- **Configuration** - Format and validate Terraform files
- **State Management** - List, show, move, remove state items
- **Workspace Management** - Create, select, delete workspaces
- **Resource Operations** - Import, taint, untaint resources
- **Output and Refresh** - View outputs and refresh state

## Installation

```bash
pip install oclawma-skill-terraform
```

Or install from source:

```bash
git clone https://github.com/openclaw/oclawma-skill-terraform.git
cd oclawma-skill-terraform
pip install -e .
```

### Prerequisites

- **Terraform** - Version 1.0 or later (`terraform version`)
- Valid **Terraform configuration files**
- Access to target infrastructure provider

## Configuration

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `TF_VAR_*` | - | Terraform variables (e.g., TF_VAR_region) |
| `TF_DATA_DIR` | `.terraform` | Data directory |
| `TF_PLUGIN_CACHE_DIR` | - | Plugin cache directory |
| `TF_IN_AUTOMATION` | - | Set to non-empty for CI/CD |

## Tools

### Lifecycle Commands

#### `init`

Initialize Terraform working directory.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `path` | `string` | No | `.` | Path to Terraform configuration |
| `backend` | `boolean` | No | true | Configure backend |
| `upgrade` | `boolean` | No | false | Upgrade modules and plugins |

**Example:**
```python
# Initialize with backend
result = await registry.execute_tool("terraform", "init")

# Initialize without backend
result = await registry.execute_tool(
    "terraform", "init",
    backend=False
)

# Upgrade dependencies
result = await registry.execute_tool(
    "terraform", "init",
    upgrade=True
)
```

#### `validate`

Validate Terraform configuration.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `path` | `string` | No | `.` | Path to Terraform configuration |

#### `plan`

Generate and show execution plan.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `path` | `string` | No | `.` | Path to Terraform configuration |
| `var_file` | `string` | No | - | Path to variables file |
| `vars` | `object` | No | - | Variables (key-value pairs) |
| `destroy` | `boolean` | No | false | Plan destroy operation |
| `target` | `string` | No | - | Resource to target |
| `detailed_exitcode` | `boolean` | No | true | Return detailed exit code |

**Example:**
```python
# Basic plan
result = await registry.execute_tool("terraform", "plan")

# Plan with variables
result = await registry.execute_tool(
    "terraform", "plan",
    vars={
        "region": "us-west-2",
        "instance_type": "t2.micro"
    }
)

# Plan with variable file
result = await registry.execute_tool(
    "terraform", "plan",
    var_file="prod.tfvars"
)

# Plan destruction
result = await registry.execute_tool(
    "terraform", "plan",
    destroy=True
)

# Target specific resource
result = await registry.execute_tool(
    "terraform", "plan",
    target="aws_instance.web"
)
```

#### `apply`

Build or change infrastructure.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `path` | `string` | No | `.` | Path to Terraform configuration |
| `var_file` | `string` | No | - | Path to variables file |
| `vars` | `object` | No | - | Variables (key-value pairs) |
| `auto_approve` | `boolean` | No | false | Auto-approve changes |
| `target` | `string` | No | - | Resource to target |
| `refresh` | `boolean` | No | true | Refresh state before apply |

**Example:**
```python
# Apply with auto-approval
result = await registry.execute_tool(
    "terraform", "apply",
    auto_approve=True
)

# Apply with variables
result = await registry.execute_tool(
    "terraform", "apply",
    auto_approve=True,
    vars={"region": "us-east-1"}
)

# Apply specific resource
result = await registry.execute_tool(
    "terraform", "apply",
    target="aws_s3_bucket.data",
    auto_approve=True
)
```

#### `destroy`

Destroy Terraform-managed infrastructure.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `path` | `string` | No | `.` | Path to Terraform configuration |
| `var_file` | `string` | No | - | Path to variables file |
| `vars` | `object` | No | - | Variables (key-value pairs) |
| `auto_approve` | `boolean` | No | false | Auto-approve destruction |
| `target` | `string` | No | - | Resource to target |

### Configuration Commands

#### `fmt`

Rewrite configuration files to canonical format.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `path` | `string` | No | `.` | Path to Terraform configuration |
| `recursive` | `boolean` | No | false | Process files recursively |
| `check` | `boolean` | No | false | Check if formatting is correct |

#### `show`

Show Terraform state or plan.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `path` | `string` | No | `.` | Path to Terraform configuration |
| `json` | `boolean` | No | false | Output in JSON format |

### State Commands

#### `state_list`

List resources in state.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `path` | `string` | No | `.` | Path to Terraform configuration |

**Example:**
```python
result = await registry.execute_tool("terraform", "state_list")
# Output: aws_instance.web\naws_s3_bucket.data
```

#### `state_show`

Show a resource in state.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `address` | `string` | Yes | - | Resource address |
| `path` | `string` | No | `.` | Path to Terraform configuration |

**Example:**
```python
result = await registry.execute_tool(
    "terraform", "state_show",
    address="aws_instance.web"
)
```

#### `state_mv`

Move item in state.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `source` | `string` | Yes | - | Source address |
| `destination` | `string` | Yes | - | Destination address |
| `path` | `string` | No | `.` | Path to Terraform configuration |

**Example:**
```python
# Rename a resource in state
result = await registry.execute_tool(
    "terraform", "state_mv",
    source="aws_instance.web",
    destination="aws_instance.frontend"
)
```

#### `state_rm`

Remove items from state.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `address` | `string` | Yes | - | Resource address to remove |
| `path` | `string` | No | `.` | Path to Terraform configuration |

### Resource Commands

#### `import`

Import existing infrastructure into Terraform.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `address` | `string` | Yes | - | Resource address |
| `id` | `string` | Yes | - | Resource ID to import |
| `path` | `string` | No | `.` | Path to Terraform configuration |

**Example:**
```python
# Import EC2 instance
result = await registry.execute_tool(
    "terraform", "import",
    address="aws_instance.web",
    id="i-1234567890abcdef0"
)
```

#### `taint`

Mark a resource as tainted (will be recreated on next apply).

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `address` | `string` | Yes | - | Resource address |
| `path` | `string` | No | `.` | Path to Terraform configuration |

#### `untaint`

Remove taint from a resource.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `address` | `string` | Yes | - | Resource address |
| `path` | `string` | No | `.` | Path to Terraform configuration |

### Output Commands

#### `output`

Show output values from state.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `path` | `string` | No | `.` | Path to Terraform configuration |
| `name` | `string` | No | - | Output name (omit for all) |
| `json` | `boolean` | No | true | Output in JSON format |

**Example:**
```python
# Show all outputs
result = await registry.execute_tool("terraform", "output")

# Show specific output
result = await registry.execute_tool(
    "terraform", "output",
    name="instance_ip"
)
```

#### `refresh`

Update state file against real resources.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `path` | `string` | No | `.` | Path to Terraform configuration |
| `var_file` | `string` | No | - | Path to variables file |
| `vars` | `object` | No | - | Variables (key-value pairs) |

### Workspace Commands

#### `workspace_list`

List workspaces.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `path` | `string` | No | `.` | Path to Terraform configuration |

#### `workspace_select`

Select a workspace.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `name` | `string` | Yes | - | Workspace name |
| `path` | `string` | No | `.` | Path to Terraform configuration |

**Example:**
```python
result = await registry.execute_tool(
    "terraform", "workspace_select",
    name="production"
)
```

#### `workspace_new`

Create a new workspace.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `name` | `string` | Yes | - | Workspace name |
| `path` | `string` | No | `.` | Path to Terraform configuration |

#### `workspace_delete`

Delete a workspace.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `name` | `string` | Yes | - | Workspace name |
| `path` | `string` | No | `.` | Path to Terraform configuration |

### Utility Commands

#### `providers`

Show provider requirements.

**Parameters:**

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `path` | `string` | No | `.` | Path to Terraform configuration |

#### `version`

Show Terraform version.

**Example:**
```python
result = await registry.execute_tool("terraform", "version")
# Output: Terraform v1.6.0 on linux_amd64
```

## Error Handling

All tools return a standardized result dictionary:

```python
{
    "success": bool,           # True if operation succeeded
    "output": str,             # Command output
    "exit_code": int,          # Process exit code
    "error": str | None,       # Error message on failure
    "truncated": bool          # True if output was truncated
}
```

### Special Exit Codes

- **Plan command**: Exit code 2 indicates changes are present (still considered success)
- **Exit code 1**: General error

### Common Errors

- **Terraform not found** - Install Terraform and ensure it's in PATH
- **Configuration errors** - Run `validate` to check configuration
- **State lock errors** - Another process may be running Terraform
- **Provider errors** - Check provider configuration and credentials

## Dependencies

- `oclawma>=0.1.0` - Core OCLAWMA framework
- `pyyaml>=6.0` - YAML parsing

## Testing

```bash
# Run test suite
pytest tests/ -v

# Test with coverage
pytest --cov=src/oclawma_skill_terraform
```

## Development

```bash
# Clone repository
git clone https://github.com/openclaw/oclawma-skill-terraform.git
cd oclawma-skill-terraform

# Create virtual environment
python -m venv venv
source venv/bin/activate

# Install in development mode
pip install -e ".[dev]"

# Run tests
pytest

# Run linting
black src tests
ruff check src tests
mypy src
```

## Best Practices

1. **Always run `init` first** before other commands
2. **Review plans** before applying with `auto_approve=True`
3. **Use workspaces** for environment separation
4. **Format code** with `fmt` before committing
5. **Validate** configurations before applying

## Security Notes

- Never commit Terraform state files to version control
- Use remote state backends for team collaboration
- Protect state files as they may contain sensitive data
- Use environment variables or vaults for secrets

## License

MIT License - see LICENSE file for details.

## Contributing

Contributions are welcome! Please:
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request
