First time at Zeet?

26 Sep
2023
-
9
min read

A Comprehensive Guide to Terraform Commands

Terraform is a powerful tool for building infrastructure as code. This blog post will give you an overview of the essential Terraform commands you need to become proficient in provisioning infrastructure on any Cloud.

Jack Dwyer

Product
How To
Content
heading2
heading3
heading4
heading5
heading6
heading7

Share this article

Terraform at a High Level

Terraform is one of the hottest infrastructure as code tools out there right now, and for good reason. With Terraform, you can spin up servers, load balancers, databases and more with just a few commands. No more clicking through clunky cloud consoles - Terraform lets you define and provision your infrastructure using code.

To get started with Terraform, you'll need to familiarize yourself with the basic commands. There are commands to plan your infrastructure, build it, update it, and tear it down. Using Terraform commands, you can go from zero to deployed in minutes. In this post, we're going to cover all the essential Terraform commands you'll need to know, from init to apply to destroy. We'll explore how to provision and manage infrastructure across clouds like Google Cloud, AWS and Azure using Terraform's CLI.

By the end, you'll be writing Terraform configurations, planning infrastructure changes, and applying updates with the best of 'em. You'll be well on your way to mastering Terraform and all its various terraform commands. So sit back, grab a coffee, and let's get to it! 

Terraform Init, Plan and Apply: Ready, Set, Deploy!

The first set of Terraform commands we'll cover are init, plan and apply. These are the three commands you'll use the most in your Terraform workflow.

The first thing you'll want to do with any Terraform configuration is run 'terraform init'. This initializes your working directory and downloads any providers defined in your config. Think of it as installing dependencies for your Terraform code.

Running 'terraform init' is simple. Just open up your terminal, cd into the directory with your Terraform files, and run:

terraform init

Terraform will install the providers listed in your .tf files and you'll be ready to start using Terraform commands. You'll need to run init anytime you add a new provider to your config.

Now that your workspace is initialized, you're ready to start running some of the more exciting Terraform commands. The next step is planning your infrastructure with terraform plan. This will show you what Terraform intends to create, modify or destroy. This is a dry run and will not actually make any changes to your infrastructure. Running plan is a best practice as it allows you to preview changes before applying them. Pretty handy, right?

Once you've reviewed the plan and are satisfied with the proposed changes, you can apply them with terraform apply. Terraform apply executes the plan and builds/updates your infrastructure. This command creates, updates and deletes resources according to the configuration files in your working directory. Your servers, load balancers and databases will spring to life before your eyes (figuratively speaking, of course). Apply will prompt you to confirm the plan before making any changes. Type "yes" to proceed.

A typical workflow using these commands would be:

  1. Write your Terraform configuration
  2. Run 'terraform init' to initialize
  3. Run 'terraform plan' to preview changes
  4. Run 'terraform apply' to deploy the changes

With just these three commands, you can go from nothing to deployed infrastructure. You'll want to run these commands in order each time you modify your Terraform configuration. A good practice is to incorporate them into a CI/CD pipeline so infrastructure changes go through a review and approval process before being applied.

Using init, plan and apply, you can stand up infrastructure across multiple clouds with just a few commands. These commands form the foundation of your Terraform workflow, so get familiar with them! In the next section, we'll look at how to tear down infrastructure using the destroy command.

Terraform Destroy and Taint: Deprovisioning Infrastructure

Now that you've used Terraform to provision your infrastructure, at some point you'll want to deprovision it, right? That's where 'terraform destroy' comes in. This command will destroy the Terraform-managed infrastructure. So if you built a VM, load balancer and database with Terraform, terraform destroy will remove all of those resources.

To destroy infrastructure, just run:

terraform destroy

Terraform will prompt you to confirm the destruction, unless you specify '-force'. It will then proceed to remove all resources it had created.

Sometimes you may want to rebuild just a single resource, rather than destroying everything. In that case, you can use terraform taint. This "taints" a resource, marking it for recreation. When you next run 'terraform apply', Terraform will destroy that single resource and recreate it.

To taint a resource, run:

terraform taint resource_type.resource_name

For example, to taint an AWS EC2 instance named "example", run:

