Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

How can you prevent Duplicate Resource Error in Terraform?

Answer»

Depending on the situation and the necessity, it can be ACCOMPLISHED in one of three ways.

  • By DESTROYING the resource, the Terraform CODE will no longer manage it.
  • By removing resources from APIs
  • Importing action will also AID in resource elimination.
Useful Resources

Kubernetes

AWS

Azure

Terraform Tutorial

Terraform DOWNLOAD

2.

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

Answer»

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.

3.

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

Answer»

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.
4.

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

Answer»

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.

5.

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

Answer»

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
6.

Explain State File Locking in the context of Terraform.

Answer»

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.

7.

What do you know about Terragrunt? What are its uses?

Answer»

Terragrunt is a lightweight WRAPPER that adds extra features for maintaining DRY configurations, dealing with many Terraform modules, and MANAGING remote state.

Following are the use CASES of Terragrunt:

  • To Keep Our Background Configuration DRY (Don’t Repeat Yourself): By setting your backend configuration once in a root location and inheriting that information in all child modules, Terragrunt helps you to keep it DRY ("Don't Repeat Yourself").
  • To Keep Our Provider Configuration DRY: It might be difficult to unify provider configurations across all of your modules, especially if you wish to alter authentication credentials. You may use Terragrunt to refactor common Terraform code and keep your Terraform modules DRY by using it. The provider configurations can be defined once at a root location, just like the backend configuration.
  • To Keep Our Terraform Command Line Interface arguments DRY: In the Terraform universe, CLI flags are another typical source of copy/paste. It can be difficult and error-prone to have to remember these -var-file options every time. By declaring your CLI parameters as code in your terragrunt.hcl settings, Terragrunt helps you to keep your CLI arguments DRY.
  • To Promote Terraform modules that are immutable and versioned across environments: Large modules should be considered hazardous, according to one of the most important lessons we've learnt from building hundreds of thousands of lines of infrastructure code. That is, defining all of your environments (dev, stage, prod, and so on) or even a huge amount of infrastructure (servers, databases, load balancers, DNS, and so on) in a single Terraform module is a Bad IDEA. Large modules are slow, insecure, difficult to update, code review, test, and are brittle. Terragrunt LETS you define your Terraform code once and then promote a versioned, immutable "artifact" of that code from one environment to the next.
8.

Explain the command terraform fmt in the context of Terraform.

Answer»

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.
9.

What do you mean by a Virtual Private Cloud (VPC)? Which command do you use in Terraform to use a VPC service?

Answer»

A Virtual Private Cloud (VPC) is a private virtual network within AWS where you can store all of your AWS services. It will have gateways, route tables, network access control lists (ACL), subnets, and security groups, and will be a logical data centre in AWS. When you create a service on a public cloud, it is effectively open to the rest of the WORLD and can be vulnerable to internet attacks. You lock your instances down and secure them from outside threats by putting them INSIDE a VPC. The VPC limits the types of TRAFFIC, IP addresses, and individuals who have access to your instances.

This STOPS unauthorised users from ACCESSING your resources and protects you from DDOS assaults. Because not all services require internet connection, they can be safely stored within a private network. You can then only allow particular machines to connect to the internet.

We use the command aws_vpc to use a VPC Service in Terraform.

10.

Differentiate between Terraform and Ansible.

Answer»

Ansible : Ansible is a remarkably straightforward IT automation technology. Configuration management, APPLICATION deployment, cloud provisioning, ad-hoc task execution, network automation, and multi-node orchestration are all handled by this software. Complex modifications, such as zero-downtime rolling updates with load balancers, are simple using Ansible.

Following table lists the differences between Ansible and Terraform:

TerraformAnsible 
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.
11.

Explain the command terraform taint in the context of Terraform.

Answer»

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.
12.

Differentiate between Terraform and Cloudformation.

Answer»

