# terraform-instance

Part of **TERRAFORM**

# Terraform Instance Management CLI Reference

## Command Overview

| Command | Purpose | Syntax |
|--------|---------|--------|
| `terraform init` | Initialize a working directory containing Terraform configuration files | `terraform init [options]` |
| `terraform validate` | Validate the configuration files in a directory | `terraform validate [options]` |
| `terraform fmt` | Format configuration files to canonical style | `terraform fmt [options]` |
| `terraform plan` | Generate and show an execution plan | `terraform plan [options]` |
| `terraform apply` | Apply changes to reach the desired state | `terraform apply [options] [PLAN_FILE]` |
| `terraform destroy` | Destroy all managed infrastructure | `terraform destroy [options]` |
| `terraform import` | Import existing infrastructure into Terraform state | `terraform import [options] ADDR ID` |
| `terraform refresh` | Update state file with real-world infrastructure | `terraform refresh [options]` |
| `terraform output` | Show output values from the root module | `terraform output [options] [NAME]` |
| `terraform console` | Interactive console for evaluating expressions | `terraform console [options]` |
| `terraform graph` | Generate a visual dependency graph | `terraform graph [options]` |
| `terraform show` | Inspect current state or a plan file | `terraform show [options] [PATH]` |
| `terraform taint` | Mark a resource as tainted (to be replaced) | `terraform taint [options] ADDR` |
| `terraform untaint` | Remove taint from a resource | `terraform untaint [options] ADDR` |
| `terraform state list` | List resources in the state | `terraform state list [options] [FILTER...]` |
| `terraform state show` | Show attributes of a single resource | `terraform state show [options] ADDR` |
| `terraform state pull` | Pull current state and output to stdout | `terraform state pull [options]` |
| `terraform state rm` | Remove resource(s) from the state | `terraform state rm [options] ADDR...` |
| `terraform state mv` | Move resource(s) in the state | `terraform state mv [options] SOURCE DEST` |
| `terraform workspace` | Manage multiple workspaces/environments | `terraform workspace <subcommand> [options]` |

## Command Details

### terraform init

**Purpose**: Initializes a Terraform working directory by downloading required providers and modules.

**Syntax**:
```bash
terraform init [options]
```

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| `--backend-config` | — | string | No | Configuration for backend (can be used multiple times) |
| `--get` | — | boolean | No | Whether to download modules (`true` by default) |
| `--upgrade` | — | boolean | No | Upgrade modules and plugins to latest versions |
| `--from-module` | — | string | No | Copy the source of the given module to the target directory |

```bash
# Initialize with default settings
terraform init

# Upgrade providers and modules during init
terraform init -upgrade
```

### terraform validate

**Purpose**: Validates the syntax and structure of Terraform configuration files.

**Syntax**:
```bash
terraform validate [options]
```

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| `--json` | — | boolean | No | Produce output in JSON format |

```bash
# Validate current configuration
terraform validate

# Get machine-readable validation result
terraform validate --json
```

### terraform fmt

**Purpose**: Rewrites Terraform configuration files to a canonical format.

**Syntax**:
```bash
terraform fmt [options] [DIR...]
```

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| `--list` | — | boolean | No | List files that would be formatted (`true` by default) |
| `--write` | — | boolean | No | Write result to source file (`true` by default) |
| `--diff` | — | boolean | No | Display diffs of formatting changes |
| `--recursive` | `-r` | boolean | No | Process subdirectories recursively |

```bash
# Format all .tf files in current directory
terraform fmt

# Show diff without writing changes
terraform fmt -diff -write=false
```

### terraform plan

**Purpose**: Creates an execution plan showing what actions Terraform will take to reach the desired state.

**Syntax**:
```bash
terraform plan [options]
```

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| `--out` | — | string | No | Save plan to file for later use with `apply` |
| `--var` | — | string | No | Set variable value (e.g., `--var 'key=value'`) |
| `--var-file` | — | string | No | Load variable values from file |
| `--destroy` | — | boolean | No | Generate plan to destroy all resources |
| `--refresh` | — | boolean | No | Refresh state before planning (`true` by default) |

```bash
# Generate a plan with variables
terraform plan -var 'region=eu-central-1'

# Save plan to file
terraform plan -out=tfplan
```

### terraform apply

**Purpose**: Applies the changes required to reach the desired state.

**Syntax**:
```bash
terraform apply [options] [PLAN_FILE]
```

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| `--auto-approve` | — | boolean | No | Skip interactive approval prompt |
| `--var` | — | string | No | Set variable value |
| `--var-file` | — | string | No | Load variable values from file |
| `--parallelism` | — | integer | No | Limit number of concurrent operations |

```bash
# Apply with auto-approval
terraform apply -auto-approve

# Apply a saved plan
terraform apply tfplan
```

### terraform destroy

**Purpose**: Destroys all infrastructure managed by Terraform.

