Skip to main content

Command Palette

Search for a command to run...

Exploring Terraform Lifecycle Commands: A Full Guide

Overview of Key Terraform Commands

Updated
•8 min read•View as Markdown
Exploring Terraform Lifecycle Commands: A Full Guide
M

Crowd to Cloud

Terraform CLI Commands

1. terraform init - Initialization

terraform init is the first command to run when working with a new or existing Terraform configuration. It initializes the directory, downloads provider plugins, and sets up the backend where Terraform stores its state files.

Purpose:

  • Download the provider plugins (e.g., AWS, Azure).

  • Initialise the working directory.

  • Set up the backend for storing state.

Syntax:

terraform init [options]

Example:

terraform init

Key Options:

  • -input=false: Disables interactive prompts.

  • -backend-config: Override backend configuration settings.

Explanation:

When terraform init is run, Terraform:

  • Checks the configuration file for required providers.

  • Downloads those provider plugins to .terraform/plugins.

  • Configures the backend (e.g., S3, local storage) to store the Terraform state.

Tips:

  • You only need to run init once when setting up the working directory or after modifying the backend configuration.

  • Running init does not make changes to infrastructure, only to the local configuration.


2. terraform plan - Planning

terraform plan is used to preview the actions that Terraform will take to modify infrastructure. It compares the current state of infrastructure with the desired state defined in the configuration files and generates an execution plan.

Purpose:

  • Preview the changes before applying them.

  • Verify if the desired infrastructure changes are correct.

Syntax:

terraform plan [options]

Example:

terraform plan

Key Options:

  • -out=planfile: Saves the generated plan to a file to use with apply.

  • -var 'key=value': Passes variables from the command line.

  • -target=resource: Focuses the plan on a specific resource or module.

Explanation:

Running terraform plan allows you to see what Terraform will do (create, update, or destroy) without actually applying any changes. This gives you the opportunity to review and make sure the plan aligns with your goals.

Output:

The output shows:

  • Add: Resources that will be created.

  • Change: Resources that will be updated.

  • Destroy: Resources that will be deleted.

Tips:

  • Use the -out option to save the plan to a file if you intend to apply it later. This ensures the same plan is applied.

  • Always run terraform plan before applying changes to avoid unexpected modifications.


3. terraform apply - Applying Changes

terraform apply is the command that actually provisions, updates, or destroys infrastructure. It takes the desired state from the configuration files and applies it to the real-world infrastructure.

Purpose:

  • Create, modify, or destroy infrastructure based on the execution plan.

Syntax:

terraform apply [options] [planfile]

Example:

terraform apply

Key Options:

  • -auto-approve: Skips interactive approval of the plan before applying.

  • -var 'key=value': Passes variables from the command line.

Explanation:

Running terraform apply applies the actions described in the plan to real infrastructure. If no saved plan file is provided, Terraform will create a new plan before applying it.

Output:

After applying, Terraform will output the list of resources that were created, modified, or destroyed, as well as their corresponding identifiers (like instance IDs).

Tips:

  • Use the -auto-approve option in automation pipelines to skip manual approval.

  • If you saved the plan from the plan command using -out=planfile, pass that plan file to apply to ensure exactly those changes are applied:

    Copy

        terraform apply planfile
    

4. terraform destroy - Destroying Resources

terraform destroy is the opposite of apply. It is used to remove infrastructure managed by Terraform. This command is often used during teardown phases in development environments.

Purpose:

  • Destroy or tear down infrastructure.

Syntax:

terraform destroy [options]

Example:

terraform destroy

Key Options:

  • -auto-approve: Skips interactive approval for destruction.

  • -target=resource: Destroy a specific resource or module.

Explanation:

terraform destroy compares the current state of the infrastructure to the configuration and destroys all resources managed by Terraform. By default, it asks for confirmation before proceeding.

Tips:

  • Use -auto-approve to skip the confirmation prompt.

  • Be cautious when using destroy in a production environment, as it will remove all resources managed by Terraform.


5. terraform fmt - Formatting Code

terraform fmt formats Terraform configuration files (.tf) to ensure they follow a standard style.

Purpose:

  • Format configuration files to improve readability.

Syntax:

terraform fmt [options] [path]

Example:

terraform fmt

Key Options:

  • -recursive: Formats files in all subdirectories.

Explanation:

Running terraform fmt ensures that all configuration files conform to the standard formatting style for Terraform, which includes indentation, spacing, and alignment of arguments.

Tips:

  • Run terraform fmt regularly to keep your configuration files clean and readable.

