Day 71 - Terraform Interview Questions

Day 71 - Terraform Interview Questions

Table of contents

Below are some basic Terraform interview questions along with the answers.✍

1. What is Infrastructure as Code?

Infrastructure as code, also referred to as IaC, is an IT practice that codifies and manages underlying IT infrastructure as software. The purpose of infrastructure as code is to enable developers or operations teams to automatically manage, monitor and provision resources, rather than manually configure discrete hardware devices, operating systems (OSes), applications and services.

2. What is Terraform and how it is different from other IaC tools?

Terraform is a popular Infrastructure as Code (IaC) tool that allows you to automate the provisioning and management of infrastructure resources.
Unlike other IaC tools, Terraform is cloud-agnostic, supporting multiple providers, and uses configuration files written in the HashiCorp Configuration Language (HCL) to define the desired state of your infrastructure, and it uses various commands to apply those configurations and manage your infrastructure resources.

3. Why do we use Terraform?

Following are the some of the reasons to use terraform: -

  1. Provisioning Cloud Resources: Different types of cloud resources can be provisioned by using terraform like AWS,GCP, and others. The resources can be managed are compute, storage, networking, and application services.

  2. Multi-Cloud Management: You can manage the infrastructure of different cloud platform at a time which will helps you to maintain the multi-cloud or hybrid cloud environments.

  3. Infrastructure Versioning and Collaboration: You can store the scripts which have been written to provision the infrastructure in the version control system like git form where other teams can collaborate on infrastructure changes, track revisions, and roll back to previous states if needed.

  4. Automation and CI/CD: You can also integrate the terraform into you CI/CD pipelines where ever the build is triggered if there is any changes the infrastructure will upgrades automatically.

  5. Dependency Management and Resource Relationships: Terraform handles dependencies between resources and manages their relationships. It automatically determines the correct order in which resources should be provisioned or modified based on their dependencies.

  6. Community and Ecosystem: Terraform has a large and active community, contributing to its rich ecosystem. This includes a vast number of provider plugins for integrating with various services and technologies.

4. What are Terraform Providers?

A provider is a plugin in Terraform that is responsible for interacting with a specific cloud provider or service. They are used to manage and provision resources within the target infrastructure. Examples of providers include AWS, Azure, Google Cloud, and more. Each provider has its own set of resources and configuration options.

5. What are Terraform Resources?

A resource represents a specific infrastructure object that Terraform manages. Resources can be virtual machines, databases, networks, load balancers, or any other entity offered by the cloud provider. Each resource has a specific configuration block that defines its properties and settings.

6. What are Terraform Modules?

A module is a reusable unit of infrastructure configuration. It encapsulates a set of resources and configurations that can be used to create and manage infrastructure components. They promote modularity, code reuse, and maintainability by abstracting complex configurations into manageable units.

Modules can be used across different projects or shared within a team, making infrastructure configurations more maintainable and scalable.

7. How does Terraform work?

Terraform creates an implementation plan, defines what it will do to achieve the desired state, and then executes it to build the infrastructure described. Terraform is capable of determining what changed and generating incremental execution plans that are practical as the configuration changes.

8. Define Terraform init?

Terraform initializes the code with the command terraform init. This command is used to set up the working directory for Terraform configuration files. It is safe to run this command multiple times.

You can use the init command for:

  1. Installing Plugins

  2. Installation of a Child Module

  3. Initialization of the backend

9. What are Terraform Outputs?

Outputs are values that are derived from the Terraform configuration and can be used to provide information about the infrastructure to external systems or users. They are typically used to expose important details such as IP addresses, URLs, or resource identifiers for reference or consumption by other components.

10. What is Terraform State and State file?

The state in Terraform represents the current state of the infrastructure being managed. It is a record of the resources and their configurations defined in the Terraform configuration files.

The state file contains metadata about resources, their attributes, dependencies, and relationships.

Terraform uses this state file to understand the existing infrastructure, track changes, and plan and execute updates in a controlled manner.

11. What do you understand by terraform backend?

The backend in Terraform defines where Terraform state files are stored. This can be a local file system, remote storage services like Amazon S3 or Azure Blob Storage, or a version control system like Git.

The backend configuration determines how the state is accessed and shared among team members.

12. You have a Terraform configuration file that defines an infrastructure deployment. However, there are multiple instances of the same resource that need to be created. How would you modify the configuration file to achieve this?