**Syntax**:
```bash
terraform destroy [options]
```

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| `--auto-approve` | — | boolean | No | Skip confirmation prompt |
| `--var` | — | string | No | Set variable value |
| `--var-file` | — | string | No | Load variable values from file |

```bash
# Destroy all resources without confirmation
terraform destroy -auto-approve
```

### terraform import

**Purpose**: Imports existing infrastructure into Terraform state.

**Syntax**:
```bash
terraform import [options] ADDR ID
```

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| `--var` | — | string | No | Set variable value |
| `--var-file` | — | string | No | Load variable values from file |

```bash
# Import an existing vSwitch
terraform import alicloud_vswitch.this vsw-gw8gl31wz******
```

### terraform refresh

**Purpose**: Updates the state file with the real-world infrastructure.

**Syntax**:
```bash
terraform refresh [options]
```

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| `--var` | — | string | No | Set variable value |
| `--var-file` | — | string | No | Load variable values from file |

```bash
# Refresh state with custom variables
terraform refresh -var 'region=eu-central-1'
```

### terraform output

**Purpose**: Shows output values from the root module.

**Syntax**:
```bash
terraform output [options] [NAME]
```

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| `--json` | — | boolean | No | Produce output in JSON format |
| `--state` | — | string | No | Path to state file |

```bash
# Show all outputs
terraform output

# Show specific output
terraform output vswitchId
```

**Example Output**:
```text
vswitchId = vsw-gw8gl31wz********
```

### terraform taint

**Purpose**: Marks a resource as tainted so it will be destroyed and recreated on next apply.

**Syntax**:
```bash
terraform taint [options] ADDR
```

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| `--allow-missing` | — | boolean | No | Succeed even if resource is missing from config |
| `--module-depth` | — | integer | No | Depth to display modules |

```bash
# Taint a vSwitch resource
terraform taint alicloud_vswitch.this
```

**Example Output**:
```text
Resource instance alicloud_vswitch.this has been marked as tainted.
```

### terraform untaint

**Purpose**: Removes taint from a resource so it won’t be replaced.

**Syntax**:
```bash
terraform untaint [options] ADDR
```

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| `--allow-missing` | — | boolean | No | Succeed even if resource is missing |
| `--module-depth` | — | integer | No | Depth to display modules |

```bash
# Untaint a vSwitch resource
terraform untaint alicloud_vswitch.this
```

**Example Output**:
```text
Resource instance alicloud_vswitch.this has been successfully untainted.
```

### terraform state list

**Purpose**: Lists all resources in the Terraform state.

**Syntax**:
```bash
terraform state list [options] [FILTER...]
```

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| `--state` | — | string | No | Path to state file |

```bash
# List all resources
terraform state list
```

**Example Output**:
```text
data.alicloud_slbs.default
alicloud_vpc.default
alicloud_vswitch.this
```

### terraform state show

**Purpose**: Shows detailed attributes of a single resource in state.

**Syntax**:
```bash
terraform state show [options] ADDR
```

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| `--state` | — | string | No | Path to state file |

```bash
# Show details of a vSwitch
terraform state show alicloud_vswitch.this
```

**Example Output**:
```text
# alicloud_vswitch.this:
resource "alicloud_vswitch" "this" {
    availability_zone = "eu-central-1a"
    cidr_block        = "172.16.0.0/24"
    id                = "vsw-gw8gl31wz******"
    vpc_id            = "vpc-gw8calnzt*******"
}
```

### terraform state pull

**Purpose**: Outputs the full state file in JSON format.

**Syntax**:
```bash
terraform state pull [options]
```

**Parameters**: None

```bash
# Pull and view state
terraform state pull
```

**Example Output**:
```json
{
    "version": 4,
    "terraform_version": "0.12.8",
    "serial": 615,
    "lineage": "39aeeee2-b3bd-8130-c897-2cb8595cf8ec",
    "outputs": {
     ***
 },
 "resources": [
  {
        "mode": "data",
        "type": "alicloud_slbs",
        "name": "default",
        "provider": "provider.alicloud",
     ***
  },
  {
        "mode": "managed",
        "type": "alicloud_vpc",
        "name": "default",
        "provider": "provider.alicloud",
     ***
  }
]
```

### terraform state rm

**Purpose**: Removes one or more resources from the state file.

**Syntax**:
```bash
terraform state rm [options] ADDR...
```

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| `--state` | — | string | No | Path to input state file |
| `--state-out` | — | string | No | Path to output state file |

```bash
# Remove a vSwitch from state
terraform state rm alicloud_vswitch.this
```

**Example Output**:
```text
Removed alicloud_vswitch.this
Successfully removed 1 resource instance(s).
```

### terraform state mv

**Purpose**: Moves a resource within the state file (e.g., rename or move between modules).

**Syntax**:
```bash
terraform state mv [options] SOURCE DEST
```

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| `--state` | — | string | No | Path to input state file |
| `--state-out` | — | string | No | Path to output state file |

```bash
# Rename resource from 'this' to 'default'
terraform state mv --state-out=../tf.tfstate alicloud_vswitch.this alicloud_vswitch.default
```

**Example Output**:
```text
Move "alicloud_vswitch.this" to "alicloud_vswitch.default"
Successfully moved 1 object(s)
```

### terraform graph

**Purpose**: Generates a visual representation of resource dependencies.

**Syntax**:
```bash
terraform graph [options]
```

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| `--draw-cycles` | — | boolean | No | Highlight cycles in the graph |
| `--type` | — | string | No | Type of graph to output (`plan`, `plan-destroy`, `apply`) |

```bash
# Generate dependency graph in DOT format
terraform graph

# Convert to SVG using Graphviz
terraform graph | dot -Tsvg > graph.svg
```

**Example Output**:
```text
digraph {
 compound = "true"
 newrank = "true"
 subgraph "root" {
 "[root] alicloud_vpc.default" [label = "alicloud_vpc.default", shape = "box"]
 "[root] alicloud_vswitch.this" [label = "alicloud_vswitch.this", shape = "box"]
                ****
 "[root] output.vswitchId" -> "[root] alicloud_vswitch.this"
 "[root] provider.alicloud (close)" -> "[root] alicloud_vswitch.this"
****
 "[root] root" -> "[root] provider.alicloud (close)"
 }
}
```

## Common Scenarios

### Scenario 1: Import Existing Infrastructure and Manage via Terraform

```bash
# Step 1: Write a Terraform configuration for the existing resource
# (e.g., define alicloud_vswitch.this in main.tf)

# Step 2: Initialize the working directory
terraform init

# Step 3: Import the existing vSwitch into state
terraform import alicloud_vswitch.this vsw-gw8gl31wz******

# Step 4: Verify the import succeeded
terraform state show alicloud_vswitch.this

# Step 5: Plan and apply to ensure consistency
terraform plan
terraform apply -auto-approve
```

### Scenario 2: Debug Resource Dependencies and State

```bash
# Step 1: List all resources in state
terraform state list

# Step 2: Inspect a specific resource's attributes
terraform state show alicloud_vswitch.this

# Step 3: Visualize dependencies
terraform graph | dot -Tpng > dependency-graph.png

# Step 4: If needed, remove a resource from state (without destroying)
terraform state rm alicloud_vswitch.this
```

### Scenario 3: Force Replacement of a Resource

```bash
# Step 1: Mark resource as tainted
terraform taint alicloud_vswitch.this

# Step 2: Plan to confirm replacement
terraform plan

# Step 3: Apply the change
terraform apply -auto-approve

# Step 4: If change was accidental, untaint before apply
terraform untaint alicloud_vswitch.this
```

## Environment Setup

### Installation
Terraform is a standalone binary. Download the appropriate version for your OS from [https://developer.hashicorp.com/terraform/downloads](https://developer.hashicorp.com/terraform/downloads) and add it to your system PATH.

### Configuration
- **Provider Configuration**: Define the Alibaba Cloud provider in your Terraform configuration (`main.tf` or `provider.tf`) with region and credentials.
- **Authentication**: Configure credentials via environment variables (`ALICLOUD_ACCESS_KEY`, `ALICLOUD_SECRET_KEY`) or shared credentials file.
- **State Backend**: Optionally configure a remote backend (e.g., OSS) for team collaboration by adding a `backend` block in your configuration.

Example provider setup:
```hcl
provider "alicloud" {
  region = "eu-central-1"
}
```

## FAQ

Q: How do I configure credentials for Terraform to manage Alibaba Cloud resources?
A: You can set credentials using environment variables (`ALICLOUD_ACCESS_KEY` and `ALICLOUD_SECRET_KEY`), or configure them directly in the provider block (not recommended for production). For secure usage, use RAM roles or instance metadata when running on ECS.

Q: What is the difference between `terraform refresh` and `terraform apply -refresh-only`?
A: `terraform refresh` updates the state file directly with real-world values. `terraform apply -refresh-only` (available in Terraform 0.15+) generates a plan that only refreshes state and shows drift, but does not allow destructive changes—safer for detecting configuration drift.

Q: How can I safely rename a resource in my Terraform configuration?
A: Use `terraform state mv` to update the state to match the new name in your config. First, update the resource name in your `.tf` file, then run `terraform state mv old_address new_address` to align the state.

Q: Why does `terraform plan` show changes even when no configuration was modified?
A: This usually indicates "drift"—the real infrastructure differs from the state file. Run `terraform refresh` to update state, or investigate manual changes outside Terraform. Use `terraform apply -refresh-only` to detect and record drift safely.

Q: How do I export the entire Terraform state for backup or analysis?
A: Use `terraform state pull > terraform.tfstate` to export the current state as a JSON file. This file contains all resource metadata and outputs, and can be used for auditing or migration.