terraform taint aws_instance.example

On the next 'apply', Terraform will destroy that EC2 instance and create a new one in its place.

If you make a mistake and 'taint' a resource you didn't mean to, use 'terraform untaint' to unmark it. Terraform will then skip recreating that resource on the next apply.

So in summary, use 'terraform destroy' to de-provision all your infrastructure when you're done with it, 'terraform taint' to mark a single resource for recreation, and 'terraform untaint' to undo a taint. With these commands, you have full control over the lifecycle of your Terraform resources.

Terraform gives you a simple way to manage infrastructure from cradle to grave. Now that you've got the basics of provisioning and deprovisioning down, let's look at some other useful terraform commands for managing state, importing resources, and more!

Terraform Output, Import, and State

Terraform output, import, and state commands allow you to view resource attributes, import existing resources into Terraform management, and manage Terraform's state file. Let's take a closer look at each of these commands.

Terraform output prints output values from the state file. This allows you to view attributes of resources after Terraform has applied changes. For example, if you provision an EC2 instance, you can use terraform output to view the public IP and DNS name of the instance. Pretty handy!

Terraform import imports existing infrastructure into Terraform state. Say you've already got resources running in Google Cloud, but now you want to manage them with Terraform. Terraform import allows you to import those existing resources into Terraform state so you can manage them going forward.

Terraform state commands manage Terraform's state file. The state file keeps track of resources Terraform has created so it knows what it's managing. State commands like terraform state mv, terraform state pull, and terraform state push allow you to move, pull and push state files. You'll want to use remote state with a backend like Google Cloud Storage to store the state file.

Using Terraform output, import, and state commands, you'll have full visibility into your infrastructure resources and be able to import any existing resources into Terraform management. The state file is the source of truth for Terraform, so being able to manage it is crucial. These commands, along with init, plan and apply, provide you with all the tools you need to provision and manage infrastructure with Terraform.

Pretty cool stuff, right? We've only just scratched the surface of what's possible with Terraform.

Terraform Validate, Format and Console

So you've got your Terraform configuration written, but how do you know if it's valid before running terraform apply? Enter terraform validate. This handy command will check your Terraform syntax and configuration for any errors. Running validate is a best practice and can save you from potential disasters down the road.

Once validate says your config looks good, you'll want to run 'terraform format' to standardize the style of your code before applying it. Format will re-write your entire config in a canonical style, making it easier for others to read and work with. Consistent style is key for any infrastructure as code tool, so get into the habit of running 'terraform format' often.

Now for some fun - the 'terraform console'! This interactive command line environment lets you experiment with Terraform interpolations and functions. In the console, you can enter expressions and see their outputs immediately. It's a great way to test how certain variables, attributes or other references will resolve without having to do a full 'terraform apply'. I use the console all the time when I'm building new Terraform configurations to make sure I'm getting the outputs I expect before unleashing changes into production.

The validate, format and console commands are extremely useful for ensuring high quality Terraform code. Validate catches errors, format enforces style standards, and console lets you experiment freely. Using these three commands as part of your Terraform workflow can help reduce errors, enable collaboration, and give you more confidence in your infrastructure as code. Terraform gives you a lot of power, so taking advantage of these commands helps ensure you're using that power responsibly!

Terraform Import: Bringing Outside Resources Into the Fold

So you've got some existing infrastructure already running that you'd like to bring under Terraform's management. No problem - that's exactly what the 'terraform import' command is for. Terraform import will import your existing resources into the Terraform state, allowing you to manage them with all the usual Terraform commands going forward.

To import a resource into Terraform, you need to know its type and ID. The type is the kind of resource it is, like aws_instance or google_compute_instance. The ID is the unique identifier for that resource in your cloud platform. Once you have those details, you can run:

terraform import {type} {id}

For example, if I wanted to import an EC2 instance with ID i-abcd1234, I would run:

terraform import aws_instance.my_instance i-abcd1234

This would import the instance into Terraform under the name my_instance. I could then add the my_instance resource to my Terraform config, and Terraform would recognize it as the imported instance.

From there, you can run 'terraform plan' to see Terraform's plan for managing the resource, and 'terraform apply' to officially bring it under Terraform's control. Your imported resource will now behave just like any other resource in your Terraform config.

The 'terraform import' command allows you to gradually transition existing infrastructure over to Terraform, rather than having to rebuild everything from scratch. It's a great way to start using Terraform on legacy systems and work your way towards fully automated infrastructure as code. Just remember - once a resource is imported, Terraform owns the management of that resource. So make sure you're ready to let Terraform maintain control before importing!

Terraform Refresh and Debug

So your infrastructure is deployed and humming along nicely. But have you refreshed your Terraform state recently? If not, your Terraform state could be out of sync with what's actually deployed. That's where 'terraform refresh' comes in. This handy command will scan your infrastructure and update the Terraform state to match. It's a good idea to run terraform refresh periodically to make sure your state is accurate.

Every now and then, things don't go as planned and you need to debug your Terraform configuration. For those times, Terraform provides the 'terraform debug' command. This will print debugging information about your Terraform configuration, including the configuration syntax, values of variables, etc. The debug info can uncover issues with your config that are causing errors.

To use terraform debug, just run:

terraform debug

This will print the debug info for your current Terraform configuration. The output will show you things like:

  • The syntax tree of your configuration
  • The values of any defined variables
  • The addresses of resources in your config

The debug info can be really helpful for troubleshooting errors and other issues in your Terraform code. I often use it when a plan or apply fails for some reason, to get more details on what might be going wrong.

Between 'terraform refresh' and 'terraform debug', you'll be well equipped to keep your infrastructure in working order and troubleshoot any problems. Terraform gives you the commands you need to manage resources properly and fix issues as they come up. These tools, combined with Terraform's simple syntax and workflow, make infrastructure management almost too easy!

Terraform Workspaces: Keeping Environments Separate

So your Terraform configuration has been working great, deploying resources into production. But now you want to spin up a staging environment. How can you use the same Terraform code to manage two separate environments? Enter Terraform workspaces.

Workspaces are a way to isolate multiple deployments from a single Terraform configuration. You can have one workspace for production, another for staging, and so on. Each workspace will have its own Terraform state file, variables, and outputs. This allows you to use one set of Terraform files to manage many environments.

To create a new workspace, run:

terraform workspace new {name}

So to create staging and production workspaces, you'd run:

terraform workspace new staging
terraform workspace new production

Then to switch between workspaces, use:

terraform workspace select {name}

When you switch workspaces, Terraform will change to using that workspace's state file and variables. So you can deploy to staging, switch to production, and deploy there using the same configuration. Nifty!

Workspaces give you an easy way to separate your infrastructure environments while reusing the bulk of your Terraform code. You can have workspace-specific variables and state files, but share modules, data sources, and resource configurations across workspaces. This allows you to define your infrastructure in a reusable, modular way.

A few other useful workspace commands:

terraform workspace list ## Lists all workspaces
terraform workspace show ## Shows the current workspace
terraform workspace delete {name} ## Deletes the given workspace

Using workspaces in your Terraform configuration is a best practice and will make managing multiple environments a breeze. No more duplicating code for production and staging - just spin up a new workspace and deploy! Terraform workspaces provide a simple solution for achieving reusable, multi-environment infrastructure as code.

Best Practices for Terraform Commands

Now that you've got a handle on all the main Terraform commands, let's talk best practices. Following these tips will make you a Terraform pro in no time.

  1. First, always run 'terraform init' when you start working with a new configuration or add a new provider. Init downloads the providers you need and sets up your working directory. Without running init first, other commands like plan and apply won't work properly.
  1. Second, get into the habit of running 'terraform plan' before every apply. Plan shows you exactly what changes Terraform will make to your infrastructure. Review the plan to make sure there are no unwanted surprises, then apply with confidence knowing what's going to happen. Plan is a dry run, so it's a chance to catch issues before they hit production.
  1. Third, use version control for your Terraform code! Keep your configurations in Git or a similar version control tool. That way you can track changes over time, revert mistakes, and collaborate with others. Version control is a must for any infrastructure as code tool.
  1. Fourth, keep your Terraform state files small and separate environments. Don't put production and staging resources in the same state file. Use Terraform workspaces or separate configurations for different environments. This makes your states easier to manage and avoids issues that could arise from mixing environments.
  1. Fifth, run 'terraform refresh' periodically, especially after resources have been modified outside of Terraform. Refresh syncs your state with real-world infrastructure, so running it regularly ensures your state is accurate. Out of date state can lead to problems, so refresh is well worth the effort.
  1. Finally, use CI/CD to automate your Terraform apply process. Have changes go through a review process. This avoids risky manual applies and ensures changes follow your workflow.