6. terraform validate - Validating Configurations

terraform validate checks whether the Terraform configuration files are syntactically valid and internally consistent. This is useful for catching errors early in the development process.

Purpose:

  • Validate the configuration files before applying changes.

Syntax:

terraform validate [options] [path]

Example:

terraform validate

Explanation:

terraform validate checks the syntax and consistency of the configuration files but does not validate if resources are correctly configured in the cloud provider.

Tips:

  • Run terraform validate before planning or applying to catch any syntax errors early.

  • It doesn’t access external systems, so it is fast and safe to run at any time.


Terraform Configuration Language (HCL)

The Terraform Configuration Language (HCL) is used to write configuration files that define your infrastructure. HCL is designed to be both human-readable and machine-friendly, making it easy to understand and automate.

Example Configuration:

provider "aws" {
  region = "us-west-2"
}
resource "aws_instance" "example" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"
}

This simple configuration defines an AWS provider and an EC2 instance resource. The provider block specifies the region, while the resource block defines the instance details.

Real-World Scenario: Suppose you need to deploy multiple EC2 instances across different regions. By modifying the provider block and using variables, you can easily manage configurations for different environments.

Providers and Provisioners

Providers: Providers are plugins that enable Terraform to interact with various cloud platforms and services. They are responsible for managing the lifecycle of resources. Examples include AWS, Azure, Google Cloud, and many others.

Example Provider Configuration:

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

Provisioners: Provisioners are used to execute scripts or commands on resources. They are typically used for bootstrapping tasks like installing software or configuring instances after they are created.

Example Provisioner Configuration:

resource "aws_instance" "example" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"

  provisioner "remote-exec" {
    inline = [
      "sudo apt-get update",
      "sudo apt-get install -y nginx",
    ]
  }
}

Real-World Scenario: If you need to install and configure a web server on a newly created EC2 instance, you can use a remote-exec provisioner to run the necessary commands as soon as the instance is ready.

Resources and Data Sources

Resources: Resources are the fundamental building blocks of your infrastructure. They represent components like virtual machines, databases, and networking elements. You define resources in your configuration files to create, update, or delete them.

Example Resource Configuration:

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

Data Sources: Data sources allow you to query information about your infrastructure. They enable you to fetch data from existing resources or services and use that data in your configurations.

Example Data Source Configuration:

data "aws_ami" "latest" {
  most_recent = true
  owners      = ["self"]
  filter {
    name   = "name"
    values = ["my-ami-*"]
  }
}

Real-World Scenario: When you need to use the latest Amazon Machine Image (AMI) for your instances, you can use a data source to dynamically fetch the most recent AMI ID.

Variables and Outputs

Variables: Variables allow you to parameterize your Terraform configurations, making them more flexible and reusable. You can define variables in a separate file or within the main configuration file.

Example Variable Definition:

variable "instance_type" {
  default = "t2.micro"
}

Example Resource Using Variable:

resource "aws_instance" "example" {
  ami           = "ami-12345678"
  instance_type = var.instance_type
}

Outputs: Outputs are used to extract information from your Terraform configurations and make it available after the deployment. They are useful for retrieving values like instance IP addresses or resource IDs.

Example Output Definition:

output "instance_ip" {
  value = aws_instance.example.public_ip
}

Real-World Scenario: By defining outputs for key resource attributes, such as IP addresses or database endpoints, you can easily reference these values in your deployment scripts or documentation.

State Management

Terraform uses a state file to keep track of the current state of your infrastructure. This file, typically named terraform.tfstate, is crucial for managing and applying changes to your infrastructure.

Key Points About State Management:

  1. State File: Stores information about the managed infrastructure.

  2. Remote State: You can store the state file remotely (e.g., in an S3 bucket) to enable collaboration and ensure consistency across teams.

  3. State Locking: Prevents concurrent operations that could corrupt the state file.

Example Remote State Configuration:

terraform {
  backend "s3" {
    bucket = "my-terraform-state"
    key    = "terraform.tfstate"
    region = "us-west-2"
  }
}

Real-World Scenario: In a team environment, storing the state file in a remote location like an S3 bucket ensures that everyone works with the same state, preventing conflicts and inconsistencies.

Conclusion

Terraform lifecycle commands are essential to managing the full infrastructure provisioning and management cycle. Commands like init, plan, apply, and destroy cover the basic infrastructure lifecycle, while others, like fmt, validate help maintain code quality and extract useful information.

Understanding these commands is crucial for effectively working with Terraform and ensuring a smooth workflow when managing your infrastructure as code.