main_bg

Terraform Interview Questions

Prepare for your Terraform interview with a comprehensive list of Terraform interview questions and well-explained answers. Boost your confidence and be ready to tackle questions related to infrastructure as code and automation.

1. What is Terraform?

Terraform is an open-source Infrastructure as Code (IaC) tool developed by HashiCorp. It allows users to define and provision infrastructure using a declarative configuration language.

2. Explain the difference between Terraform and Ansible.

Terraform focuses on provisioning infrastructure, while Ansible is a configuration management tool that automates software provisioning, configuration, and application deployment.

3. What are the key features of Terraform?

Following are the key features of Terraform:

  • Infrastructure as Code: Terraform's high-level configuration language is used to describe your infrastructure in declarative configuration files that are human-readable. You may now generate a blueprint that you can edit, share, and reuse.
  • Execution Strategies: Before making any infrastructure modifications, Terraform develops an execution plan that describes what it will do and asks for your agreement. Before Terraform produces, upgrades, or destroys infrastructure, you can evaluate the changes.
  • Graph of Resources: Terraform develops or alters non-dependent resources while simultaneously building a resource graph. This allows Terraform to construct resources as quickly as possible while also providing you with more information about your infrastructure.
  • Automation of Change: Terraform can automate the application of complex changesets to your infrastructure with little to no human intervention. Terraform identifies what happened when you update configuration files and provides incremental execution plans that take dependencies into account.

4. Is it feasible to use Terraform on Azure with callbacks? Sending a callback to a logging system, a trigger, or other events, for example?

Yes. Azure Event Hubs can be used to accomplish this. This capability is now accessible in the Terraform AzureRM provider. Terraform's Azure supplier provides users with simple functionality. Microsoft Azure Cloud Shell includes a Terraform occurrence that has already been setup.

5. What do you mean by terraform init in the context of Terraform?

The terraform init command creates a working directory in which Terraform configuration files can be found. After creating a new Terraform configuration or cloning an old one from version control, run this command first. It is safe to use this command more than once. Despite the fact that successive runs may result in errors, this command will never overwrite your current settings or state.

Syntax:

terraform init [options]

The following options can be used in conjunction with the init command :

  • -input=true: This option is set to true if the user input is mandatory. If no user input is provided, an error will be thrown.
  • -lock=false: This option is used to disable the locking of state files during state-related actions.
  • -lock-timeout=<duration>: This option is used to override the time it takes Terraform to get a state lock. If the lock is already held by another process, the default is 0s (zero seconds), which results in an immediate failure.
  • -no-color: This option disables the color codes in the command output.
  • -upgrade: This option can be chosen to upgrade modules and plugins throughout the installation process.

6. Why is Terraform preferred as one of the DevOps tools?

 Following are the reasons that Terraform is preferred as one of the DevOps tools :

  • Terraform allows you to specify infrastructure in config/code, making it simple to rebuild, alter, and track infrastructure changes. Terraform is a high-level infrastructure description.
  • While there are a few alternatives, they are all centred on a single cloud provider. Terraform is the only powerful solution that is totally platform-neutral and supports different services.
  • Terraform allows you to implement a variety of coding concepts, such as putting your code under version control, writing automated tests, and so on.
  • Terraform is the best tool for infrastructure management since many other solutions suffer from an impedance mismatch when attempting to use an API meant for configuring management to govern an infrastructure environment. Instead, Terraform is a perfect match for what you want to do because the API is built around how you think about infrastructure.
  • Terraform has a thriving community and is open source, so it's attracting a sizable following. Many people already use it, making it easy to discover individuals who know how to use it, as well as plugins, extensions, and expert assistance. Terraform is also evolving at a much faster rate as a result of this. They have a lot of releases.
  • Terraform's speed and efficiency are unrivalled. Terraform's plan command, for example, allows you to see what changes you're about to make before you do them. Terraform and its code reuse feature makes most modifications faster than similar tools like CloudFormation.

7. Explain the destroy command in the context of Terraform.

The terraform destroy command is a simple way to eliminate all remote objects maintained by a Terraform setup. While you should avoid destroying long-lived objects in a production environment, Terraform is occasionally used to manage temporary infrastructure for development, in which case you can use terraform destroy to quickly clean up all of those temporary objects after you're done.

Syntax: terraform destroy [options]

You may also execute the following command to build a speculative destroy plan to see what the effect of destroying might be: 

terraform -destroy plan

This will launch Terraform Plan in destroy mode, displaying the proposed destroy changes but not allowing you to execute them.

8. What do you understand about Terraform modules?

 A Terraform module is a single directory containing Terraform configuration files. Even a simple arrangement with a single directory having one or more files can be referred to as a module. The files have the extension .tf.  This directory is referred to as the root module when Terraform commands are run directly from it. Terraform commands will only use the configuration files in one location: the current working directory. Your configuration, on the other hand, can employ module blocks to call modules from other directories. When Terraform comes across a module block, it loads and processes the configuration files for that module. A module that is called by another configuration is frequently referred to as that configuration's "child module."

