Provisioning VMs with Terraform


Terraform is a resource provisioning tool based on a declarative approach. It is an Infrastructure-as-Code approach that allows you to describe the resources you would like to allocate and that takes care of the allocation for you.

To use it, you will first need to install Terraform. To install Terraform on Ubuntu 18.04, run the following commands:

wget https://releases.hashicorp.com/terraform/0.12.10/terraform_0.12.10_linux_amd64.zip
unzip terraform_0.12.10_linux_amd64.zip
sudo mv terraform /usr/local/bin/

We provide you with files to be used for a basic Terraform deployment: terraform-basics.tar.gz

After extracting the archive move into the terraform_basics directory.

Before using Terraform to allocate resources inside you project, we need to create a service account to enable Terraform to do so. To create the service account, run the following commands:

gcloud iam service-accounts create [SERVICE_NAME]
gcloud projects add-iam-policy-binding [PROJECT_NAME] --member serviceAccount:[SERVICE_NAME]@[PROJECT_NAME].iam.gserviceaccount.com --role roles/editor
gcloud iam service-accounts keys create ./[SERVICE_NAME].json --iam-account [SERVICE_NAME]@[PROJECT_NAME].iam.gserviceaccount.com

Note that:

We are now ready to allocate resources. We just have to modify some information in the provided files to make it correspond to your project:

The first thing to be done is to initialize Terraform for the target provider. For that, simply run:

terraform init

In our case Terraform will be initialized for GCP because this is the provider we declared in simple_deployment.tf.

Before launching the deployment, we can review the state that is going to be created using:

terraform plan

Finally we can launch the deployment using:

terraform apply

By default, our deployment is creating two VMs. You can modify this number in the file simple_deployment.tf. Then you can launch an update of the deployment and observe what happens. Here the command to be launched is again:

terraform apply

Finally, we can deallocate all the resources with the command:

terraform destroy