# Terraform commands

Here’s a complete guide to using Terraform’s core commands, advanced lifecycle attributes, debugging methods, and handling `.tfvars` files for variable customization. This will streamline your infrastructure management while providing flexibility and precision.

---

### **1\. Initialization and Basic Commands**

#### **1.1** `terraform init`

* **Purpose**: Initializes a new or existing Terraform configuration, setting up backend and provider plugins.
    
* **Command**:
    
    ```bash
    terraform init
    ```
    

#### **1.2** `terraform fmt`

* **Purpose**: Formats Terraform configuration files to keep code standardized.
    
* **Command**:
    
    ```bash
    terraform fmt
    ```
    

#### **1.3** `terraform validate`

* **Purpose**: Validates configuration files for syntax and logical correctness.
    
* **Command**:
    
    ```bash
    terraform validate
    ```
    

#### **1.4** `tflint` (Terraform Linter)

* **Purpose**: Checks configuration for best practices and potential issues.
    
* **Command**:
    
    ```bash
    tflint
    ```
    

---

### **2\. Planning and Execution Commands**

#### **2.1** `terraform plan`

* **Purpose**: Previews the changes Terraform will make to reach the desired state.
    
* **Command**:
    
    ```bash
    terraform plan
    ```
    
* **Save Plan**: Store the plan for later execution.
    
    ```bash
    terraform plan -out=tfplan
    ```
    

#### **2.2** `terraform apply`

* **Purpose**: Applies changes to reach the desired state.
    
* **Command**:
    
    ```bash
    terraform apply
    ```
    
* **Auto-Approve**:
    
    ```bash
    terraform apply -auto-approve
    ```
    
* **Apply a Saved Plan**:
    
    ```bash
    terraform apply tfplan
    ```
    

---

### **3\. Managing and Debugging**

#### **3.1** `terraform taint`

* **Purpose**: Marks a resource for recreation in the next apply.
    
* **Command**:
    
    ```bash
    terraform taint <resource_name>
    ```
    

#### **3.2** `terraform output`

* **Purpose**: Displays output variables defined in your configuration.
    
* **Command**:
    
    ```bash
    terraform output
    ```
    

#### **3.3** `terraform destroy`

* **Purpose**: Destroys all managed infrastructure.
    
* **Command**:
    
    ```bash
    terraform destroy -auto-approve
    ```
    

---

### **4\. Importing Existing Resources**

#### **4.1** `terraform import`

* **Purpose**: Imports existing infrastructure into Terraform state.
    
* **Command**:
    
    ```bash
    terraform import <resource_type>.<resource_name> <resource_id>
    ```
    
* **Example**:
    
    ```bash
    terraform import aws_s3_bucket.example my-existing-bucket
    ```
    

---

### **5\. Debugging Terraform**

#### **Enable Debug Mode**

* Set the `TF_LOG` environment variable to `DEBUG` for detailed logs:
    
    ```bash
    export TF_LOG=DEBUG
    terraform apply
    ```
    
    * **Log Levels**: Options include `TRACE`, `DEBUG`, `INFO`, `WARN`, and `ERROR`.
        

#### **Log to File**:

* Redirect logs to a file:
    
    ```bash
    export TF_LOG=DEBUG
    terraform apply > debug.log
    ```
    

#### **Disable Debug Mode**:

* Clear the debug variable:
    
    ```bash
    unset TF_LOG
    ```
    

---

### **6\. Lifecycle Management Attributes**

#### **6.1** `create_before_destroy`

* Ensures resources are created before the existing ones are destroyed to avoid downtime.
    
    ```bash
    lifecycle {
      create_before_destroy = true
    }
    ```
    

#### **6.2** `prevent_destroy`

* Prevents accidental deletion of critical resources.
    
    ```bash
    lifecycle {
      prevent_destroy = true
    }
    ```
    

#### **6.3** `ignore_changes`

* Ignores specified attributes if modified outside Terraform.
    
    ```bash
    lifecycle {
      ignore_changes = [tags]
    }
    ```
    

###   
**7\. Workspaces and State Management**

Terraform’s state file (`terraform.tfstate`) tracks resources and stores metadata. For teams, managing state remotely with S3 and DynamoDB for state locking ensures consistency and prevents conflicts.

**7.1 Storing Terraform State in S3**

Storing Terraform state in S3 provides centralized state management, enabling collaboration and redundancy. To configure it:

* **Backend Configuration**:
    
    ```bash
    terraform {
      backend "s3" {
        bucket = "my-terraform-state-bucket"
        key    = "path/to/my/terraform.tfstate"
        region = "us-west-2"
        encrypt = true
      }
    }
    ```
    

#### **7.2 Locking Terraform State with DynamoDB**

DynamoDB enables state locking to prevent concurrent modifications to the state file, minimizing the risk of race conditions in collaborative environments.