9. What are the benefits of using modules in Terraform?

 Following are the benefits of using modules in Terraform :

  • Organization of configuration: By grouping relevant portions of your configuration together, modules make it easier to access, understand, and change your configuration. Hundreds or thousands of lines of configuration can be required to establish even moderately complicated infrastructure. You can organise your configuration into logical components by utilising modules.
  • Encapsulation of configuration: Another advantage of modules is that they allow you to separate configuration into logical components. Encapsulation can help you avoid unforeseen consequences, such as a change to one element of your configuration causing changes to other infrastructure, and it can also help you avoid basic mistakes like naming two resources with the same name.
  • Maintains consistency and ensures best practices: Modules can also help you maintain uniformity in your configurations. Consistency not only makes complex configurations easier to grasp, but it also ensures that best practices are followed in all of your settings. Cloud providers, for example, offer a variety of options for establishing object storage services like Amazon S3 or Google Cloud Storage buckets. Many high-profile security problems have occurred as a result of improperly secured object storage, and given the number of sophisticated configuration options involved, it's possible to misconfigure these services by accident.
  • Modules can aid in the reduction of errors: For example, you might design a module to define how all of your organization's public website buckets would be set, as well as a separate module for private logging buckets. In addition, if a configuration for a particular resource type needs to be altered, using modules allows you to do it in one place and have it applied to all scenarios where that module is used.
  • Aids in reusability: Setting up the configurations from scratch and writing all of your settings can be time-consuming and error-prone. By reusing configuration generated by yourself, other members of your team, or other Terraform practitioners who have published modules for you to utilise, you can save time and avoid costly errors. You can also share modules you've produced with your colleagues or the broader public, allowing them to profit from your efforts.

10. What are some guidelines that should be followed while using Terraform modules?

Following are some of the guidelines that should be followed while using Terraform modules :

  • To publish to the Terraform Cloud or Terraform Enterprise module registries, you must use this convention terraform-<PROVIDER>-<NAME>.
  • Start thinking about modules as you write your setup. The benefits of using modules outweigh the time it takes to utilise them properly, even for somewhat complicated Terraform settings maintained by a single person.
  • To organise and encapsulate your code, use local modules. Even if you aren't using or publishing remote modules, structuring your configuration in terms of modules from the start will dramatically minimise the time and effort required to maintain and update your setup as your infrastructure becomes more complicated.
  • To identify useful modules, go to the Terraform Registry, which is open to the public. By relying on the efforts of others to create common infrastructure scenarios, you may implement your configuration more quickly and confidently.
  • Modules can be published and shared with your team. The majority of infrastructure is handled by a group of individuals, and modules are a vital tool for teams to collaborate on infrastructure creation and maintenance.

11. Explain the command terraform validate in the context of Terraform.

The terraform validate command verifies the configuration files in a directory, focusing solely on the configuration and excluding any outside services such as remote state, provider APIs, and so on. Validate performs checks to see if a configuration is syntactically correct and internally consistent, regardless of any variables or current state. As a result, it's best used for general verification of reusable modules, such as ensuring that attribute names and value types are correct. This command can be executed automatically, for example as a post-save check in a text editor or as a test step for a reusable module in a continuous integration system.

Syntax: terraform validate [options]

The following options are available with this command:

  • -json - Create output in the machine-readable JSON format, appropriate for integration with text editors and other automated systems. Color is always turned off.
  • -no-color - If supplied, the output will be colourless.

12. Explain the command terraform apply in the context of Terraform.

The terraform apply command is used to carry out the tasks in a Terraform plan. The simplest method to use terraform apply is to run it without any arguments, in which case it will construct a new execution plan (as if you had run terraform plan) and then request you to accept it before doing the activities you specified. Another approach to use terraform apply is to supply it the filename of a saved plan file generated with terraform plan -out=..., in which case Terraform will apply the modifications to the plan without prompting for confirmation. This two-step process is most useful when using Terraform in an automated environment.

Syntax:

terraform apply [options] [plan file]

13. Explain the command terraform version in the context of Terraform.

 The terraform version command shows the current Terraform version as well as any installed plugins.

Syntax:

terraform version [options]

Unless disabled, the version will display the Terraform version, the platform it's installed on, installed providers, and the results of upgrade and security checks with no extra arguments.

There is one optional flag for this command:

If you specify -json, the version information is formatted as a JSON object, with no upgrade or security information.

14. What do you understand about providers in the context of Terraform?

To interface with cloud providers, SaaS providers, and other APIs, Terraform uses plugins called "providers." Terraform configurations must specify the providers they need in order for Terraform to install and use them. Some providers also require setup (such as endpoint URLs or cloud regions) before they may be used. Terraform may manage a set of resource types and/or data sources that each provider contributes. A provider implements each resource type; Terraform would be unable to manage any infrastructure without them. The majority of service providers set up a specific infrastructure platform (either cloud or self-hosted). Local utilities, such as generating random numbers for unique resource names, can be offered by providers.

15. Explain the command terraform taint in the context of Terraform.