To create multiple instances of the same resource in Terraform, you can use resource "count" or resource "for_each" depending on your specific requirements. By setting the count or for_each argument with an appropriate value, you can dynamically create and manage multiple instances of the resource within your configuration file.

13. You want to know from which paths Terraform is loading providers referenced in your Terraform configuration (*.tf files). You need to enable debug messages to find this out. Which of the following would achieve this?

To enable debug messages in Terraform and identify the paths from which providers are loaded, you can set the TF_LOG environment variable to DEBUG before running Terraform commands. This will display detailed debug logs, including information about provider loading, allowing you to determine the paths referenced in your Terraform configuration.

A. Set the environment variable TF_LOG=TRACE

B. Set verbose logging for each provider in your Terraform configuration

C. Set the environment variable TF_VAR_log=TRACE

D. Set the environment variable TF_LOG_PATH

14. Below command will destroy everything that is being created in the infrastructure. Tell us how would you save any particular resource while destroying the complete infrastructure.

terraform destroy

15. Which module is used to store .tfstate file in S3?

The "terraform_backend_s3" module is commonly used to store the .tfstate file in an S3 bucket. It provides a convenient way to configure the backend in Terraform, allowing for state storage, locking, and versioning in an S3 bucket.

16. How do you manage sensitive data in Terraform, such as API keys or passwords?

Sensitive data in Terraform, like API keys or passwords, should be stored securely outside the code. Common practices include using environment variables, secret management systems like HashiCorp Vault, or integration with cloud provider-specific services like AWS Secrets Manager or Azure Key Vault.

17. You are working on a Terraform project that needs to provision an S3 bucket, and a user with read and write access to the bucket. What resources would you use to accomplish this, and how would you configure them?

To provision an S3 bucket and a user with read and write access, you would use the "aws_s3_bucket" resource to create the bucket and the "aws_iam_user" resource to create the user. For access control, you would configure an appropriate "aws_iam_policy" with the necessary permissions and attach it to the user.

18. Who maintains Terraform providers?

Terraform providers are maintained by various organizations, including both cloud service providers (such as AWS, Azure, and Google Cloud) and independent contributors. Each provider has its own maintainers responsible for developing, updating, and supporting the provider's integration with Terraform.

19. How can we export data from one module to another?

To export data from one module to another in Terraform, you can use output variables. Define output variables in the module where the data is generated, and reference those outputs as input variables in the module where the data needs to be consumed.

20. What are the most useful Terraform commands?

Some of the most useful Terraform commands are: -

  • terraform init - initializes the current directory

  • terraform plan - a dry run to see what Terraform will do

  • terraform apply - applies the Terraform code and builds stuff

  • terraform refresh - refreshes the state file

  • terraform fmt - rewrite the configuration files in a different format

  • terraform output - views Terraform outputs

  • terraform validate - check whether the configuration is valid

  • terraform destroy - destroys what has been built by Terraform

  • terraform graph - creates a DOT-formatted graph

21. What is Terraform D?

Terraform D is a plugin used on most in-service systems and Windows. Terraform init by default searches next directories for plugins.

22. Why is Terraform used for DevOps?

Terraform is widely used in DevOps because it enables infrastructure as code (IaC), which means that infrastructure is defined and managed using code rather than manual configuration. This approach has several advantages for DevOps, including:

  • Automation: Terraform configurations can be automatically applied and set up, which can save time and reduce errors.

  • Reproducibility: Infrastructure can be easily replicated and recreated from code, which ensures consistency across different environments.

  • Version control: Terraform configurations can be stored in version control systems, which allows for easy tracking of changes and rollbacks.

23. Explain State File Locking?

State file locking is Terraform mechanism in which operations on a specific state file are blocked to avoid conflicts between multiple users performing the same process. When one user releases the lock, then only the other one can operate on that state. This helps in preventing state file corruption. This is a backend operation.

24. Describe the working of Terraform core?

The terraform core examines configuration monitoring and generates configuration-based analysis and evaluation. It keeps track of and compares versions (current and previous) before displaying the results via the terminal.

Terraform core mainly takes two inputs:

  • Terraform Configuration – It keeps track of the infrastructure detail.

  • Terraform state – It keeps track of the infrastructure status.

25. What exactly is Sentinel? Can you provide few examples that we can use for Sentinel policies?

Sentinel is a policy-as-code framework developed by HashiCorp. It integrates with various HashiCorp tools, including Terraform, to enforce governance and security policies.

Sentinel enables the creation of custom policies to control infrastructure provisioning and deployment. Examples of Sentinel policies include enforcing tagging conventions, validating resource configurations, restricting access to certain regions, enforcing encryption requirements, and ensuring compliance with regulatory standards.

Sentinel provides fine-grained control over infrastructure deployments by evaluating policy rules before changes are applied.

26. How can you specify dependencies between resources in Terraform?

In Terraform, you can specify dependencies between resources using the depends_on attribute within resource blocks. By including this attribute, you define an explicit ordering of resource creation and ensure that one resource is created before another. This helps manage dependencies when one resource relies on the existence or configuration of another resource.

27. What is the purpose of the Terraform plan command?

The Terraform plan command is used to create an execution plan that shows the changes Terraform will apply to the infrastructure. It compares the desired state defined in the configuration with the current state recorded in the state file.

The plan command provides a summary of the actions Terraform will take, such as creating, modifying, or deleting resources. It allows you to review and verify the changes before applying them to the infrastructure.

28. What are Terraform variables, and how can you use them in your infrastructure code?

Terraform variables allow you to parameterize your infrastructure code and make it more reusable and configurable. Variables can be defined in Terraform configuration files or separate variable files. You can use variables to customize resource configurations, such as specifying the number of instances or setting environment-specific values.

By leveraging variables, you can avoid hardcoding values and easily reuse and share your infrastructure code across different environments.

29. How does Terraform handle dependencies between modules?

Terraform handles dependencies between modules through the use of input and output variables.

Modules can define input variables that represent dependencies required from the calling module. The calling module provides these values as arguments when calling the module.

Additionally, modules can define output variables to expose specific values to the calling module. This mechanism allows Terraform to establish a clear relationship and pass data between modules, enabling them to work together while maintaining modularity.

30. Explain the concept of Terraform workspaces and when to use them.

Terraform workspaces provide a way to manage multiple instances of a Terraform configuration. Workspaces allow you to have separate sets of resources for different environments, such as development, staging, and production. They help in maintaining isolated environments and managing the state of each workspace.

31. How does Terraform handle variable interpolation in strings?

Terraform allows variable interpolation in strings using the "${var.NAME}" syntax. When the configuration is processed, Terraform replaces the variable references with their corresponding values.

32. What is the difference between Terraform modules and remote modules?

Terraform modules are self-contained packages of Terraform configurations that encapsulate a specific set of resources and their associated dependencies. They promote code reusability and modularity by allowing you to define and share infrastructure components across projects and teams.

Remote modules, on the other hand, refer to modules hosted remotely, typically in a version control repository or a module registry. Remote modules provide a way to retrieve and use pre-configured modules directly from a remote source. They enable code sharing, versioning, and collaboration by allowing users to consume modules without manually copying or managing the module code locally.

33. How can you perform targeted resource deployment in Terraform?

Targeted resource deployment in Terraform can be achieved by using the "-target" flag with the "apply" or "plan" command. By specifying the target resource's address or name, Terraform focuses only on that particular resource and its dependencies during the deployment or planning process.

Targeted deployment is useful while isolating changes to specific resources without affecting the rest of the infrastructure.

34. How can you integrate Terraform with CI/CD pipelines?

Terraform can be integrated with CI/CD pipelines to automate the deployment and management of infrastructure. Here's the typical process:

  • Commit the Terraform configurations to a version control system (e.g., Git).

  • Set up a CI/CD pipeline that monitors changes to the Terraform code repository.

  • In the pipeline, execute Terraform commands such as init, validate, and plan to ensure the configurations are valid and generate an execution plan.

  • Use Terraform's apply command to create or modify infrastructure based on the approved changes.

  • Optionally, leverage infrastructure testing and verification tools to validate the deployed infrastructure.

  • Finally, trigger additional pipeline stages for application deployment, testing, and release.

35. How can you perform rolling updates or zero-downtime deployments with Terraform?

Rolling updates or zero-downtime deployments involve updating infrastructure components without causing service disruptions. With Terraform, you can achieve this by utilizing features such as rolling deployment strategies and lifecycle hooks.

For example, you can define an AWS Auto Scaling Group with a rolling update policy to gradually replace instances while ensuring the overall availability of the application. Terraform allows you to specify update policies, health checks, and other parameters to control the pace and behavior of updates, minimizing downtime and ensuring smooth transitions.

36. Explain using the "Terraform.tfvars" file for variable assignment.

The "Terraform.tfvars" file is used to assign values to variables declared within Terraform configurations. Instead of defining variables directly within the configuration files, you can store them in the "Terraform.tfvars" file, which Terraform automatically loads.

This approach simplifies the management of variable values, especially when working with sensitive or environment-specific information. By separating variable assignments from the configuration files, you can provide different "Terraform.tfvars" files for different environments or teams, allowing for more flexible and reusable configurations.

37. What are the advantages of using Terraform's "count" feature over resource duplication?

Using Terraform's "count" feature provides advantages over resource duplication by allowing you to dynamically create multiple instances of a resource based on a given condition or variable. With "count," you can define a resource block with a count value that evaluates an expression, such as a variable or a conditional statement.

Terraform then creates the specified number of resource instances, reducing code duplication and enabling more efficient resource management and scalability.

38. Explain immutable infrastructure.

When infrastructures are termed disposable and no modification is allowed once they are provisioned, those infrastructures are called immutable infrastructures. Immutable infrastructures are supported by Terraform by promoting the recreation of resources. Commands such as ‘destroy’ and ‘apply’ can be used to destroy and recreate every change, ensuring a consistent and predictable infrastructure.

39. Explain null resource in the context of Terraform.

The null resource is a resource that lets you set up provisioners that aren't directly linked to any current resource. Because a null resource behaves like any other resource, you can configure provisioners, connection details, and other meta-parameters just like any other resource. This gives you more precise control over when provisioners execute in the dependency graph.

40. Differentiate between Terraform and Ansible.

Following table lists the differences between Ansible and Terraform: -

Terraform is a tool for provisioning.Ansible is a tool for managing configurations.
It uses a declarative Infrastructure as Code methodology.It takes a procedural method.
It’s ideal for orchestrating cloud services and building cloud infrastructure from the ground up.It is mostly used to configure servers with the appropriate software and to update resources that have previously been configured.
By default, Terraform does not allow bare metal provisioning.The provisioning of bare metal servers is supported by Ansible.
In terms of packing and templating, it does not provide better support.It includes complete packaging and templating support.
It is strongly influenced by lifecycle or state management.It doesn’t have any kind of lifecycle management. It does not store the state.

41. How can you prevent Duplicate Resource Error in Terraform?

Depending on the situation and the necessity, it can be accomplished in one of three ways: -

  1. By destroying the resource, the Terraform code will no longer manage it.

  2. By removing resources from APIs

  3. Importing action will also aid in resource elimination.

42. What is Terraform Directory?

Terraform Directory, which Terraform uses to manage cached provider plugins and modules, as well as to record which workspace is currently active and the last known backend configuration in case state needs to be migrated on the next run.

43. What are Provisioners in Terraform?

Provisioners are used to execute scripts on a local or remote machine as part of resource creation or destruction. Provisioners can be used to bootstrap a resource, cleanup before destroy, run configuration management, etc.

44. Define Resource Graph in Terraform.

A resource graph is a graphical representation of the available resources. It enables the modification and creation of independent resources at the same time. Terraform creates a plan for the graph’s configuration to generate plans and refresh the state. It efficiently and effectively creates a structure to help us understand the disadvantages.

45. What are the various levels of Sentinel enforcement?

Sentinel has three levels of enforcement: advisory, soft mandatory, and hard mandatory.

  • Advisory – Logged in but permitted to pass. When a user initiates a plan that violates the policy, an advisory is issued.

  • Soft Mandatory – Unless an override is specified, the policy must be followed. Overrides are only available to administrators.

  • Hard Mandatory – The policy must be implemented regardless. Unless and until this policy is removed, it cannot be overridden. Terraform’s default enforcement level is this.


You can go through the detailed blogs regarding Linux, GitHub, Docker, Jenkins, Kubernetes, AWS, IaC, Configuration Management, Ansible and Terraform from here: Smriti's Blog.🎇

In this blog, I have put my heart to collect interview questions on Terraform. If you have any questions or would like to share your experiences, feel free to leave a comment below👇. Don’t forget to read my blogs, hope you find it helpful🤞 and connect with me on LinkedIn and let’s have a conversation.✨

👆The information presented above is based on my interpretation. Suggestions are always welcome.😊

~Smriti Sharma✌