Making Terraform Dynamic with Interpolation
Continuing from the previous post we will try to introduce interpolation, flow control and looping. We will split the main.tf to different chunks of files that hold specific definitions to create the resources in GCP. We will create the provider.tf file which holds the provider configurations.
provider.tf
1 | variable "path" { default = "/home/vagrant/gcp_credentials/keys" } |
Firewall rules can be defined in a separate file as firewall.tf as below:
firewall.tf
1 | resource "google_compute_firewall" "allow-http-port" { |
Interpolation in Terraform helps to assign values to variables, this way we can dynamically manage the provisioning of resources in the cloud environments. Here we create variables.tf file with defines the variables that can be used in the script.
variable.tf
1 | variable "image" { default = "centos-8" } |
We will then create a seperate file httpd_install.sh where we install the web servers into the compute instances.
httpd_install.sh
1 | sudo yum update |
Now lets define the main.tf that reffers to the interpolation, firewall rules and the script to install the apache webservers.
main.tf
1 | resource "google_compute_instance" "default" { |
Now by carefully observing main.tf, we see that the lines refer to the variables defined in the variables.tf
1 | count = length(var.name_count) |
Further the above lines also shows the looping and flow control. Here we are looping to create 3 compute instances of type production grade. Below we see clear interpolation the terraform which refers the image and machine_size defined in the variables.tf
boot_disk {
initialize_params {
image = var.image
size = var.machine_size
}
}
The below line initializes the installation of apache webservers with httpd_install.sh script.
metadata_startup_script = "${file("httpd_install.sh")}"
Hence the output.tf will look like below:
output.tf
1 | output "machine_type" { |
the overall files created in this regard is as below:
1 | ---/gce/ |
The results of the above experiments are as below: