Top 20 Terraform Interview Questions

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

Never miss a post!

Sign up for our newsletter and get FREE Development Trends delivered directly to your inbox.

You can unsubscribe any time. Terms & Conditions.
Categories

Are you preparing for DevOps interviews and looking for frequently asked terraform interview questions? Well, you have landed at the right place. In this blog, I will talk about the top 20 terraform interview questions that you must know.

Terraform is an important tool in the world of DevOps, hence you must showcase your knowledge on this tool well to get a lucrative job in this domain. I have created a collection of the most important questions on Terraform, which most interviewers often ask. So, let’s get started.

Terraform Interview Questions

Q1: Define Terraform

Terraform is an open-source tool used to create, change and version the infrastructure using a declarative configuration language – HashiCorp Configuration Language (HCL), or optionally JSON. It is a very popular DevOps tool across the world as it can handle very complex ‘infrastructure as a code’ with ease.

Q2: What are the features of terraform?

Below are the key features of Terraform:

  • Builds graph database for operators to provide them insights on resource dependencies.
  • Generates execution graph to tell the operators about the sequence of steps terraform will perform to add or change the configurations.
  • Translates HashiCorp Configuration Language configuration code into JSON
  • Specifies the number of modules added to Terraform.
  • Supports multiple cloud platforms like AWS, Azure, GCP through terraform providers.
  • Locks the module to make sure that at a particular time, only one person can make the changes.
  • Provides custom syntax which is very easy to use and helps in improving efficiency.
  • Organizes and maintains the configurations easily by breaking them into smaller parts.

Q3: Terraform is written in which programming language?

Terraform is written in the Go programming language.

Q4: What is terraform language, and what is its syntax?

Terraform language is the heart of terraform. Every configuration code is written in terraform language. Terraform language is declarative and used to define resources in terraform, which are basically infrastructure objects. Below is a sample syntax of terraform:

resource "aws_vpc" "main" {
  cidr_block = var.base_cidr_block
}
 "" "" {
  # Block body
   =  # Argument
}

Q5 : What is Terraform Plugins?

The providers and provisioners in Terraform are basically Terraform Plugins. They are executable binaries that are written in the Go programming language. Providers are the most popular plugins used by terraform to extend its capabilities and manage more types of infrastructure. Terraform has multiple built-in plugins, the SDK of terraform plugin currently supports providers type terraform plugin.

 

Q6 : How will you create a single EC2 instance on AWS using terraform?

You can use Terraform AWS module to create an EC2 instance on AWS:


module "ec2_cluster" {
source = "terraform-aws-modules/ec2-instance/aws"
version = "~> 2.0"
  name = "demo"
instance_count = 2
  ami = "ami-ebd02392" 
instance_type = "t2.micro" 
key_name = "user5" 
monitoring = true 
vpc_security_group_ids = ["sg-12345678"] 
subnet_id = "subnet-eddcdzz4"
  tags = {  
Terraform = "true"  
Environment = "stages"
  }
}

Q7 : What if you encounter a serious error and want to rollback?

If I encounter a serious error and want to rollback, I will recommit the previous stable code version and make it the current version again in the version control system. This will run a trigger in terraform to execute the previous version code. All the entities provisioned for the rollback must exist, which are required for the old code to run. In case because of any terraform run, the state file got corrupted, then you can rollback the state through terraform enterprise to get the previous latest state.

 

Q8 : How can I upgrade plugins on Terraform?

If you want Terraform to ignore the dependency lock file and install newer versions of terraform plugins, you can use the -upgrade option. There are multiple ways on which you can upgrade terraform plugins and modify terraform init’s plugin behavior:

  • -upgrade – When you use this option with terraform init command, all the selected plugins will get upgraded to the newest version that complies with the configuration’s version constraints. So, any selections recorded in the dependency lock file will be ignored by terraform.
  • -get-plugins=false – Skip plugin installation.
  • -plugin-dir=PATH – This will force the installation of the plugin to read plugins only from the specified directory.
  • -lockfile=MODE Set a dependency lockfile mode.

 

Q9 : How can you handle CLI authentication on terraform cloud?

With the login and logout commands, I can handle CLI authentications on terraform cloud. These commands help in automating the process of getting an API token for the Terraform Cloud user account.