Following these best practices will make you a Terraform pro in no time. For Zeet users, the good news is all these best practices are done for you out of the box, but it’s still good to know what’s happening under the covers. Even so, start with the basics, use version control, keep your states clean, refresh regularly, and automate with CI/CD. If you make these tips a habit, you'll be using Terraform to deploy infrastructure like a champ! 

Getting Started with Terraform and Google Cloud

Now that you've got a handle on Terraform commands, let's walk through an example of how to use Terraform to manage Google Cloud infrastructure. Terraform has a Google Cloud Platform (GCP) provider that allows you to provision GCP resources.

To use the GCP provider, you need to:

  1. Enable the APIs for the GCP services you want to use. This can be done in the GCP Console or with gcloud.
  2. Create a service account key and save it as a JSON file. This will be used by Terraform to authenticate to GCP.
  3. Add the GCP provider to your Terraform config, specifying the path to your service account key file:
provider "google" {
  credentials = file("/path/to/service-account.json")
  project = "your-gcp-project-id"
  region = "us-central1"
}

4. Define the GCP resources you want to provision in your config. For example, to deploy a Compute Engine instance:

resource "google_compute_instance" "example" {
  name = "terraform-instance"
  machine_type = "e2-medium"
  zone = "us-central1-a"

  boot_disk {
    initialize_params {
    image = "debian-cloud/debian-9"
  	}
	}

	network_interface {
		network = "default"
	}
}

5. Run `terraform init` to install the GCP provider, then `terraform plan` and `terraform apply` to deploy your resources!

Terraform supports managing many GCP resources, including:

  • Compute Engine (instances, disks, etc.)
  • Kubernetes Engine
  • Cloud Storage
  • Cloud SQL
  • VPC networks
  • Load balancers
  • And much more!

You can deploy entire application infrastructures on GCP using Terraform. The possibilities are endless!

To destroy resources, just run terraform destroy. This will remove everything Terraform created.

And that covers the basics of using Terraform with Google Cloud!

Terraform + Zeet: Your Way to Cloud Success

And that's the basics of provisioning infrastructure with Terraform! We covered all the essential Terraform commands, best practices for using them, and how to get started with the GCP provider. With Terraform, you can go from nothing to a full application infrastructure with just a few commands.

If managing cloud resources with Terraform sounds appealing but you want to accelerate your efforts, try out Zeet. Zeet is a DevOps platform for cloud native teams that provides managed Terraform. With Zeet, you get access to a prebuilt Terraform Blueprint, automation, ci/cd, and best practices, like auto-scaling, networking, and audit-logs, baked right in. Zeet allows you to spend less time wrangling infrastructure and more time shipping features. In fact, if you’re using Zeet with Terraform, you don’t need to worry about any of the commands you learned today. Zeet will take care of the Terraform init and apply steps as well as the other Terraform commands.

Terraform and Zeet make a powerful combination for deploying to the cloud. Need to deploy an S3 Bucket, SQS Instance, and a Kubernetes cluster with Terraform? A few clicks on Zeet and it's up. VPC, load balancers, managed instance groups? Zeet's got you covered. With Terraforma and Zeet you can focus on your applications and let us handle the infrastructure.

Navigate your Terraform journey like a pro with these commands and tips. And remember, when in doubt, always 'terraform apply --help', or just use Zeet! 😉

Happy shipping!

Subscribe to Changelog newsletter

Jack from the Zeet team shares DevOps & SRE learnings, top articles, and new Zeet features in a twice-a-month newsletter.

Thank you!

Your submission has been processed
Oops! Something went wrong while submitting the form.