Terraform Commands

  • terraform init - initializes the current directory

terraform init
-- What is terraform init ?

The terraform init command is used to initialize a Terraform working directory. This command performs several important tasks:

  1. Download Provider Plugins: Terraform will download and install the provider plugins specified in the configuration files. Providers are responsible for managing the lifecycle of a resource (e.g., AWS, Azure, Google Cloud).

  2. Initialize Backend: If a backend configuration is specified, terraform init will initialize the backend, which is used to store the state of your infrastructure. This is particularly important for collaboration and for maintaining state consistency.

  3. Install Modules: If your configuration includes modules, terraform init will download and install these modules from the specified sources (e.g., a local path, a Git repository, or the Terraform Registry).

  4. Validate Configuration: It checks for errors in the configuration files and ensures that all necessary files are present.

  5. Prepare the Working Directory: It sets up the directory for use with other Terraform commands, like terraform plan and terraform apply.

Running terraform init is typically the first step you take after creating or cloning a new Terraform configuration, as it sets up everything needed to work with your infrastructure code.

Here is an example of how to use the terraform init command:

 

  • terraform refresh - refreshes the state file 

    -- What is terraform refresh ?
     

    The terraform refresh command is used to reconcile the state of the Terraform-managed infrastructure with the real-world resources. It updates the state file to reflect the actual state of the resources.

    Here is what terraform refresh does in more detail:

  • Read Current State: It reads the current state of the resources as described in the state file.

  • Query Real Infrastructure: It queries the actual state of the resources from the providers (e.g., AWS, Azure, Google Cloud) to get the current status.

  • Compare States: It compares the state information from the state file with the actual state of the resources.

  • Update State File: If there are any differences between the state file and the real-world resources, it updates the state file to reflect the current state.

The terraform refresh command helps ensure that the state file is up-to-date with the real-world resources, which is crucial for accurate planning and applying of changes. However, as of Terraform v0.15.0, the terraform refresh command is deprecated. Its functionality is integrated into the terraform plan and terraform apply commands. When you run these commands, they automatically refresh the state before executing.

Here is an example of using the terraform refresh command:


  • terraform output - views Terraform outputs
    --what is terraform output

    The terraform output command is used to extract and display the values of output variables defined in a Terraform configuration. These output variables are typically defined in the outputs.tf file and are used to expose information about the resources created by your Terraform configuration.

    Here are the main uses of the terraform output command:

  • Display All Outputs: By running terraform output without any arguments, it will display all the output values defined in your Terraform configuration.

  • Display a Specific Output: You can specify the name of a particular output variable to display only that value.

  • Format Output: The command allows formatting options to display the output in various formats (e.g., JSON).

Here are some examples of how to use the terraform output command:

  • terraform apply - applies the Terraform code and builds stuff
    -- What is terraform apply ?

    The terraform apply command is used to apply the changes required to reach the desired state of the configuration. This command executes the actions proposed in the Terraform plan, creating, updating, or destroying resources as needed to align the actual state with the desired state described in the configuration files.

    Here are the main steps involved in the terraform apply process:

  • Refresh State: Terraform refreshes the state to ensure that it has the latest information about the resources.

  • Plan Execution: If you haven’t already created a plan file with terraform plan, Terraform will create an execution plan that shows what actions will be taken to achieve the desired state.

  • Approval: Terraform will prompt for approval before applying the changes unless the -auto-approve flag is used.

  • Apply Changes: Terraform applies the changes to the infrastructure as defined in the plan. This includes creating, updating, or deleting resources.

  • Update State: After making the changes, Terraform updates the state file to reflect the current state of the resources.

Here are some examples of how to use the terraform apply command:

  1. Apply Changes with Prompt for Approval:

    terraform apply
     

  2. This command will show the execution plan and prompt you for approval before applying the changes.

  3. Apply Changes Without Prompting for Approval:

    terraform apply -auto-approve
     

  4.  Apply a Specific Plan File:

    terraform plan -out=tfplan
    terraform apply tfplan
     

     

  • terraform destroy - destroys what has been built by Terraform
    -- What is terraform destroy ?

    The terraform destroy command is used to delete all the resources that have been created by your Terraform configuration. This command is useful when you want to tear down your infrastructure completely.

    Here is what the terraform destroy command does:

  • Refresh State: Terraform refreshes the state to ensure it has the latest information about the resources.
  • Generate Plan: It creates a destruction plan that shows what resources will be deleted.
  • Approval: Terraform prompts for approval before destroying the resources unless the -auto-approve flag is used.
  • Destroy Resources: It deletes the resources as specified in the plan.
  • Update State: After destroying the resources, Terraform updates the state file to reflect the changes.