The terraform login command automatically obtains and saves an API token for Terraform Cloud, Terraform Enterprise, or any other Terraform service host.

Syntax: terraform login [hostname]

The terraform logout command removes the terraform login credentials which were stored.

Syntax: terraform logout [hostname]

Terraform will assume you want to log out of Terraform Cloud at app.terraform.io. in cases where you do not provide an explicit hostname.

Q10 : What do you mean by IAC in Terraform?

IAC stands for Infrastructure as Code. In IaC, you configure, manage and deploy IT infrastructure using code. Multiple organizations today use IaC to spin hundreds of servers in different service providers like AWS, Azure or GCP. Even in terraform, you write the configuration codes in HashiCorp Configuration Language, which is very easy to read. These configurations file where you put the code has .tf extension. You can write the code for the desired state in the configuration you want and terraform will execute the required steps to reach that desired state.

Q11 : Do you know about the new factors in the latest v1.24.0 and v1.25.0 Terraform Azure Provider?

There are many new resources in the v1.24.0 and v1.25.0 Terraform Azure Provider with many new data resources. One such new resource is Azurerm_batch_certificate. It manages the certificate in the Azure batch. You can use this new resource to manage public IP, the prefix in networking. Another new data resource in the latest version includes Azurerm_firewall, with this resource, you can access the data for some already existing firewalls. Multiple bugs have also been fixed in the latest release. The Azurerm_app_service resource has some enhanced improvements.

 

Q12 : Does Terraform support themes?

Yes, terraform version 0.3.1 and above support Gtk themes efficiently. You can run the command cp /usr/wherever/THEMENAME/gtk/gtkrc $HOME/.gtkrc to enable the theme. If you get an error while opening the theme file, then edit the .gtkrc file and, after that, attach the below line at the starting of the file.

pixmap_path”/usr/wherever/THEMENAME/gtk”

Now the theme will load on startup.

Q13 : Can I use Terraform for on-premises infrastructure?

Yes, there are multiple terraform providers using which you can use terraform for on-premises infrastructure that has the functionalities required for it. And there are a few terraform providers which offer APIs for accessing Terraform in on-premises infrastructure.

 

Q14 : What are all version controls supported by Terraform?

Below are the version controls supported by Terraform:

  • com
  • com (OAuth)
  • GitHub Enterprise
  • com
  • GitLab EE and CE
  • Bitbucket Cloud
  • Bitbucket Server
  • Azure DevOps Server
  • Azure DevOps Services

Q15 : Can I add policies to the open-source or pro version of Terraform enterprise?

No, you cannot add policies to both open-source or pro versions of Terraform enterprise. The best version of Terraform Enterprise could only contact the lookout policies.

Q16 : Is there a way to bulk import the state of the current cloud subscription into Terraform state?

With terraform import command, individual resources can be imported to terraform state, but there is not bulk import feature as of now.

Q17 : How do we define multiple Provider configurations?

To define multiple provider configurations, we need to add multiple provider blocks within the same provider name. We will have to use the alias meta-argument for the additional non-default configurations. For example:


# The default provider configuration
provider "aws" {
  region = "us-west-1"
}

# Additional provider configuration
provider "aws" {
  alias = "east"
  region = "us-east-2"
}

Q18 : If different teams are working on the same configuration. How do you make files have consistent formatting?

We can use terraform fmt to keep the configuration format consistent across teams. This command modifies the configurations in terraform for better readability and consistency. fmt command is used to keep the style consistent across different terraform codebases.

 

Q19 : If different teams are working on the same configuration. How do you make files to have syntactically valid and internally consistent?

To make sure different teams working on the same configuration are keeping the configuration syntactically valid and internally consistent, we can use the validate command. terraform validate validates the configuration files in a directory and reports errors found in attribute name, modules, and value types. This command returns a success message if all the syntax is valid and consistent.

 

Q20 : How do you inspect the current state of the infrastructure applied in terraform?

You inspect the current state of the infrastructure applied in terraform using terraform show command. It will give a human-readable output which will be a JSON representation of the state file if you run the command with -json parameter.

 

Q21 : What do we need to use a remote-exec?