* **DynamoDB Table for Locking**:
    
    * Create a DynamoDB table with a primary key named `LockID`.
        
* **Backend Configuration with DynamoDB**:
    
    ```bash
    terraform {
      backend "s3" {
        bucket         = "my-terraform-state-bucket"
        key            = "path/to/my/terraform.tfstate"
        region         = "us-west-2"
        encrypt        = true
        dynamodb_table = "terraform-lock-table"
      }
    }
    ```
    
      
    **Commands for Workspace and State**  
    **terraform workspace**
    
* Workspaces allow you to manage multiple environments in the same configuration.
    
* **Commands**:
    
    * `terraform workspace list`: Lists all workspaces.
        
    * `terraform workspace new <name>`: Creates a new workspace.
        
    * `terraform workspace select <name>`: Switches to a specified workspace.
        

#### terraform state

* Manage state files for precise resource tracking.
    
* **Commands**:
    
    * `terraform state list`: Lists resources in the state.
        
    * `terraform state show <resource>`: Shows details of a specific resource.
        
    * `terraform state rm <resource>`: Removes a resource from state without deleting it.
        

---

### **8\. Enhancing Reusability with Local Variables, Dynamic Blocks, and Modules**

#### **8.1 Local Variables**

Local variables reduce duplication by centralizing expressions that you want to reuse multiple times.

* **Define Locals**:
    
    ```bash
    locals {
      environment = "production"
      instance_count = var.is_high_demand ? 3 : 1
    }
    ```
    
* **Usage**:
    
    ```bash
    resource "aws_instance" "example" {
      count = local.instance_count
      tags = {
        Environment = local.environment
      }
    }
    ```
    

#### **8.2 Dynamic Blocks**

Dynamic blocks create configurations based on conditions or iterables, allowing for flexible resource definitions.

* **Example**: Define security group rules dynamically.
    
    ```bash
    resource "aws_security_group" "example" {
      name = "example-sg"
    
      dynamic "ingress" {
        for_each = var.ingress_rules
        content {
          from_port   = ingress.value.from_port
          to_port     = ingress.value.to_port
          protocol    = ingress.value.protocol
          cidr_blocks = ingress.value.cidr_blocks
        }
      }
    }
    ```
    

#### **8.3 Modules for Reusability**

Modules allow you to encapsulate configurations and reuse them across different environments.

* **Creating a Module**:
    
    * Folder structure:
        
        ```bash
        ├── main.tf
        └── modules
            └── vpc
                ├── main.tf
                ├── variables.tf
                └── outputs.tf
        ```
        
* **Using a Module**:
    
    ```bash
    module "vpc" {
      source        = "./modules/vpc"
      environment   = var.environment
      cidr_block    = var.vpc_cidr_block
    }
    ```
    

---

### **9\. Using Variables with** `.tfvars` Files

#### **Defining Variables in Terraform**

Terraform allows you to define variables in multiple ways for flexibility and environment-specific configurations:

* **Variable Block**: Define variables in configuration files.
    
    ```bash
    hclCopy codevariable "instance_type" {
      description = "EC2 instance type"
      type        = string
      default     = "t2.micro"
    }
    ```
    
* **Using** `.tfvars` Files: For managing environment-specific values, `.tfvars` files like `dev.tfvars` and `prod.tfvars` help provide different configurations.
    
    * Example (`dev.tfvars`):
        
        ```bash
        instance_type = "t2.small"
        region        = "us-west-2"
        ```
        

#### **9.2 Loading Variables**

* To specify a `.tfvars` file:
    
    ```bash
    terraform apply -var-file="dev.tfvars"
    ```
    
* You can also define variables directly in the command line:
    
    ```bash
    terraform apply -var="instance_type=t2.large"
    ```
    

#### **9.3 Variable Precedence**

Terraform loads variables in the following order, with the last loaded overriding the previous:

1. `.tfvars` files specified in the command.
    
2. `.tfvars` files automatically loaded (`terraform.tfvars` or `<workspace>.tfvars`).
    
3. Environment variables (e.g., `TF_VAR_instance_type`).
    
4. Default values in `variable` blocks.
    

---

### **10\. Additional Terraform Commands**

#### **10.1** `terraform graph`

* Generates a visual representation of the dependency graph in DOT format, useful for visualizing complex configurations.
    
* **Command**:
    
    ```bash
    terraform graph | dot -Tpng > graph.png
    ```
    

#### **10.2** `terraform fmt -check`

* Checks formatting without making changes, useful for CI/CD pipelines.
    
    ```bash
    terraform fmt -check
    ```
    

---

This complete guide provides a full toolkit for managing Terraform projects, from basic commands to advanced options for imports, debugging, variable handling, and lifecycle management. Each command and feature enhances control and flexibility, making Terraform a powerful tool for infrastructure management.
