# terraform-iac

Part of **TERRAFORM**

# Terraform Infrastructure as Code CLI Reference

## Command Overview

| Command | Purpose | Syntax |
|--------|--------|--------|
| terraform init | Initialize a working directory containing Terraform configuration files | `terraform init [options]` |
| terraform plan | Create an execution plan to preview infrastructure changes | `terraform plan [options]` |
| terraform apply | Apply the changes required to reach the desired state of the configuration | `terraform apply [options]` |
| terraform destroy | Destroy the infrastructure managed by Terraform | `terraform destroy [options]` |
| terraform output | Read output values from the state file | `terraform output [options] [NAME]` |

## Command Details

### terraform init

**Purpose**: Initializes a Terraform working directory by downloading provider plugins, setting up backend configuration, and preparing modules.

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

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| --backend | — | boolean | No | Configure the backend for storing state (default: true) |
| --backend-config | — | string | No | Backend configuration file or key=value pair |
| --get | — | boolean | No | Download modules (default: true) |
| --plugin-dir | — | path | No | Directory containing plugin binaries |
| --upgrade | — | boolean | No | Upgrade modules and plugins to latest versions |

```bash
# Initialize with default settings
terraform init

# Initialize and upgrade providers/modules
terraform init -upgrade

# Initialize with custom backend config
terraform init --backend-config="path=prod.tfstate"
```

**Output Example**:
```text
Initializing the backend...
Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
Terraform has been successfully initialized!
```

### terraform plan

**Purpose**: Generates and shows an execution plan without applying changes, allowing users to review proposed actions.

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

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| --out | — | path | No | Save plan to a file for later application |
| --var | — | string | No | Set variable value (e.g., `--var 'region=cn-shanghai'`) |
| --var-file | — | path | No | Load variable values from a file |
| --destroy | — | boolean | No | Generate a plan to destroy all resources |

```bash
# Generate a standard execution plan
terraform plan

# Plan with variables from file
terraform plan --var-file="prod.tfvars"

# Plan to destroy all infrastructure
terraform plan --destroy
```

**Output Example**:
```text
Terraform will perform the following actions:
  # aws_instance.example will be created
  + resource "aws_instance" "example" {
      + ami           = "ami-0abcdef1234567890"
      + instance_type = "t3.micro"
    }
Plan: 1 to add, 0 to change, 0 to destroy.
```

### terraform apply

**Purpose**: Applies the changes required to achieve the desired state defined in configuration files.

**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 | — | path | No | Load variable values from file |
| — | — | path | No | Optional saved plan file to apply |

```bash
# Apply interactively (prompts for confirmation)
terraform apply

# Apply without confirmation
terraform apply --auto-approve

# Apply a pre-saved plan
terraform apply "prod.tfplan"
```

**Output Example**:
```text
aws_instance.example: Creating...
aws_instance.example: Creation complete after 45s [id=i-0abcd1234efgh5678]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
```

### terraform destroy

**Purpose**: Destroys all infrastructure managed by Terraform in the current configuration.

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

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| --auto-approve | — | boolean | No | Skip interactive approval |
| --var | — | string | No | Set variable value |
| --var-file | — | path | No | Load variable values from file |

```bash
# Destroy with confirmation prompt
terraform destroy

# Destroy without confirmation
terraform destroy --auto-approve
```

**Output Example**:
```text
aws_instance.example: Destroying... [id=i-0abcd1234efgh5678]
aws_instance.example: Destruction complete after 20s
Destroy complete! Resources: 0 added, 0 changed, 1 destroyed.
```

### terraform output

**Purpose**: Reads and displays output values defined in the configuration from the Terraform state.

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

| Parameter | Short | Type | Required | Description |
|----------|-------|------|----------|-------------|
| --json | — | boolean | No | Output in JSON format |
| --raw | — | boolean | No | Display raw output value (for strings) |
| NAME | — | string | No | Specific output name to retrieve |

```bash
# List all outputs
terraform output

# Get a specific output value
terraform output instance_ip

# Get outputs in JSON format
terraform output --json
```

**Output Example**:
```text
instance_ip = "203.0.113.25"
```

## Common Scenarios

### Scenario 1: Initialize and Deploy Infrastructure
```bash
# Step 1: Initialize the working directory (downloads providers)
terraform init

# Step 2: Review the execution plan before applying
terraform plan

# Step 3: Apply the configuration to create resources
terraform apply --auto-approve
```

### Scenario 2: Destroy and Clean Up Resources
```bash
# Step 1: Generate a destruction plan for review
terraform plan --destroy

# Step 2: Destroy all managed infrastructure
terraform destroy --auto-approve
```

### Scenario 3: Use Variables and Save Plan for CI/CD
```bash
# Step 1: Initialize with module upgrades
terraform init -upgrade

# Step 2: Create a plan with environment-specific variables
terraform plan --var-file="staging.tfvars" --out="staging.tfplan"

# Step 3: Apply the saved plan in automated pipeline
terraform apply "staging.tfplan"
```

## Environment Setup

### Installation

Terraform can be installed via multiple methods:

**Manual Installation (macOS/Linux)**:
```bash
# Download binary and move to PATH
mv ~/Downloads/terraform /usr/local/bin/
```

**Homebrew (macOS)**:
```bash
brew tap hashicorp/tap
brew install hashicorp/tap/terraform
```

**Chocolatey (Windows)**:
```powershell
choco install terraform
```

**YUM (RHEL/CentOS)**:
```bash
yum install -y dnf-plugin-releasever-adapter
yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
yum install terraform
```

### Configuration

- Ensure the `terraform` binary is in your system `PATH`
- No authentication is required for Terraform itself; cloud provider credentials are configured separately in provider blocks
- Version compatibility is managed automatically during `terraform init`

## FAQ

Q: How do I verify Terraform is installed correctly?
A: Run `terraform version` in your terminal. It should display the installed version (e.g., `Terraform v1.6.0`).

Q: What does `terraform init` actually do?
A: It downloads required provider plugins, initializes the backend for state storage, and prepares any child modules referenced in your configuration.

Q: Can I apply changes without manual confirmation?
A: Yes, use the `--auto-approve` flag with `terraform apply` or `terraform destroy` to skip the interactive prompt.

Q: Where are Terraform plugins stored after initialization?
A: By default, plugins are cached in a hidden `.terraform` directory in your working directory. You can override this with the `--plugin-dir` option.

Q: How do I handle different environments (dev, staging, prod)?
A: Use separate variable files (e.g., `dev.tfvars`, `prod.tfvars`) and pass them with `--var-file`, or use workspace-based configurations for more advanced setups.