You will need ssh or winrm connection type to use a remote-exec through a connection block. The provisioner can be inline in which the command string are executed in the order they are provided or it can be local script path which will be copied on remote resource and then executed. For example:


provider "aws" {
   profile = "default"
   region = "us-east-1"
 }
resource "aws_instance" "demo" {
   ami = "ami-04590e7389a6e577c"
   instance_type = "t2.micro"
connection { 
type = "ssh"  
host = aws_instance.example_public.public_ip   
user = var.ssh_user   
port = var.ssh_port
agent = true
 
}
provisioner "remote-exec" {
     inline = [
       "sudo amazon-linux-extras enable nginx1.12",
       "sudo yum -y install nginx",
       "sudo systemctl start nginx"
     ]
   }
 }

Q22 : Does the taint command modify the infrastructure?

Taint command in terraform does not modify the infrastructure, rather it updates the terraform state file and marks the object as tainted. This tainted object gets destroyed and recreated in the next terraform plan, and the terraform apply will make the changes.

 

Q23 : How do you apply constraints for the provider versions?

To apply constraints for the provider versions, you can use version constraints in terraform. The syntax used here is very similar to the dependency management systems like NPM. The example below used operations and applies constraints for aws terraform provider greater than or equal to 2.5.0.

terraform {

required_providers {

aws = “>= 2.5.0”

}

}

 

Q24 : What is the command import?

The import command in terraform imports the existing resources into terraform.

Syntax: terraform import [options] ADDRESS ID

Depending on the ID you provide in the command, the import will find the existing resource and add it to the terraform state at the given address. This resource address must be valid. The ID depends on the resource type getting imported, for example for AWS Route53 zones, it will be zone ID, and for AWS instances, it will be instance ID. For example, the command below will import an AWS instance into the resource name demo:

terraform import aws_instance.demo i-efgh5678

Q25 : If terraform crashes, where should you see the logs?

If terraform crashes, all the debug logs from the session get stored in the crash.log file with a panic message. So, crash.log is the file you need to check for the details. For example, it will look something like this:

 

panic: runtime error: invalid memory address or nil pointer dereference

goroutine 567 [running]:

panic(0xabc100, 0xd93000a0a0)

 

/opt/go/src/runtime/panic.go:464 +0x3e6

 

Q26 : How do you remove items from the Terraform state?

We can use the state rm command to remove items from the terraform state. This command is used to remove the binding to an existing remote object without destroying it. Below is the syntax of the command:

Syntax: terraform state rm [options] ADDRESS

Depending on the address provided in the command, terraform will look for the resource record and remove it so that terraform does not track that object anymore. For example, the command below will remove all the instances of packet_device of resource demo:

terraform state rm ‘packet_device.demo’

 

Q27 : How do you move the state from one source to another?

terraform state mv command is used to move the current state of a module, resource, or instance from one source to another. Below is the syntax of the command:

Syntax: terraform state mv [options] SOURCE DESTINATION

The tracking of the object moved will be done from the destination. Here is an example, where a resource of ‘demo’ is moving to ‘test’:

terraform state mv packet_device.demo packet_device.test

  1. Where do you find and explore terraform Modules?
  2. To find and explore terraform modules, you can use terraform registry. Terraform registry is a collection of modules that are small, reusable, and lets you manage a bunch of resources. You can quickly deploy common infrastructure configurations through modules available on terraform registry.

 

Q28 : What is State Locking?

State locking in terraform locks the terraform state so that no write operations can be performed. It is used to prevent someone from achieving a lock on the terraform state and corrupting it. You can so state locking only for few supported backends.

 

Q29 : What is the null resource in Terraform?

The null_resource in terraform is used to implement standard resource lifecycle and no further actions. You can implement null resource in trigger arguments, for example:

 