The following points highlight the differences between Terraform and Cloudformation:

  • User-friendliness: 
    • Terraform encompasses numerous Cloud Service Providers such as AWS, Azure, GOOGLE Cloud Platform, and many more, while CloudFormation is limited to AWS services. Terraform covers the majority of AWS resources.
  • Based on language: 
    • CloudFormation employs either JSON or YAML as a language. CloudFormation is now simple to read and manage. However, AWS developers are restricted from creating CloudFormation templates that are more than 51MB in size. Developers must establish a layered STACK for the templates if the template exceeds this size restriction.
    • Terraform, on the other hand, makes use of Hashicorp's own HCL language (Hashicorp Configuration Language). This language is also JSON compatible.
  • State-management: 
    • Because CloudFormation is an AWS managed service, it examines the infrastructure on a regular basis to see if the provisioned infrastructure is still in good shape. If anything changes, CloudFormation receives a thorough response.
    • Terraform, on the other hand, saves the state of the infrastructure on the provisioning machine, which can be either a virtual machine or a remote computer. The state is saved as a JSON file, which Terraform uses as a map to describe the resources it manages.
    • To summarise, Cloudformation's state is managed out-of-the-box by CloudFormation, which prevents conflicting updates. Terraform stores the state on a local disk, which makes it easier to synchronise the state. Terraform states can also be saved in storage services like S3, which is another recommended practice for state management. This must be defined on the backend, making management easier and safer.
  • Cost:
    • The nicest aspect about both of these tools is that they are both COMPLETELY free. Both of these technologies have sizable communities that provide plenty of HELP and examples. Cloudformation is completely free. The only expense that consumers pay is for the AWS service that CloudFormation provides. Terraform is a completely free and open-source application. Terraform, on the other hand, includes a premium enterprise version with more collaboration and governance features.
  • Integration of Multiple Clouds:
    • Terraform is the WAY to go if you want to supply services across several cloud platforms. While Terraform works with a variety of cloud providers, including AWS, GCP, Azure, and others, CloudFormation is exclusive to AWS. Cloudformation is not for you if your setup includes several cloud installations. If you're using AWS resources like EC2, S3, and so on, you should stick to Cloudformation.
13.

Explain the architecture of Terraform request flow.

Answer»

A request in Terraform undergoes the following steps as shown in the diagram:

Following are the different components in the above architecture:

Command Line Interface (CLI):

CLI (Common Language Interface) (command package)

Aside from some early bootstrapping in the root package (not shown in the diagram), when a user starts the terraform application, execution jumps RIGHT into one of the command package's "command" implementations. The commands.go file in the repository's root directory contains the mapping between user-facing command names and their respective command package types. 

The job of the command implementation for these commands is to read and parse any command line arguments, command-line options, and environment variables required for the given command and use them to generate a backend.operation object. The operation is then transferred to the backend that is currently selected.

Backends:

In Terraform, a backend has a variety of RESPONSIBILITIES

  • Carry out operations (e.g. plan, apply)
  • To save workspace-defined variables
  • To save state

The local backend retrieves the current state for the workspace specified in the operation using a state manager (either statemgr.Filesystem if the local backend is being used directly, or an implementation provided by whatever backend is being wrapped), then uses the config loader to load and do initial processing/validation of the configuration specified in the operation. It then constructs a terraform.context object using these, as well as the other parameters specified in the procedure. The main object actually executes Terraform operations.

Configuration Loader :

Model types in package configs represent the top-level configuration structure. configs.Config represents an entire configuration (the root module and all of its child modules). ALTHOUGH the configs package offers some low-level functionality for creating configuration objects, the major entry point is via configload.Loader, which is found in the sub-package configload. When a configuration is loaded by a backend, a loader takes care of all the complexities of installing child modules (during terraform init) and then locating those modules again. It takes the path to a root module and loads all of the child modules in a recursive manner to create a single configs. 

State Manager:

The state manager is in charge of storing and retrieving snapshots of a workspace's Terraform state. Each manager is an implementation of a subset of the statemgr package's interfaces, with most practical managers implementing the entire SET of statemgr.Full's operations . The smaller interfaces are mostly for use in other function signatures to be specific about what actions the function might perform on the state manager; there's no reason to design a state manager that doesn't implement all of statemgr. Full.

Graph Builder:

The terraform.Context method invokes a graph builder. A graph builder is used to represent the essential steps for that operation and the dependence relationships between them. Because the graph-building process differs by operation, each has its own graph builder. A "plan" operation, for example, requires a graph created directly from the configuration, whereas an "apply" action creates its graph from the set of modifications stated in the plan being applied.

Graph Walk:

The graph walking method visits each vertex of the graph in a fashion that respects the graph's "happens after" edges. Each vertex in the graph is assessed in such a way that the "happens after" edges are taken into account. The graph walk method will assess many vertices at the same time if possible.

Vertex Evaluation:

During a graph walk, the action executed for each vertex is referred to as execution. Execution PERFORMS a series of random operations that make sense for a given vertex type. Before the graph walk begins evaluating further vertices with "happens after" edges, a vertex must be complete correctly. When one or more errors occur during evaluation, the graph walk is interrupted and the errors are returned to the user.