Here is an example of how to use the terraform destroy command:

  1. Destroy Resources with Prompt for Approval:

  • terraform graph - creates a DOT-formatted graph
    -- Terraform graph :

    The terraform graph command is used to generate a visual representation of the resources in a Terraform configuration and their relationships. This command creates a DOT-formatted graph that can be used with visualization tools like Graphviz to produce a graphical representation of your infrastructure.

    Here is how the terraform graph command works:

  • Generate Graph: It creates a graph in DOT format that describes the dependency relationships between resources in the configuration.
  • Output to Console: By default, it outputs the DOT format graph to the console.
  • Export to File: You can redirect the output to a file to use with graph visualization tools.

terraform graph : 

This command outputs the DOT format graph to the console. 

Export Graph to a File:

terraform graph > graph.dot

This command saves the DOT format graph to a file named graph.dot.

 Visualize the Graph:

To visualize the graph, you can use a tool like Graphviz. For example, to generate a PNG image from the DOT file:

 dot -Tpng graph.dot -o graph.png

This command uses Graphviz to create a PNG image from the DOT file.

 

Example Configuration and Graph Generation:

  1. Terraform Configuration:

    provider "aws" {
      region = "us-west-2"
    }

    resource "aws_instance" "example" {
      ami           = "ami-0c55b159cbfafe1f0"
      instance_type = "t2.micro"
    }

    output "instance_id" {
      value = aws_instance.example.id
    }
     

    Initialize and Apply:

    terraform init
    terraform apply
     

    Generate and Visualize Graph:

    terraform graph > graph.dot
    dot -Tpng graph.dot -o graph.png
     

The resulting graph visualizes the relationships and dependencies between the resources defined in the Terraform configuration. This can be especially helpful for understanding complex infrastructures and debugging dependency issues.


  • terraform plan - a dry run to see what Terraform will do
    -- terraform plan :

    The terraform plan command is used to create an execution plan, showing what actions Terraform will take to reach the desired state defined in the configuration files. This command performs a "dry run" without making any changes to the actual infrastructure. It's a crucial step for reviewing and verifying changes before applying them.

    Here is what the terraform plan command does:

  • Refresh State: Terraform refreshes the state to ensure it has the latest information about the resources.
  • Generate Execution Plan: It compares the current state with the desired state defined in the configuration files and generates a plan that outlines the changes required to achieve the desired state. This includes resources to be created, updated, or destroyed.
  • Display Plan: The plan is displayed on the console, allowing you to review the proposed changes.

 

 

 

  • terraform show 
    terraform state show aws_instance.example
    resource "aws_instance" "example" {

    The terraform show command is used to provide a human-readable output of the state or plan. This command is useful for inspecting the current state of your infrastructure or the details of a Terraform plan. It can be used to get a clear and detailed view of what resources are managed by Terraform and their current attributes.

1. Show the Current State: By default, terraform show displays the current state of your infrastructure.

 terraform show

This will output the current state file in a human-readable format.

2.  Show a Specific Plan: You can use terraform show to display the details of a saved plan file. This is useful for reviewing the plan before applying it.

terraform show <plan-file>

Replace <plan-file> with the name of your saved plan file (e.g., tfplan).

3. JSON Output: The -json flag can be used to output the state or plan in JSON format, which is useful for programmatic processing.

terraform show -json 

4. To show a plan file in JSON format:

terraform show -json <plan-file>
 

Example Workflow

  1. Create Configuration Files:

    provider "aws" {
      region = "us-west-2"
    }

    resource "aws_instance" "example" {
      ami           = "ami-0c55b159cbfafe1f0"
      instance_type = "t2.micro"
    }
     

 Initialize the Directory:

terraform init
 

Apply the Configuration:

terraform apply
 

Show the Current State:

terraform show
 

 Save a Plan to a File:

terraform plan -out=tfplan
 

Show the Plan:

terraform show tfplan
 

This will display the details of the saved plan in a human-readable format.

Show the Plan in JSON Format:

terraform show -json tfplan
 

This will display the details of the saved plan in JSON format, which can be useful for further processing or integration with other tools.

The terraform show command is a versatile tool for inspecting the state and plans in Terraform. It provides a way to review the current state of resources or the changes proposed by a plan, helping you ensure that your infrastructure is managed accurately and predictably.

When you run the terraform plan -out=tfplan command, Terraform generates an execution plan and saves it to a binary file named tfplan in the current working directory. This plan file can then be used with the terraform apply command to apply the exact changes outlined in the plan.

Example Usage

  1. Generate and Save the Plan:

    terraform plan -out=tfplan
     

    This command will:

  2. Generate an execution plan based on the current configuration and state.
  3. Save the plan to a binary file named tfplan in the current directory.

 Apply the Saved Plan:

terraform apply tfplan
 

This command will:

  • Read the plan from the tfplan file.
  • Apply the changes specified in the plan to your infrastructure.

 

Comments

Popular posts from this blog

1. Terraform workflow using terraform commands

Terraform-Interview- QUESTIONS

Terraform Practicle Questions