resource “null_resource” “demo” {

triggers = {

cluster_instance_ids = join(“,”, aws_instance.cluster.*.id)

}

Q30. What are the reasons for choosing Terraform for DevOps?

Terraform is a tool for Infrastructure as Code (IaC). It is used for defining and provisioning the complete infrastructure. Here are some of the most important reasons why I would choose Terraform:

  • It can do complete orchestration and not just configuration management (like Ansible and Puppet).
  • Has an amazing support of almost all the popular cloud providers like AWS, Azure, GCP, DigitalOcean etc.
  • Easily manages the configuration of an immutable (dynamic) infrastructure.
  • Provide immutable infrastructure where configuration changes smoothly.
  • Works on HCL (HashiCorp configuration language), which is very easy to learn and understand.
  • Easily portable from one provider to another.
  • Works on masterless, Client only architecture. You just need to install Terraform client and it will take care of the rest using the APIs.

 

Q31. How does Terraform work?

There are four stages in a Terraform lifecycle – terraform init, terraform plan, terraform apply, and terraform destroy. So, the flow is first you initialize, then you plan, after that you apply and finally destroy.

 

  • Terraform init is used to initialize the working directory which has all the terraform configuration files.
  • Terraform plan is used to create an execution in order to reach a desired state of the infrastructure. This is created to check whether the expectation of reaching the desired state will be met or not, without changing any real state of resources.
  • Terraform apply basically executes the execution plan created by terraform plan to reach the desired state of the infrastructure.
  • Terraform destroy is used to remove all the resources on the infrastructure and destroy it.

 

Q32. Explain the working of Terraform Core.

Terraform core is the entry point of the whole terraform architecture. It is responsible for reading all the configurations and create a dependency graph out of it. Once the terraform plan command is executed, the terraform core loads all the needed configuration files from the disk and also the last known state of the resources. It then begins a refresh operation and tells the terraform provider plugin to read all the resources. After the read operation, the terraform core checks if there is any difference in the last known state and current state. It then presents the changes in the output of terraform plan on the terminal.

 

Terraform configurations and terraform state are the two inputs to the terraform core. Terraform configuration has the details of what needs to be created and provisioned on the infrastructure and terraform state is to keep the up-to-date status of the infrastructure.

 

Q33. What are the primary responsibilities of the provider and provisioner plugins?

 

Providers and Provisioners are used in Terraform using plugins.

 

The responsibilities of provider plugins are:

  • Creating, reading, updating and deleting resources
  • Adding new resource type to an existing provider
  • Writing a new provider in case the existing provider is not enough to manage the resources
  • Understanding the API interactions and exposing the resources
  • Help in local utilities for tasks like generating random numbers for unique resource names
  • Authentication of the provider of infrastructure

 

The responsibilities of provisioner plugins are:

  • To pass data to VMs and other compute resources
  • To launch configuration management products
  • To execute scripts on a local or a remote machine to create or destroy resources
  • To bootstrap a resource, to perform clean-up before destroying the resource

 

Q34. How does Terraform help in discovering plugins and what are the different behaviours of it?

 

After running the terraform init command, terraform reads all the configuration files from the working directory to check which plugins are required depending on the configuration for the infrastructure. Then it searches for those plugins, checks where they are installed, sometimes it downloads additional plugins if required and decides which plugin version must be used. Then terraform writes a lock file to make sure the same plugin version is used when the next terraform init command runs.

 

There are three different ways in which terraform plugins behave in order to discover plugins:

  1. They use built-in provisioners. These are used where plugins are always available and included in terraform binary
  2. They use providers distributed by Hashicorp. The plugins here are automatically downloaded if they are not installed already
  3. They use 3rd party providers and provisioners. Here the necessary plugins are manually installed

 

Q35. What are the ways to lock Terraform module versions?

Here you need to use the proven way to lock the terraform module version. You can use the terraform module registry as a source and provide the attribute as ‘version’ in the module in a terraform configuration file. If you are using the GitHub repository as a source, then you need to specify the branch, version and query string with ‘? ref’.

 

Q36. What is Terragrunt in Terraform?

Terragrunt is a tool by Gruntwork which work on the principle of DRY (Don’t Repeat Yourself). It is a thin wrapper which has some extra tools using which you can keep the configurations DRY. You can use it for terraform modules and terraform states also.

 

By using Terragrunt, you write your codes on Terraform only once, even if you have multiple environments. You do not write configuration codes for every environment. It helps you get rid of duplicate code in the backend. Using Terragrunt, you can manage the terraform state once by defining it in the root directory and all the child modules can inherit it. In case you want to apply something on multiple modules, using terragrunt, you can do that using a single command which will make the changes in all the modules.

 

Terragrunt helps in encouraging versioned modules and reusability for multiple environments. It also comes with additional features such as lifecycle hooks which adds flexibility in using terraform. This tool also supports continuous deployment practices natively. Here the code is packaged, versioned and reused by multiple environments in the CICD pipelines.

 

Q37. What is the difference between Terraform and CloudFormation?

Terraform is a product by Hashicorp and CloudFormation is a product of Amazon Web services. Both are similar in many ways as they are used to do similar tasks but there are multiple differences between them.

 

HashiCorp Configuration Language (HCL) is used by Terraform to keep it human-readable and it is machine friendly. On the other hand, CloudFormation uses JSON or YAML for defining the configuration.

 

Terraform provides amazing native support for modules. Terraform registry has plenty of open-source modules readily available to be used. Comparative to Terraform, the support of the module in CloudFormation is not that great. It has some features to modularize your template, but most of the time, they are not used, it is up to you if you want to use them.

 

CloudFormation is an AWS service so it works smoothly with AWS infrastructure but takes time to support new AWS service capabilities. Terraform supports AWS resources and is faster than CloudFormation most of the time when new working with new AWS features. Terraform also have better support for other cloud providers such as Microsoft Azure and Google Cloud Platform and many other 3rd parties.

 

One more very important difference between the two is that while applying and update, terraform will show you all the changes that will happen, it will drill down and share all the module information. Whereas in CloudFormation, while updating, it only tells about the nested stacks but does not drill down into the details.

 

Q38. How would you recover from a failed apply in Terraform?

The usual way to represent “rolling back” in Terraform is to put your configuration in version control and commit before each change, and then you can use your version control system’s features to revert to an older configuration if needed. You always need to recommit the previous version code for it to be the new version in the version control system.

 

Not all changes can be rolled back purely by reverting a version control system change though. For example, if you added a new provider block and resources for that provider all in one commit and then applied the result, in order to rollback, you would need to change the configuration to still include the provider block but not include any of the resource blocks, so you would need to adjust the configuration during the revert. Terraform will then use the remaining provider block to configure the provider to run the destroy actions, after which you can finally remove the provider block too.

 

If the state file gets corrupted from the latest terraform run, then you can use terraform enterprise and its features of state rollback to go to the previous latest state which was working fine and was in a good state. This is possible in the enterprise version because every state change is versioned there.

 

Q39. How to ignore duplicate resource error during terraform apply?

It seems to be the case that when a resource conflict occurs (the IAM roles in my case), Terraform will ignore certain resource types previously saved in its state and attempt to recreate those resources from scratch.

 

Possible causes of this could be:

  • You or someone else has executed your Terraform code and you don’t have a shared/updated state
  • Someone has created them manually
  • A Terraform destroy failed in a way that deleted the resources for the API but failed to save the update state

 

Solutions depend on what you need. You can:

  • Delete those resources from your Terraform code to stop managing them with it
  • Delete those resources from the API (cloud provider) and recreate them with Terraform
  • Perform a terraform import of those resources and remove the terraform code that is trying to recreate them (NOT RECOMMENDED)
  • Use terraform apply –target=xxx to apply only resources you need to apply (NOT RECOMMENDED)

 

Q40. Share a few Terraform CLI Commands which you use for your day-to-day routine?

Below are a few Terraform CLI commands which are often used on a daily basis:

  • Init:This command is used to initialize the working directory which has all the terraform configuration files.
  • Get: This command is used to download an update of the module mentioned in the root module.
  • Plan: This command is used to create an execution in order to reach a desired state of the infrastructure.
  • Apply: This command is used to execute the execution plan created by terraform plan to reach the desired state of the infrastructure.
  • Destroy: It isused to remove all the resources on the infrastructure and destroy it. 
  • Graph: Using this CLI command, you can visualize an execution plan or generate a visual representation of a configuration.
  • Validate: This command is used to validate the configuration file if they are syntactically consistent.
  • Workspace: It is used to manage the workspaces.
  • Fmt: It is used to rewrite the terraform configuration files in a canonical format and style.

 

Q41. What is an Execution Plan in Terraform?

One of the important stages in a terraform lifecycle is the terraform plan state. This is the stage where the execution plan is created. Terraform plan creates an execution plan which has the details about what all things will get executed once the apply command runs. The execution plan helps you in visualizing what changes are about to happen, and there are no surprises later.

 

Q42. What is a Resource Graph in Terraform?

A resource graph is a graph build by terraform for all the resources. It also creates and modifies any non-dependent resources parallelly. Terraform creates a dependency graph from the configurations files and walks the graph to generate plans, refresh state etc. The resource graph is used by terraform in building infrastructure as efficiently as possible, and it provides insights to the operators about the dependencies in their infrastructure.

 

Q43. What is the Terraform cloud?

Terraform Cloud is an application that manages Terraform runs in a consistent and reliable environment. It includes easy access to the shared state and secret data, a private registry for sharing Terraform modules, access controls for approving changes to infrastructure, detailed policy controls for governing the Terraform configuration contents, etc.

Terraform Cloud is a hosted service and available at https://app.terraform.io. It offers free accounts for small teams and has paid plans with additional feature sets for medium-sized businesses.

For large enterprises, there is a separate terraform cloud product – Terraform Enterprise. You get a private instance of the Terraform Cloud application for an enterprise, with no resource limits and with additional enterprise-grade architectural features like SAML single sign-on and audit logging.

Q44. Are callbacks possible with Terraform on Azure?

Yes, callbacks are possible with Terraform on Azure, it is done using Azure Events Hub. Terraform has a provider called AzureRM which provides the callback functionality.

 

Q45. What is a Remote Backend in Terraform?

The remote backend in terraform is used to store the state of terraform and can also run operations in terraform cloud. Remote backend multiple terraform commands such as init, plan, apply, destroy (terraform version >= v0.11.12), get, output, providers, state (sub-commands: list, mv, pull, push, rm, show) , taint, untaint, validate and many more. It can work with a single remote terraform cloud workspace or even multiple workspaces. For running remote operations like terraform plan or terraform apply, you can use terraform cloud’s run environment.

 

Q46. What is State File Locking?

State file locking is a mechanism in terraform where operation on a specific state file is blocked by multiple callers to avoid any conflict between the team members. Once the lock from one caller is released, then only any other caller can operate on that state file after taking a lock on it. This helps in preventing any corruption of the state file. It is a backend operation, so the acquiring of lock on a state file in backend. If it takes more time than expected to acquire a lock on the state file, you will get a status message as an output.

 

Q47. What is a Tainted Resource?

Tainted resources are those resources in terraform which are forced to be destroyed and they are asked to be recreated on the next apply command. When you mar a resource as tainted, nothing changes on infrastructure but state file is updated with this information. After marking a resource as tainted, terraform plan out will show that resource will get destroyed and recreated, and when the next apply happens the changes will get implemented.

 

Q48. How do you test a terraform module?

There are multiple ways to do that, the most popular way is using Terratest. Terratest has been developed by Gruntworks. It has been built with the purpose of testing the terraform module (code) by using a unit testing framework. This framework has been built in the Go programming language. To run Terratest, you just need to provide the terraform file (module file) and the Go test. And run the command go test.

 

Q49. Tell about a few Terraform best practices.

  • Follow a proper directory structure of the terraform workspace. The projects on production can get very complex if they are not well-structured.
  • Use naming conventions to make the cluster structure understandable.
  • Always use the latest stable terraform version, they have new features and a lot of security patches.
  • You official terraform modules, don’t waste time in creating similar modules that are already available in the terraform registry.
  • Always backup the terraform state files.
  • Use official terraform docker containers in your CICD pipeline jobs.
  • Lock the state files to avoid any conflict between teams or team members.

 

Final Thoughts

Terraform is a vast topic and there is plenty to learn. Do not just mug up these answers, understand the technicalities of these answers also. Terraform documentation is the best place to get in technical depth. But these top 20 terraform interview questions will give you a kickstart to your future terraform interviews. So, prepare well and all the best!

 

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

Our website uses cookies that help it to function, allow us to analyze how you interact with it, and help us to improve its performance. By using our website you agree by our Terms and Conditions and Privacy Policy.