Associate Exam Flashcards

Prepare with these: https://medium.com/@faisalkuzhan/day-55-90-terraform-interview-questions-e8ff859220d5

1
Q

Is locking happening automatically?

A

YES

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is “terraform taint” command?

A

Informs Terraform that a particular object has become degraded or damaged. Terraform represents this by marking the object as “tainted” in the Terraform state, in which case Terraform will propose to replace it in the next plan you create.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Command to create new workspace

A

terraform workspace new NAME

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Flag used to identify the specific version of a provider required.

A

required_providers

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

In which config block Terraform-specific setting are declared?

A

terraform

terraform {

required_providers {

aws = {

version = “>= 2.7.0”

source = “hashicorp/aws”

}

}

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Which command allow to retrieve a list of resources that are part of the state file?

A

terraform state list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Where local state is stored for a workspaces?

A

directory called terrraform.tfstate.d

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Can Terraform backed be migrated without de-provisioning the resources?

A

YES

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Where is the workspaces local state stored?

A

Directory terraform.tfstate.d

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What kind of resource dependany is stored in terraform.tfstate file?

A

Both implicit and explicit

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

The most verbose logging level

A

trace

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How to hide the output value in CLI?

A

use “sensitive” parameter

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Which command will upgrade the provider to the latest acceptable one?

A

terraform init -upgrade

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Can you publish your own modules in Terraform Registry?

A

YES

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Connection types supported by remote-exec?

A
  • ssh
  • winrm
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What’s the purpose of remote-exec?

A

Invokes a script on a remote resource after it is created

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Features exclusive to Terraform Enterpise

A
  • Audit logs
  • Clustering
  • SAML/SSO
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are limitations of SENSITIVE parameter?

A

The values are stored in the Terraform state and available using the terraform output command, so cannot be relied on as a sole means of protecting values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Two Terraform versions

A
  • open source
  • enterprise
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is terraform import?

A

This allows to take resource created by some other means and bring it under Terraform mangement.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

The purpose of “terraform validate” command.

A

Validates the configuration files in a directory, referrring only to the configuration and not accessing any remote services such as remote state, provider API, etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is a downside to using the Vault provider to read secrets from Vault?

A

Any secrets that you read and write to be persisted in both Terraform’s state file and in any generated plan files. For any Terraform module that reads or writes Vault secrets, these files should be treated as sensitive and protected accordingly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

When writing terraform code, HashiCorp recommends that you use how many spaces between each nesting level

A

2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

After executing a terraform apply. you notice that a resoruce has a tilde (~) next to it. What does this infer?

A

The resource will be updated in place

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

How local path must begin for local module

A

”./” or “../”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Which type of variable allows multiple values of several distinct types to be grouped together as a single value?

A
  • object
  • list
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Which command can be used to view th specified version constraint for all providers used in the current configuration?

A

terraform providers

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Is Role Based Access Control free?

A

NO

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

When should you use the force-unlock command?

A

Automatic unlocking failed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

In order to reduce the time it takes to provision resources, Terraform uses parallelism. By default, how many resources will Terraform provision concurrently?

A

10

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What can outputs be used for?

A
  • User reference
  • Input to other resources being created via terraform
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What is the statement that follows the resource in a terraform block called? IE resource “” “” {

A

Resource block

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

For an output what happens if you do not supply an attribute?

A

The output will provide all the attributes associated with the resource

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What are attributes?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What is an output?

A

A way to output specific attributes of a resource

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Where can you assign variables?

A
  • Environment variables
  • Command Line Flags
  • From a File
  • Variable Defaults
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What is a type argument in a variable block?

A

the type argument in a variable block allows you to restrict the type of value that will be accepted as the value for a variable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What is a type list

A

Sequential list of values identified by their position. Starts with 0
[
“apple”,
“orange”,
“pear”
]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What is a type map

A

a group of values identified by name labels, like
{
name = “Mabel”,
age = “52”
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

How can you reference a specific position in a list

A

var.[position (i.e. 1)]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

What is a local value?

A

A local value assigns a name to an expression, allowing it to be used multiple times within a module without repeating it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What is the general syntax of a function?

A

function(argument 1, argument 2)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What are the categories of functions in use by Terraform?

A

Numeric
String
Collection
Encoding
Filesystem
Date and Time
Hash and Crypto
IP Network
Type Conversion

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

Where can you test terraform functions?

A

terraform console

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

What does a lookup do?

A

retrieves the value of a single element from a map, given its key. If the given key does not exist, a the given default value is returned instead.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

What does an element do?

A

retrieves a single element from a list.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

What do data source allow

A

Data sources allow data to be fetched or computed for use elsewhere in Terraform configuration.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

How can you setup detailed logs for debugging

A

You can set TF_LOG to one of the log levels

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

How do you enable logging?

A

by exporting the logs and setting a verbosity level from the local console
- export TF_LOG=

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

How can you export Terraform Logs to a file?

A

by specifying a log path to export the TF logs to
- export TF_LOG_PATH=

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

What is the most verbose level of TF_LOG?

A

Trace

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

How can you validate the terraform configuration files for systematic validation?

A

terraform validate

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

What is the Terraform State File?

A

The state allows terraform to map real world resources to existing configuration. Terraform stores the state of the infrastructure in TF files

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

What is a desired state?

A

The specific configuration defined in a resource block is what creates a desired state

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

What is terraform refresh

A

Terraform refresh fetches the latest information about the current state of your infrastructure.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

What does Terraform plan do?

A

Match the desired state with the current state

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

What does terraform show do?

A

Shows all information within the terraform state file

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

Can Terraform providers have a different provider plugin version that Terraform?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

Where are terraform plugins installed?

A

.terraform/plugins directory

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

Can you specify a specific version number or a base version number for installing a provider?

A

Yes by providing a version statement in the provider configuration block

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

How can you obtain HashiCorp Distributed providers?

A

They are automatically downloaded during terraform init

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

How can you obtain non distributed providers?

A

Manually installed locally

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

Where do you download and install plugins for manual installation?

A
  • ~/.terraform.d/plugins directory
  • All manual plugins should be copied into the above directory
  • Terraform init will read from the ~/.terraform/plugins directory
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

What are terraform provisioners?

A

Provides the ability to configure an added resource using a defined script

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

How many types of provisioners are there?

A

2

66
Q

What are the types of provisioners?

A
  • local-exec
  • remote-exec
67
Q

What does a local-exec provisioner allow?

A

local-exec provisioners allow us to invoke local executable after resource is created

68
Q

What does a remote-exec provisioner allow?

A

Remote-exec provisioners allow to invoke scripts directly on the remote server

69
Q

What is required for a provisioner to run scripts on the remote server?

A

connection block with login information

70
Q

What are the two types of provisioners?

A
  • Creation-Time Provisioner
  • Destroy-Time Provisioner
71
Q

What is a creation-time provisioner?

A
  • creation time provisioners are only run during creation, not during updating or any other lifecycle
  • If a creation-time provisioner fails, the resource is marked as tainted
72
Q

What is a destroy-time provisioner?

A

destroy provisioners are run before the resource is destroyed

73
Q

When is a destroy provisioner invoked?

A

when = destroy is added to the provisioner block

74
Q

What does the on_failure setting do?

A

Ignore the error and continue with creation or destruction

75
Q

What is the DRY Principle

A

Dont Repeat Yourself

76
Q

What is the terraform registry?

A

modules that have already been written by the TF community

77
Q

How do you know if the input is required?

A

check the registry Note and Inputs section of the resource group

78
Q

What does multiple workspaces allow for in Terraform?

A

Terraform allows us to have multiple workspaces, with each of the workspaces we can have different set of environment variables associated.

79
Q

What command allows me to switch between workspaces?

A

terraform workspace

80
Q

What are the sub commands for terraform workspace?

A
  • delete
  • list
  • new
  • select
  • show
81
Q

What does the start denote when you run a terraform workspace show

A

what environment you are in

82
Q

What is terraform state file locking?

A

Whenever you are performing a write operation, terraform would lock the state file.

83
Q

Is locking available in S3?

A

No

84
Q

How can you create a locking mechanism for tfstate files stored in s3?

A

integrate dynamodb

85
Q

The current implementation of Terraform import can only import resources into the state. It does not generate configuration.

A

true

86
Q

You want to use terraform import to start managing infrastructure that was not originally provisioned through infrastructure as code. Before you can import the resource’s current state, what must you do in order to prepare to manage these resources using Terraform?

A

Update the configuration file to include the new resources.

87
Q

Usage of “terraform refresh” command

A

The terraform refresh command is used to reconcile the state Terraform knows about (via its state file) with the real-world infrastructure. This can be used to detect any drift from the last-known state, and to update the state file. This does not modify infrastructure, but does modify the state file.

88
Q

During a terraform plan, a resource is successfully created but eventually fails during provisioning. What happens to the resource?

A

the resource is marked as tainted

89
Q

You want to evaluate an expression in terraform before appying it. What command do you use?

A

Console

90
Q

Command to unlock the locked state file

A

force-unlock

91
Q

Command used to automatically obtain and save an API token for Terraform Cloud, Terraform Enterprise, or any other host that offers Terraform services

A

terraform login

92
Q

Command to inspect the current state files

A

terraform show

93
Q

Databse used by backend terraform enterpsie

A

postgresql

94
Q

Environment variables format

A

TF_VAR_name

95
Q

Command to Force plugin installation to read plugins only from the specified directory

A

terraform init -plugin-dir=PATH

96
Q

Terraform Plugins language

A

Go

97
Q

Command to manually unlock the state for the defined configuration.

A

terraform force-unlock [options] LOCK_ID [DIR]

98
Q

Which backen has default state locking?

A
  • azurerm
  • gcs
99
Q

Which terraform command reads the current settings from all managed remote objects and updates the Terraform state to match

A

tarraform refresh

100
Q

You wanted to play with terraform to check what it has to offer. After a while you remembered that you didn’t specify any configuration for the backend. What default behaviour is expected here of terraform?

A

Terraform uses local backend.

101
Q

Terraform Cloud workspaces and Terraform CLI workspaces are not the same, though they share similar concepts. What’s different?

A

**Purpose and Scope:
**Terraform CLI Workspaces: These are used to manage multiple state files within a single working directory, providing isolated environments for different configurations or stages of an infrastructure project (e.g., development, staging, production) [3].
Terraform Cloud Workspaces: These are designed for managing infrastructure in a more collaborative and scalable way, offering additional features such as remote state management, VCS integration, and policy enforcement. Terraform Cloud workspaces are better suited for long-lived environments and team collaboration [1, 5].
State Management:
Terraform CLI Workspaces: State is stored locally or remotely (e.g., in an S3 bucket) but managed from the local CLI environment.
Terraform Cloud Workspaces: State is stored and managed remotely in Terraform Cloud, providing built-in state locking and history for enhanced safety and collaboration [1].

102
Q

To begin writing a Terraform configuration while adhering to the best practices, we create the files below in the project’s root directory

A

provider.tf – containing the terraform block, s3 backend definition, provider configurations, and aliases.
main.tf – containing the resource blocks which define the resources to be created in the target cloud platform.
variables.tf – containing the variable declarations used in the resource blocks.
output.tf – containing the output that needs to be generated on successful completion of “apply” operation.
*.tfvars – containing the environment-specific default values of variables.

103
Q

slicing the main.tf files into different layers - what would you find?

A

By services – the team may include all the components required to support a particular business service in one file. This file includes all the databases, compute resources, network configs, etc., in a single file. The file is named as per the service being supported. Thus, while doing the root cause analysis (RCA), we already know which Terraform file needs to be investigated.
By components – it may be decided to segregate the resource blocks based on the nature of the components used. A Terraform project may have a single file to manage all the databases. Similarly, all network configurations, compute resources, etc., are managed in their individual files.

104
Q

What types of provisioners are available?

A

Terraform supports three primary types of provisioners:

File Provisioner:

Used for copying files from the local machine to the newly created resource.
Example use case: Deploying a configuration file to a remote server [3].

**Local-Exec Provisioner:
**Executes commands on the local machine where Terraform is run.
Example use case: Running a script to configure infrastructure after creation [3].

**Remote-Exec Provisioner:
**Runs commands on the remote resource after it is created.
Example use case: Running configuration management tools on a remote server [5].
Provisioners are typically used for tasks that cannot be accomplished directly through Terraform’s resource model, such as running custom scripts or commands during the provisioning process

105
Q

What can you use for any name for a variable except?

A

We can use any name for a variable except for: source, version, providers, count, for_each, lifecycle, depends_on and locals.

We have used the variable name as “providers”. This is not a valid identifier

106
Q

Passing an object containing a sensitive input variable to the keys() function will result in a list that is _ .

A

Sensitive

107
Q

Can you delete the default Terraform workspace.

A

No, you cannot delete the default Terraform workspace. The default workspace is a special workspace that is always present and cannot be deleted. Terraform starts with a single workspace called “default,” and this workspace cannot be removed to ensure that there is always a workspace available for managing state [1].

If you attempt to delete the default workspace, Terraform will fail with an error, as it requires the default workspace to be present [3].

108
Q

For local state, Terraform stores the workspace states in a directory called :

A
109
Q

Terraform import command updates the configuration files as well as the state file, with the details of the infrastructure being imported?

A

For local state, Terraform stores the workspace states in a directory called terraform.tfstate.d. Within this directory, it creates sub-directories for each workspace to manage multiple states with a single configuration directory

110
Q

What are the valid sub-commands of the Terraform state command?

A

The valid sub-commands of the Terraform state command include:

terraform state list: Lists all resources in the state file or specific resources matching given addresses [1].
terraform state show: Displays detailed state information about a single resource [2].
terraform state mv: Moves an item in the state file [2].
terraform state pull: Pulls the current state and outputs it in JSON format [4].
terraform state push: Updates remote state from a local state file [2].
terraform state rm: Removes items from the state file [3].
terraform state replace-provider: Replaces provider references in the state [2].

111
Q

You were working with different terraform scripts which are provisioning various sets of resources , you need to look up for some additional details related to one specific resource from the state file. Which terraform command will help you achieve this?

A

Terraform state show “Address”

112
Q

What is Terraform Sentinel?

A

Terraform Sentinel is a policy-as-code framework developed by HashiCorp that allows you to enforce policies on Terraform configurations, states, and plans. It provides a way to define, enforce, and manage compliance and governance policies as code. Here are some key features of Terraform Sentinel:

Policy Enforcement: Sentinel can enforce rules on Terraform plans and configurations before any infrastructure changes are applied. This ensures that all changes comply with organizational policies and standards [1].
Integration with Terraform Enterprise: Sentinel is tightly integrated with Terraform Enterprise, enabling centralized policy management and enforcement across your infrastructure deployments [2].
Policy Language: Sentinel uses a custom policy language that allows you to create complex policies. It includes useful functions and imports to define rules and evaluate Terraform configurations [1].

113
Q

The label after the variable keyword should be unique among all

A

keywords in the same module

114
Q

The for_each Meta-Argument Accepts What Inputs?

A

The for_each meta-argument in Terraform accepts the following inputs:

Map: A collection of key-value pairs.
Set: A collection of unique values.

These inputs are used to iterate over a data structure to configure a set of similar resources, modules, or data blocks. Unlike most arguments, the value for for_each must be known before Terraform performs any remote operations [1].

115
Q

Which “terraform command” from the following downloads the latest version of the provider plugins?

A

terraform init

116
Q

Default Behavior of Terraform When Provider Version is Not Specified?
🗒️

A

When the provider version is not specified in the terraform block, Terraform will use the latest version available. This behavior can lead to unexpected changes in the provider version used by your configuration, potentially causing compatibility issues if the latest version introduces breaking changes. It’s recommended to always specify the provider version explicitly in the terraform block to ensure predictable behavior and avoid compatibility issues.

117
Q

Define and Describe the Optional Arguments That Are Available for the Output

A

description: This argument is used to provide a description of the output value. It is helpful for documenting the purpose and content of the output.
output “example” {
value = aws_instance.example.public_ip
description = “The public IP address of the example instance.”
}

sensitive: When set to true, this argument marks the output value as sensitive. Sensitive values will be hidden in the CLI output to avoid displaying sensitive information.
output “example_password” {
value = aws_db_instance.example.password
sensitive = true
}

**depends_on: **This argument allows you to specify dependencies explicitly. This ensures that the output value is only calculated after the specified dependencies are fully created or updated.

hcl
Copy code
output “example” {
value = aws_instance.example.public_ip
depends_on = [aws_instance.example]
}

118
Q

Using Dynamic Blocks for Meta-Argument Blocks

A

No, you cannot use dynamic blocks to generate meta-argument blocks such as lifecycle and provisioner blocks. Dynamic blocks are specifically designed to generate repeated nested blocks of configuration, like those for defining multiple AWS instances or Google Cloud Storage buckets. Meta-argument blocks, on the other hand, are used to configure special behaviors of resources (like lifecycle for resource lifecycle management or provisioner for defining provisioners) and are not supported for dynamic generation. These blocks must be explicitly defined in the resource configuration.

119
Q

In the UI and VCS workflow, every workspace is associated with a specific branch of a VCS repo of Terraform configurations. T/F?

A

True
In the UI and VCS workflow, every workspace is associated with a specific branch of a VCS repo of Terraform configurations. Terraform Cloud registers webhooks with your VCS provider when you create a workspace, then automatically queues a Terraform run whenever new commits are merged to that branch of workspace’s linked repository.

120
Q

Referencing Attributes in Terraform Expression?

A

Resource Attributes: resource_type.resource_name.attribute_name, where resource_type is the type of the resource, resource_name is the name of the resource, and attribute_name is the attribute you want to reference.
Example: aws_instance.example.public_ip

Variable Attributes: var.variable_name, where variable_name is the name of the variable you want to reference.
Example: var.region

Output Attributes: output.output_name, where output_name is the name of the output you want to reference.
Example: output.ip_address

Data Source Attributes: data.data_source_name.attribute_name, where data_source_name is the name of the data source and attribute_name is the attribute you want to reference.

Example: data.aws_ami.ubuntu.id

121
Q

A simple terraform configuration file is given below. What is the name of the resource that will be created?

resource “local_file” “pet” {​
filename = “/root/pets.txt”​
content = “We love pets!”​ ​
}

A

pet

122
Q

What can a dynamic block generate?

A

A dynamic block can only generate arguments that belong to the resource type, data source, provider or provisioner being configured. It is not possible to generate meta-argument blocks such as lifecycle and provisioner blocks , since Terraform must process these before it is safe to evaluate expressions.

123
Q

terraform plan and terraform apply both refresh the state before their execution. Which option could be used to disable this default behaviour?

A

-refresh=false

124
Q

Describe the available arguments that are available for the lifecycle meta-argument:

A

The lifecycle meta-argument in Terraform allows users to control the behavior of resource creation, updates, and deletion. The available arguments within a lifecycle block are:

create_before_destroy: Ensures that a new resource is created before the old resource is destroyed. This is useful for resources where downtime needs to be minimized.
prevent_destroy: Prevents Terraform from destroying the resource. If a terraform destroy or any plan that would result in destruction is applied, it will fail.
ignore_changes: Specifies attributes of a resource that should be ignored during updates. This is useful when certain attributes are managed outside of Terraform.
replace_triggered_by: Forces resource replacement when a specified attribute or resource changes. This can include references to other resources or attributes within the same resource [1], [2], [6].
These arguments help manage the resource lifecycle more effectively, providing greater control over infrastructure changes and stability.

125
Q

Terraform language supports user-defined functions

A

False

126
Q

# What steps are needed in order to change the backend in terraform? For instance: local to remote

A

Update Backend Configuration:
Modify your Terraform configuration file to include the remote backend configuration. For example, if you are migrating to an S3 backend, your configuration might look like this:
terraform {
backend “s3” {
bucket = “my-terraform-state-bucket”
key = “path/to/my/key”
region = “us-west-2”
}
}

**Initialize the New Backend:
**Run terraform init -reconfigure. This command will prompt Terraform to initialize the new backend and migrate your existing state.
terraform init -reconfigure
Confirm State Migration:
During the terraform init -reconfigure process, you will be asked to confirm the migration of the existing state to the new backend. Confirm the prompt to proceed with the migration.
Verify the Migration:

After the initialization is complete, you can verify that the state has been successfully migrated to the remote backend. This can be done by checking the state file in the remote backend (e.g., S3 bucket) or by running terraform state list to ensure the state is consistent.
Cleanup:

Optionally, remove any local state files to avoid confusion, ensuring that your infrastructure state is managed exclusively by the remote backend.

127
Q

Can you export the debug logs from terraform only by setting the TF_LOG_PATH environment variable?

A

False

128
Q

This lifecycle meta-argument supports a list as a value ?

A

ignore_changes (list of attribute names) - By default, Terraform detects any difference in the current settings of a real infrastructure object and plans to update the remote object to match configuration.

129
Q

General syntax for function calls is :

A

The general syntax for function calls involves specifying the function’s name followed by parentheses (). If the function requires input values, known as parameters, they are placed within the parentheses. Here is the basic structure:

function_name(parameter1, parameter2, …);
Example
int result = add(5, 10);
In this example:

add is the function name.
5 and 10 are the parameters passed to the function

130
Q

“alias” and “version” are the meta-arguments which are available for all provider blocks?

A

True

131
Q

What happens when provisioners fail to execute successfully?

A

When provisioners fail to execute successfully in Terraform, several things can happen:

Terraform Apply Failure: The entire terraform apply process will fail. Terraform treats a failed provisioner as a failure for the resource creation or modification, which results in the apply operation being halted [1, 4].

Provisioner Error Reporting: Terraform will report the specific error encountered by the provisioner. This can include issues like the script not being readable, network connectivity problems, or script execution errors [2, 6].

Resource State Impact: The state of the resource can be impacted if the provisioner fails. Terraform may leave the resource in an incomplete or inconsistent state, requiring manual intervention to resolve the issue before re-running terraform apply [3].

Retry and Troubleshooting: Users may need to troubleshoot and retry the provisioner. This can involve checking the provisioner script for errors, ensuring the remote machine is accessible, and verifying any dependencies or prerequisites are met [1, 5].

To handle provisioner failures more gracefully, Terraform allows the use of on_failure argument in the provisioner block to specify how to handle failures, such as continuing the operation or attempting retries.

132
Q

Choose the suitable option that could be used to access one of the module’s output values.

A

module.<MODULE_NAME>.<OUTPUT_NAME></OUTPUT_NAME></MODULE_NAME>

Here’s a step-by-step guide:
Define the output in the module: Ensure the module has an output value defined in its outputs.tf file.

output “example_output” {
value = <some_value>
}
Reference the output in the parent module: In the configuration where the module is called, access the output value using the module's name and the output's name.</some_value>

module “example” {
source = “./path/to/module”
# module inputs
}

output “module_output_value” {
value = module.example.example_output
}

133
Q

Considering provisioners are the best way to solve your problem, in what way could you make use of provisioner block.

A

Inside resource block
Provisioners in Terraform are used to execute scripts or commands on a local or remote machine during resource creation or destruction. They are particularly useful for tasks that need to happen after the infrastructure is provisioned, such as configuring software, installing packages, or running configuration management tools.

134
Q

Describe terraform default workspace.

A

Terraform starts with a single workspace named “default”. This workspace is special both because it is the default and also because it cannot ever be deleted. If you’ve never explicitly used workspaces, then you’ve only ever worked on the “default” workspace.

135
Q

Describe local values

A

Local values are created by a locals block (plural), but you reference them as attributes on an object named local (singular). Make sure to leave off the “s” when referencing a local value!

136
Q

Which variable block argument prevents terraform from showing sensitive data in plan or apply output?

A

sensitive = true

137
Q

Which argument of the lifecycle meta-argument supports a list as a value ?

A

ignore_changes (list of attribute names) - By default, Terraform detects any difference in the current settings of a real infrastructure object and plans to update the remote object to match configuration.

138
Q

The default argument within the variable block should satisfy?

A

Provide a Sensible Default:

The default value should be a reasonable and sensible value that the variable can fall back on if no other value is provided. This ensures that the Terraform configuration can proceed without errors if the user doesn’t specify a value for the variable.
Match the Variable Type:

The default value must match the declared type of the variable. For instance, if the variable is of type string, the default value should also be a string.
Be Optional:

The presence of a default value makes the variable optional. Users can override the default value by providing their own value when calling the module or running a Terraform plan or apply.
Improve Usability:

Using default values can improve the user experience by reducing the number of required inputs and making the configuration more user-friendly.

variable “instance_type” {
description = “The type of instance to use”
type = string
default = “t2.micro”
}

139
Q

What steps are needed to enable state-locking to protect state file from concurrent operations against the same terraform configuration?

A

If supported by your backend, Terraform will lock your state for all operations that could write state. This prevents others from acquiring the lock and potentially corrupting your state.

140
Q

What are the common issues that come with configuration drift?

A

Configuration drift occurs when systems and configurations deviate from their established baseline or standard over time. This drift can lead to several common issues:

Application Failures:

Inconsistencies between environments can cause applications to fail due to differences in configurations that the application depends on [3].
Increased Downtime:

Unexpected changes or differences in configuration can lead to system outages or extended downtime as issues are diagnosed and resolved [3].
Security Vulnerabilities:

Deviations from the baseline configuration can introduce security holes, making systems more susceptible to attacks [1].
Prolonged Development Lifecycles:

Drift can cause delays in development and deployment processes, as developers spend more time troubleshooting and aligning environments [3].
Increased IT Support Tickets:

Drift often leads to more frequent issues, resulting in an increased volume of support tickets and a greater burden on IT teams [3].
Manual Configuration Errors:

Manual changes to configurations can introduce errors that lead to drift, making it harder to maintain consistent and reliable environments [5].
Inconsistent Performance:

Variations in configurations can lead to inconsistent performance across different environments, complicating performance tuning and reliability [4].

141
Q

The __ displays the current version of Terraform and of all installed plugins.

A

terraform version

142
Q

Terraform assumes an empty default configuration for any provider that is not explicitly configured.

A

True

143
Q

You recently joined an organization with the capacity of devops-engineer. Your team has been working on various projects and you were assigned one that involves heavy usage of terraform configuration files. You wanted to extract the list of resources that have been provisioned till date using this terraform configuration. What terraform command would you make use of to achieve this?

A

terraform state List

144
Q

Provisioners can only be used to model specific actions on a remote machine in order to prepare servers or other infrastructure objects for service.

A

Provisioners in Terraform are designed to execute scripts or commands on remote or local machines during the resource creation or destruction process. They are often used to prepare servers or other infrastructure objects for service. This includes tasks like installing software, configuring services, and setting up the environment. Provisioners can handle actions on both local and remote machines, contradicting the statement that they can only be used on remote machines.

Examples of Provisioners:
Remote-exec Provisioner: Executes commands on a remote machine using SSH or WinRM.
Local-exec Provisioner: Executes commands on the machine running Terraform.
These provisioners can perform various setup tasks necessary for the infrastructure to function correctly.

Key Use Cases:
Software Installation: Installing necessary software packages on servers.
Configuration Management: Applying configuration changes to servers.
Custom Scripts: Running custom scripts to perform specific actions during resource setup.
Provisioners should be used cautiously as they introduce additional complexity and potential failure points in Terraform configurations [1].

145
Q

The splat expression patterns shown below is not applicable for what?

A

The splat expression pattern var.list[*].id is not applicable in the following scenarios:

Null or Empty Lists: The splat operator cannot be applied to a null value or an empty list. If var.list is null or empty, attempting to use the splat operator will result in an error [1][3].

Non-List Types: The splat operator is designed to work with lists, sets, or tuples. If var.list is of a different type (e.g., a string or a map), the splat expression will not be applicable [1].

Incorrect Resource References: If the items in the list do not have an id attribute, the splat expression var.list[*].id will not work. Each item in the list must have the specified attribute for the splat operator to function correctly [5].

146
Q

What are the possible consequences of making heavy usage of provisioners within your Terraform script?

A

Heavy usage of provisioners within your Terraform script can lead to several potential consequences:

Resource Tainting: If a creation-time provisioner fails, the resource is marked as tainted. This means Terraform will plan to destroy and recreate the resource on the next apply, which can lead to unnecessary resource churn and potential downtime [2].

Error Handling Complexity: Provisioners add complexity in terms of error handling. If a provisioner fails during resource destruction, Terraform will continue with the destruction process, which might leave your infrastructure in an inconsistent state [3][4].

Operational Overhead: Provisioners can introduce operational overhead, as they require careful scripting and management. This overhead can lead to increased maintenance efforts and the potential for human error [1].

Performance Issues: Excessive usage of provisioners, especially with complex or long-running scripts, can negatively impact the performance of your Terraform runs. This can result in longer deployment times and a less efficient infrastructure management process [1].

Debugging Difficulties: Provisioners can make debugging Terraform configurations more difficult. Failures within provisioner scripts can be harder to diagnose and resolve compared to issues within Terraform’s declarative configuration [1].

Reduced Portability: Heavy reliance on provisioners can reduce the portability of your Terraform configurations. Provisioners often contain environment-specific scripts and commands, which can make it challenging to reuse configurations across different environments without modification [1].

🌐 Sources

https://spacelift.io/blog/terraform-provisioners
https://github.com/hash

147
Q
A
148
Q

What will happen if Terraform isn’t able to obtain acceptable versions of external dependencies, or if it doesn’t have an acceptable version of itself?

A

Both the root module and any child module can constrain the acceptable versions of Terraform and any providers they use. Terraform considers these constraints equal, and will only proceed if all of them can be met.

149
Q

Which provider is used in the below code snippet:

resource “aws_instance” “foo” {
provider = aws.west

# …
}

A

aws.west
To use an alternate provider configuration for a resource or data source, set its provider meta-argument to a .

150
Q

Choose the correct command which is used to list all existing workspaces.

A

The correct command to list all existing workspaces in Terraform is:

terraform workspace list

This command will display all existing workspaces, and the current workspace will be indicated with an asterisk (*).

https://learning-ocean.com/tutorials/terraform/terraform-workspace/

151
Q

# The lifecycle block and its contents are available for all resource blocks regardless of type.

A

🗒️ Answer
The lifecycle block and its contents are indeed available for all resource blocks in Terraform, regardless of the resource type. This block allows you to control the creation, modification, and deletion of resources using various meta-arguments such as create_before_destroy, prevent_destroy, ignore_changes, and replace_triggered_by [1] [3].

https://developer.hashicorp.com/terraform/language/meta-arguments/lifecy

152
Q

What are the appropriate options for which we can make use of version constraints:

A

In Terraform, version constraints are used to specify the versions of Terraform, providers, and modules that are compatible with your configuration. The appropriate options for using version constraints include:

Terraform Version: Specify the version of Terraform itself to ensure compatibility with your configuration.

hcl
Copy code
terraform {
required_version = “>= 1.0.0”
}

Provider Versions: Define the acceptable versions of providers, such as AWS, Azure, or Google Cloud, that your configuration can use.

terraform {
required_providers {
aws = {
source = “hashicorp/aws”
version = “~> 3.0”
}
}
}

Module Versions: Restrict the versions of modules to ensure compatibility and stability within your infrastructure.

module “vpc” {
source = “terraform-aws-modules/vpc/aws”
version = “>= 2.0.0, < 3.0.0”
}

https://developer.hashicorp.com/terraform/language/expressions/version-c

153
Q

# What workflows that Terraform Cloud utilizes to manage Terraform runs:

A

Terraform Cloud utilizes three main workflows to manage Terraform runs:

CLI-driven run workflow: This workflow allows users to initiate Terraform runs directly from the command line interface (CLI), providing flexibility and control for advanced users and scripts [1].

API-driven run workflow: This workflow is designed for integration with other systems and automation tools. It enables users to trigger and manage Terraform runs programmatically via API calls [2].

UI/VCS-driven run workflow: The primary mode of operation for most users, this workflow involves initiating Terraform runs through the Terraform Cloud user interface (UI) or via version control system (VCS) integrations. It is user-friendly and integrates well with existing development workflows [3].

[https://developer.hashicorp.com/terraform/cloud-docs/run/cli]

https://developer.hashicorp.com/terraform/cloud-docs/run/ui

154
Q

# The main way to package and reuse resource configurations with Terraform is through ??.

A

Modules in Terraform are the main way to package and reuse resource configurations. Modules allow you to encapsulate related resources, variables, and outputs, making it easier to manage and reuse configurations across different parts of your infrastructure or in different projects. With modules, you can create reusable building blocks for your infrastructure, promote code reusability, and maintain a consistent infrastructure configuration across your organization.

https://blog.gruntwork.io/how-to-create-reusable-infrastructure-with-ter

https://developer.hashicorp.com/terraform/language/modules#:~:text=Modules%20are%20the%20main%20way,reuse%20resource%20configurations%20with%20Terraform.

155
Q

Is it possible to declare the dynamic block inside another dynamic block?

A

Some providers define resource types that include multiple levels of blocks nested inside one another. You can generate these nested structures dynamically when necessary by nesting dynamic blocks in the content portion of other dynamic blocks.

https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks#multi-level-nested-block-structures

156
Q

You can dynamically construct repeatable nested blocks using which special block type:

A

You can dynamically construct repeatable nested blocks like setting using a special “dynamic block” type, which is supported inside “resource”, “data”, “provider”, and “provisioner” blocks.

157
Q

What are the techniques that could be used to safely and securely manage secrets inside terraform?

A

Use a secure remote backend: Storing your Terraform state files in a secure remote backend such as AWS S3 with encryption and access controls helps protect sensitive data [2].
Use environment variables: Storing secrets as environment variables rather than hard-coding them in Terraform files helps keep them secure.

Store secrets in a secure external storage: Utilize secure secret management services like AWS Secrets Manager, HashiCorp Vault, or Azure Key Vault to manage and access secrets securely [3].
Encrypt sensitive data: Encrypting sensitive data using tools like KMS, PGP, or other encryption methods ensures that even if the data is accessed, it remains protected [2].
Secure the Terraform host: Ensure that the machine running Terraform is secure and follows best practices for security, such as restricting access and using secure communication channels [2].

https://spacelift.io/blog/terraform-secrets

https://blog.gruntwork.io/a-comprehensive-guide-to-managing-secrets-in-your-terraform-code-1d586955ace1

158
Q

why we may need to specify the provider’s argument?

A

To override the default provider configuration. For example, the default configuration may be to deploy resources in the “us-east-1” region. If the requirement is to deploy resources in a different region, we can use the provider argument to override the default.

In some cases, a configuration may need to use multiple versions of the same provider. For example - a resource that deploys to the “us-east-1” and another resource within the same configuration that deploys to the “us-west-2” region.

https://developer.hashicorp.com/terraform/language/meta-arguments/module

159
Q

option for referencing local values from the below code snippet:

locals {
# Common tags to be assigned to all resources
common_tags = {
Service = local.service_name
Owner = local.owner
}
}

resource “aws_instance” “example” {
# …

tags = ____________
}

A

Local values are created by a locals block (plural), but you reference them as attributes on an object named local (singular). Make sure to leave off the “s” when referencing a local value!

160
Q

What environment variable needs to be defined in terraform for the persistence of the logged output?

A

To persist logged output you can set TF_LOG_PATH in order to force the log to always be appended to a specific file when logging is enabled. Note that even when TF_LOG_PATH is set, TF_LOG must be set in order for any logging to be enabled.