Terraform workflow
A basic Terraform workflow consists of the following two steps:
Init
Apply
In this first step, terraform init
initializes Terraform and downloads all the necessary configuration files. You see that after init
is run, there is a hidden directory named .terraform
. This directory is where Terraform stores various configuration files. You must run the initialization step every time you write a new configuration file. Don’t worry; you can run this command multiple times, and you learn over time when you need to rerun it. If in doubt, run it again as it only takes a few seconds.
The second step, terraform apply
, consists of two phases. First, Terraform creates an execution plan, then it executes this plan. The execution plan is an internal plan of the actions Terraform will perform and in which order. Terraform outputs this plan, including a summary of how many resources will be added, changed, and destroyed. You should always review this output carefully. Once you have confirmed that the plan does what you intended, you can confirm, and Terraform actually provisions the cloud resources.
You can also run the two phases explicitly by running terraform plan
, saving the plan in a file, and then running terraform apply
against that file, like so:
$ terraform plan --out=plan $ terraform apply plan
This is often done in CI/CD pipelines, and we will return to it later.
One of the advantages of IaC is that you can quickly remove resources. This is not only useful during the development phase, as you can test things quickly, but it also can help you save costs. At the end of the workday, you can remove all the resources and reprovision them the next day. To destroy resources in Terraform, simply execute the following command:
$ terraform destroy
Now, after you have run terraform destroy
and run terraform apply
twice, you’ll notice that the second time you run terraform apply
, Terraform reports no changes
, and no action is performed. The next chapter discusses how Terraform decides what actions to take.
There are many more Terraform commands, and we introduce them throughout the book. For now, remember the following four commands:
terraform init
to initializeterraform plan
to view and create a Terraform planterraform apply
to actually provision the resourcesterraform destroy
to remove all resources
Now that we have described the basic workflow of Terraform and shown how you run Terraform in Google Cloud Shell, let’s look at the different ways of running Terraform on your local computer.