Terraform receives notification from the terraform taint command that a specific item has been degraded or damaged. This is represented by Terraform designating the item as "tainted" in the Terraform state, in which case Terraform will suggest replacing it in the next plan you write. If you want to compel the replacement of a specific object despite the fact that no configuration modifications are required, using the terraform apply -replace option is preferred.

Utilizing the "replace" option while creating a plan is preferable to using terraform taint because it allows you to see the entire impact of the alteration before taking any externally visible action. When you utilise terraform taint to achieve a similar impact, you run the danger of someone else on your team devising a new strategy to counter your tainted object before you've had a chance to consider the implications.

Syntax:

terraform taint [options] address

The address option specifies the location of the infected resource. The following options are available with this command:

  • -allow-missing - Even if the resource is absent, the command will succeed (exit code 0) if it is supplied. Other scenarios, such as a problem reading or writing the state, may cause the command to return an error.
  • -lock=false - Turns off Terraform's default behaviour of attempting to lock the state for the duration of the operation.
  • -lock-timeout=DURATION - Instructs Terraform to reattempt procuring a lock for a period of time before issuing an error, unless locking is disabled with -lock=false. A number followed by a time unit letter, such as "3s" for three seconds, is the duration syntax.

16. Explain the command terraform fmt in the context of Terraform.

Terraform configuration files are rewritten using the terraform fmt command in a consistent structure and style. This command uses a subset of the Terraform language style conventions, as well as some small readability tweaks. Other Terraform commands that produce Terraform configuration will produce files that follow the terraform fmt style, therefore following this style in your own files will assure consistency. Because formatting selections are always subjective, you may disagree with terraform fmt's choices. This command is purposely opinionated and lacks customization options because its primary goal is to promote stylistic consistency throughout Terraform codebases, even though the chosen style will never be everyone's favourite.

Syntax:

terraform fmt [options] DIR

By default, fmt looks for configuration files in the current directory. If the dir option is provided, it will instead scan the specified directory.

The following are the flags that are available:

  • -list=false - This option doesn't show files with discrepancies in formatting.
  • -write=false - This option prevents the input files from being overwritten. (When the input is STDIN or -check, this is implied.)
  • -diff - Shows the differences in formatting modifications.
  • -check - Verifies that the input is properly formatted. If all input is properly formatted, the exit status will be 0, else it will be non-zero.
  • -recursive - Process files from subdirectories as well.

17. Explain State File Locking in the context of Terraform.

Terraform's state file locking method prevents conflicts between numerous users doing the same task by blocking activities on a given state file. When one user unlocks the lock, only the other user has access to that state. Terraform will lock your state for any operations that potentially write state if your backend supports it. This prevents outsiders from gaining access to the lock and corrupting your state. All operations that have the potential to write state are automatically locked. There will be no indication that this is happening. Terraform will not continue if state locking fails. The -lock flag can be used to deactivate state locking for most tasks, although it is not advised. Terraform will send a status message if gaining the lock takes longer than planned. If your backend enables state locking, even if Terraform doesn't send a message, it still happens.

18. What do you know about Terraform core? What are the primary responsibilities of Terraform core?

Terraform Core is a binary created in the Go programming language that is statically compiled. The compiled binary is the terraform command line tool (CLI), which is the starting point for anyone who wants to use Terraform. The source code can be found at github.com/hashicorp/terraform.

The primary responsibilities of Terraform core includes:

  • Reading and interpolating configuration files and modules using infrastructure as code
  • Management of the state of resources
  • Resource Graph Construction
  • Execution of the plan
  • Communication with plugins through RPC

19. When something goes wrong, how will you control and handle rollbacks in Terraform?

In our Version Control System, we need to recommit the previous code version to make it the new and current one. This would start the terraform run command, which would execute the old code. Because Terraform is more declarative, we will make sure that everything in the code reverts to its previous state. If the state file becomes corrupted, we would use Terraform Enterprise's State Rollback feature to restore the previous state.

20. What procedures should be taken to make a high-level object from one module available to the other module?

The steps to make an object from one module available to the other module at a high level are as follows:

  • The first step is to define an output variable in a resource configuration. The scope of local and to a module will not be declared until you define resource configuration details.
  • Now you must specify the output variable of module A so that it can be utilised in the setup of other modules. You should establish a fresh new and up-to-date key name, with a value that is equal to the output variable of module A.
  • You must now create a file named variable.tf for module B. Create an input variable with the exact same name as the key you defined in module B inside this file. This variable permits the resource's dynamic setting in a module. Replicate the process to make this variable available to other modules as well. This is because the scope of the variable established here is limited to module B.

21. What do you understand about remote backend in the context of Terraform?

Terraform's remote backend stores terraform state and can also conduct operations in the terraform cloud. terraform commands such as init, plan, apply, destroy , get, output, providers, state (sub-commands: list, mv, pull, push, rm, show), taint, untaint, validate, and many others can be run from a remote backend. It can be used with a single or several remote terraform cloud workspaces. You can utilise terraform cloud's run environment to conduct remote operations like terraform plan or terraform apply.

22. Code Snippet: Creating an AWS EC2 Instance with Terraform

            
provider "aws" {
  region = "us-west-2"
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}
            
        

23. Online Resources:

Published On: 2024-01-17