KEMBAR78
Terraform Notes-1-1 | PDF | Data Type | Boolean Data Type
0% found this document useful (0 votes)
34 views44 pages

Terraform Notes-1-1

The document provides a comprehensive overview of Terraform commands and concepts, including the functions of commands like terraform init, plan, apply, and destroy, as well as the importance of provider and resource blocks. It discusses the significance of the terraform.tfstate file, variable management, and output values, along with best practices for using providers and managing dependencies. Additionally, it covers variable precedence and methods for assigning values to variables, emphasizing the flexibility and reusability of Terraform configurations.

Uploaded by

Saurabh Dube
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views44 pages

Terraform Notes-1-1

The document provides a comprehensive overview of Terraform commands and concepts, including the functions of commands like terraform init, plan, apply, and destroy, as well as the importance of provider and resource blocks. It discusses the significance of the terraform.tfstate file, variable management, and output values, along with best practices for using providers and managing dependencies. Additionally, it covers variable precedence and methods for assigning values to variables, emphasizing the flexibility and reusability of Terraform configurations.

Uploaded by

Saurabh Dube
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

1. What does the terraform init command do?

Ans ->
The terraform init command initializes a Terraform working directory. It performs the
following tasks:

 Downloads Provider Plugins: It installs the necessary provider plugins (e.g., AWS,
Azure, GCP) that are defined in the configuration files.
 Initializes Backend: If a backend is configured (e.g., for storing Terraform state), it
initializes the connection to that backend.
 Installs Modules: If modules are used in the Terraform configuration, it downloads
and installs the required modules.
 Prepares the Environment: Sets up the working directory for use with subsequent
Terraform commands, such as terraform plan or terraform apply.

In short, terraform init sets up the necessary components for Terraform to interact with
the cloud environment defined in your configuration.
2. What does the terraform plan command do?

Ans ->
Purpose: It generates an execution plan, showing what changes Terraform will make to
your infrastructure.
Functionality:

 Compares the desired state defined in your configuration files with the current
state of the infrastructure (from the state file).
 Outputs a detailed list of actions that will be performed (e.g., resources to be
created, updated, or destroyed).
 Helps to verify and preview changes before applying them.
In summary: terraform plan shows a preview of the changes.
3. What does the terraform apply command do?

Ans ->
Purpose: It applies the changes required to reach the desired state of the
infrastructure.
Functionality:

 Executes the actions proposed in the plan (or automatically generates and
applies the plan if no plan is provided).
 Makes actual changes to the infrastructure based on the configuration, such as
creating, modifying, or destroying resources.
 Once the changes are applied, it updates the state file to reflect the current
infrastructure state.
In summary: terraform apply actually makes the changes to your infrastructure.

4. Explain about Terraform provider block.

Ans ->

In Terraform, the provider block specifies the platform (like AWS, Azure, GCP) that
Terraform will interact with. It handles:

 Platform Configuration: Defines where and how Terraform will manage


resources (e.g., AWS, Azure, etc.).
 Authentication: Contains credentials to connect to the platform.
 Region/Project Settings: Specifies regional or project-level details for resource
management.
 Multiple Providers: Allows managing resources across different platforms in
one configuration.
 Example:

provider "aws" {
region = "us-west-2"
access_key = "YOUR_ACCESS_KEY"
secret_key = "YOUR_SECRET_KEY"
}
provider "azurerm" {
features {}
}
provider "google" {
credentials = file("file-path.json")
project = "my-project-id"
region = "us-central1"
}

5. Explain about Terraform resource block.

Ans ->
In Terraform, a resource block is used to define infrastructure components like servers,
networks, or databases. It tells Terraform what to create, modify, or destroy.

Primary syntax of resource block is:

resource "provider_resource_type" "resource_name" {


# Configuration for the resource
}
Key Parts:
 provider_resource_type: Specifies the provider (e.g., aws, azurerm) and the
resource type (e.g., instance, virtual_network).
 resource_name: A unique identifier for the resource in your configuration.
 Configuration: Defines the attributes of the resource (e.g., instance type,
region).
 Example:
resource "aws_instance" "my_ec2" {
ami = "ami-12345678"
instance_type = "t2.micro"
}

6. Explain about different types of Provider Tiers in Terraform.

Ans ->
In Terraform, provider tiers are used to categorize providers based on their level of
support, development process, and maturity. There are three main provider tiers:
Official Providers:

 Developed and maintained by HashiCorp.


 Highest level of support and stability.
 Examples: aws, azurerm, google.

Verified/Partner Providers:

 Built by third-party partners and verified by HashiCorp for quality.


 Supported by the third-party vendor.
 Examples: datadog, cloudflare, splunk.

Community Providers:

 Created by the open-source community, with varying support levels.


 Not verified by HashiCorp.
 Examples: Providers for niche tools or services.
7. Explain about Provider Namespace in Terraform.

Ans ->
In Terraform, the provider namespace helps organize providers and avoid conflicts
when different sources create similar providers. It follows this format:
<namespace>/<provider>

Key Points:

 Namespace: Identifies the organization or author of the provider.


 Official providers by HashiCorp use the hashicorp namespace (e.g.,
hashicorp/aws).
 Third-party or verified/partner providers use the vendor's namespace (e.g.,
datadog/datadog).
 Community or non verified providers use community member or
organization (e.g., community/random).

Purpose: It ensures clarity and allows Terraform to distinguish between different


providers, especially when multiple providers exist for the same service.
In short, namespaces like hashicorp, vendor names, or community names
categorize the provider source and help organize them in Terraform.
8. Explain about how can non-terraform maintained provider source can be used in
terraform

Ans ->

Terraform requires explicit source information for any providers that are not HashiCorp-
maintained, so we have to use a new syntax in the required_providers nested block
inside the terraform configuration block.

 Example of Using a Verified/Partner Provider: Let's say you want to use the
Datadog provider, which is maintained by Datadog (not HashiCorp). You specify the
source as follows:
terraform {
required_providers {
datadog = {
source = "datadog/datadog"
version = "~> 3.0"
}
}
}

provider "datadog" {
api_key = "your_api_key"
}
 Example of Using a Community Provider: For a community-maintained provider
(e.g., "community/spotinst"):
terraform {
required_providers {
spotinst = {
source = "community/spotinst"
version = "~> 1.0"
}
}
}

provider "spotinst" {
token = "your_spotinst_token"
}
9. Explain about the terraform destroy command.

Ans ->
The terraform destroy command is used to delete all the infrastructure resources that
have been created using a Terraform configuration. This command essentially reverts
the changes made by terraform apply by destroying the resources defined in the
Terraform state.

terraform destroy with -target flat allows us to destroy specific resource.


Example:
resource "aws_instance" "myfirstec2" {
ami = "ami-0614680123427b75e"
instance_type = "t2.micro"
}

To delete the above resource we have to use combination of resource type + local
resource name:
terraform destroy -target aws_instance.myfirstec2

Note: After destroying the resource, we have to either the remove the resource code
block or comment it, if not done so, the next time when we run terraform apply
command it will try to create the same resource which we've destroyed.

10. Is there any other way to destroy resources without using the terraform destroy
command?

Ans ->
Yes, there is a way to destroy or remove resources managed by Terraform without
using the terraform destroy command directly. Here is the alternative:
Manually Removing Resources from Terraform Configuration and Applying
Changes:

 Steps:
 Delete or comment out the specific resource block from the Terraform
configuration.
 Run terraform apply to update the infrastructure.
 Terraform will detect that the resource is no longer defined and will remove it
from the infrastructure.
11. Explain about importance of terraform.tfstate file

Ans ->
The terraform.tfstate file is essential for tracking the state of infrastructure managed by
Terraform. It maps the configuration to actual resources and helps Terraform plan and
apply changes.
Key functions include:

 Resource Mapping: Links configuration to real resources (e.g., IDs, IPs).


 Infrastructure Sync: Keeps Terraform aware of existing resources for changes.
 Performance: Reduces API calls by storing resource details.
 Drift Detection: Identifies manual changes outside of Terraform.
 Collaboration: Allows team access via remote storage (e.g., S3, Terraform Cloud).
 It stores:
 Resource IDs: Unique identifiers (e.g., EC2 IDs).
 Attributes: Details like instance type, IPs, AMIs.
 Metadata: Provider-specific details.
 Dependencies: Relationships between resources.
 Resource State: Status (created, modified, destroyed).

12. Explain about the Desired State and Current State in Terraform.

Ans ->
In Terraform, the desired state is the infrastructure setup defined in your configuration
files (e.g., .tf files), representing the state you want your resources to have.

The current state is the actual infrastructure managed by Terraform, stored in the
terraform.tfstate file, reflecting the real-world status of your resources.

How They Work:

 When you run terraform plan, Terraform compares the desired state with the
current state to determine the changes needed.
 Terraform then creates a plan and applies it with terraform apply to sync the
infrastructure to the desired state.
In short, desired state is your configuration, and current state is the actual
infrastructure managed by Terraform, ensuring they stay aligned.
13. Why it is important to explicitly set Provider Version?

Ans ->

Explicitly setting the provider version in Terraform ensures:

1. Stability: Prevents unexpected changes from newer versions.


2. Avoids Breaking Changes: Protects against disruptive updates.
3. Consistency: Ensures all environments use the same version.
4. Controlled Upgrades: Lets you test and upgrade safely.

In short, it helps maintain reliable, consistent infrastructure management.

Example:

provider "aws" {
region = "us-west-2"
version = "~> 3.50" # Ensures use of AWS provider versions from 3.50.x to
below 4.0
}

14. Arguments for Specifying Provider versions.

Ans ->

15. Explain about the importance of Dependency Lock file.

Ans ->
The dependency lock file (.terraform.lock.hcl) in Terraform allows us to lock to a
specific version of the provider.

If a particular provider already has a selection recorded in the lock file, Terraform will
always re-select that version for installation, even if a newer version has become
available.
You can override that behavior by adding the -upgrade option when you run terraform
init command. This will look like: terraform init -upgrade
16. Explain about the terraform refresh command and why it's dangerous to use this
command explicitly?

Ans ->

The terraform refresh command updates the current state stored in the
terraform.tfstate file by re-querying the actual infrastructure. It ensures that Terraform's
state file matches the real-world status of resources, such as any manual changes
made outside of Terraform.
Why it's risky:

Using terraform refresh is risky because it updates the state with manual changes and
the terraform.tfstate file data can be lost, which can lead to unexpected resource
changes or disruptions during terraform apply, potentially causing infrastructure
issues.
Note: You shouldn't typically need to use this command, because Terraform
automatically performs the same refreshing actions as a part of creating a plan in both
the terraform plan and terraform apply commands.

17. Explain about Cross Referencing Resource Attribute.

Ans ->

In Terraform, cross-referencing resource attributes allows you to use the output or


attributes of one resource as input for another resource. This creates a dependency
between the two resources, ensuring Terraform creates or updates them in the correct
order.
Default Syntax: <Resource_Type>.<Local_Name>.<Attribute>

Example:
resource "aws_vpc" "my_vpc" {
cidr_block = "10.0.0.0/16"
}

resource "aws_subnet" "my_subnet" {


vpc_id = aws_vpc.my_vpc.id # Cross-referencing VPC ID
cidr_block = "10.0.1.0/24"
}

18. What is String Interpolation in Terraform?

Ans ->
String interpolation in Terraform allows you to embed variables, resource attributes, or
expressions within strings using the ${} syntax. It dynamically constructs strings based
on values in your configuration.
Example:
resource "aws_vpc_security_group_ingress_rule" "myFirstSG_ipv4" {
security_group_id = aws_security_group.myFirstSG.id
ip_protocol = "tcp"
cidr_ipv4 = "${aws_eip.my_eip.public_ip}/32" # string interpolation used here
from_port = 80
to_port = 100
}
19. What are Output Values in Terraform?

Ans ->
Output values in Terraform allow you to display or export data from your Terraform
configuration, such as resource attributes or computed values, after running terraform
apply. These values are typically used to pass information between different
configurations, modules, or for visibility during deployment.
Key uses of output values:

 Display Information: Outputs can show important details like instance IPs or
IDs after infrastructure is created.
 Pass Data Between Modules: Outputs from one module can be referenced in
another module.
 Integration: Can be used in external scripts or CI/CD pipelines for automation.
output "instance_ip" {
value = aws_instance.my_instance.public_ip
}
In this example, the public IP of an EC2 instance is displayed as an output when
the infrastructure is applied.

In short, output values are a way to expose or share important data generated by
Terraform resources.
20. What are variables in Terraform?

Ans ->
In Terraform, variables allow you to make configurations more flexible and reusable by
defining dynamic values instead of hardcoding them. Variables can be used to input
data, customize infrastructure, and simplify managing environments.
Key Types of Variables:

 Input Variables: Allow users to pass values into the configuration.


 Local Variables: Store values that can be reused within the configuration.
 Output Variables: Display or export data from the configuration.

Input Variables:

You define variables in a variable block and reference them using ${var.<name>}.
variable "instance_type" {
default = "t2.micro"
}

resource "aws_instance" "example" {


ami = "ami-123456"
instance_type = var.instance_type # Using the variable
}
21. Explain about *.tfvars file in terraform.

Ans ->
A *.tfvars file in Terraform is used to define input variable values, allowing you to pass
values to variables without hardcoding them in the configuration files. It's typically
named terraform.tfvars but can have any name ending with .tfvars.

Note1: If the file name is terraform.tfvars => Terraform will automatically load values
from it during terraform apply
Note2: If the file name is different like prod.tfvars --> then we have to explicitly define
the file during plan/apply operations with the -var-file flag.
The command will look like: terraform apply -var-file="prod.tfvars"

This file helps manage different environments by separating variable values from the
infrastructure code, making configurations more flexible and maintainable.
22. What are the different ways of assigning values to variables in terraform?

Ans ->

In Terraform, there are several ways to assign values to variables:

Default Values: Set within the variable block in the configuration file.
variable "instance_type" {
default = "t2.micro"
}
Command-Line Flags: Use the -var flag to pass variables during execution.
terraform apply -var="instance_type=t2.medium"

*.tfvars Files: Define values in a file like terraform.tfvars or any file with .tfvars extension.

instance_type = "t2.medium"

Environment Variables: Prefix variable names with TF_VAR_name and set them in
the shell (for Linux based OS).
export TF_VAR_instance_type="t2.medium"
23. Explain about Variable Precedence in Terraform.

Ans ->

In Terraform, variable precedence determines which value is used when multiple


sources provide values for a variable. The order of precedence, from lowest to
highest, is:

1. Environment variables (TF_VAR_variable_name). (Lowest Precedence)


2. The terraform.tfvars file, if present.
3. The terraform.tfvars.json file, if present.
4. Any *.auto.tfvars or *.auto.tfvars.json files (processed in lexical order).
5. Command-line flags (-var and -var-file) (highest precedence).

In practice, values specified on the command line override everything else, while
environment variables are the lowest priority. This hierarchy ensures flexibility when
managing variables across different environments.
24. Explain about Data Types in Terraform.

Ans ->
In Terraform, data types define the kind of values that a variable, output, or resource
attribute can hold. These types help Terraform to enforce proper structure and
validation of data. The primary data types in Terraform are:

 String: Represents a sequence of characters.


 Example: "example-string"
 Number: Represents a numerical value (can be an integer or floating-point number).
 Example: 42, 3.14
 Bool: Represents a Boolean value (true or false).
 Example: true, false
 List: Represents an ordered collection of values of the same type.
 Example: ["apple", "banana", "cherry"]
 Set: Similar to a list but contains unique values, unordered.
 Example: toset([1, 2, 3])
 Map: Represents an unordered collection of key-value pairs (both key and value can
have different data types).
 Example: {"name" = "John", "age" = 30}
 Object: Represents a complex structure with named attributes. It is a collection of
other data types.
 Example:

object({
name = string
age = number
})
 Tuple: Represents an ordered collection of elements with potentially different data
types.
 Example: [42, "string", true]
 Any: A special type that can hold any value, useful when the exact type is not
known.
 Example: any = "some-value"

25. Explain about the count argument in Terraform.

Ans ->
In Terraform, the count argument allows you to create multiple instances of a resource
or module with a single configuration block. This is particularly useful for scaling
resources without duplicating code.

Key Points:

 count accepts an integer value, which determines how many instances of the
resource/module will be created.
 If count is set to 1, a single instance is created; if set to 0, no resource is
created.
 When count is greater than 1, Terraform generates multiple instances and
assigns each one an index starting from 0 (like an array).
 Example:
resource "aws_instance" "example" {
ami = "ami-123456"
instance_type = "t2.micro"
count = 3
}

In this example, three EC2 instances will be created, each with the same configuration. You
can access each instance using the index, like aws_instance.example[0],
aws_instance.example[1], and aws_instance.example[2].
26. Explain about terraform console command in Terraform.

Ans ->
The terraform console command is a tool that lets you test and explore Terraform code
interactively without making any real changes to your infrastructure.
Key Features:

 You can experiment with variables, functions, or other Terraform expressions


to see how they work.
 Check resource attributes (like instance IP addresses) or output values.
 Debug expressions by quickly seeing the result of what you're trying to do in
your configuration.
Example Usage:

$ terraform console

> var.my_variable

> aws_instance.example.public_ip

In this interactive shell, you can run Terraform expressions just as they would
appear in your configuration files, seeing the output immediately. It's especially
helpful for exploring and testing outputs, data sources, or evaluating conditions
during development.

27. Explain about functions in Terraform.

Ans ->
In Terraform, functions are built-in helpers that allow you to perform various operations
on your variables, resources, and data. They are used to manipulate data types,
generate dynamic values, and work with collections (like lists, maps, etc.).
Key Types of Functions:

1. String Functions: (e.g., concat, toupper, tolower, replace).


2. Numeric Functions: (e.g., floor, min, max, abs).
3. Collection Functions: (e.g., sort, length, lookup, merge).
4. Encoding Functions: (e.g., base64encode, base64decode).
5. Filesystem Functions: (e.g., file, filebase64).

Note: The Terraform language does not support user-defined functions, and so only
the functions built in to the language are available for use.
For more info check -> https://developer.hashicorp.com/terraform/language/functions

28. Demonstrate a few examples of functions in Terraform.

Ans ->

1. String Function Example: upper()

Converts a string to uppercase.


output "uppercase_name" {
value = upper("terraform")
}
# Output: "TERRAFORM"

2. Numeric Function Example: min()


Finds the minimum of two or more numbers.
output "smallest_value" {
value = min(3, 5, 7)
}
# Output: 3
3. Collection Function Example: length()
Gets the number of elements in a list.
variable "my_list" {
default = ["a", "b", "c"]
}

output "list_length" {
value = length(var.my_list)
}
# Output: 3
4. Filesystem Function Example: file()
Reads the contents of a file.
output "file_content" {
value = file("example.txt")
}
# Output: Contents of the file example.txt
29. Explain about locals in Terraform.

Ans ->
In Terraform, locals are internal variables that store values for reuse within a module,
simplifying configurations. They are useful for calculated values, repeated values, or
complex expressions, making the code more readable and DRY (Don't Repeat
Yourself). Unlike input variables, locals cannot be set or changed (immutable) by users
and are evaluated each time a plan is executed.

Example:
locals {
instance_type = "t2.micro"
environment = "dev"
name_tag = "${local.environment}-app"
}

resource "aws_instance" "example" {


ami = "ami-0614680123427b75e"
instance_type = local.instance_type

tags = {
Name = local.name_tag
}
}
Note: Local values are often referred to as just locals. Local valued created by a locals
block (plural), but you reference them as attributes on a object named local (singular)
30. When to Use Locals Over Variables?

Ans ->
1. Repeated Values: Use locals for values that are repeated throughout your
configuration to avoid duplication and make it easier to update the value in one
place. For example, reuse the same tag value or instance type across multiple
resources by using a local instead of repeating the value.
2. Derived or Calculated Values: If you need to calculate or derive a value from other
inputs (variables, resources, etc.), locals are useful. Example: Concatenating strings
for tags, or deriving a region from environment variables.
3. Simplifying Complex Expressions: For complex or repeated expressions, defining
them in a local block simplifies your configuration.
4. Intermediate Results: Locals can store intermediate results when breaking down
multi-step calculations.

Summary: Use locals for calculated, repeated, or internal module values. Use variables
for external input or to make your module flexible across environments.
31. Explain about Data Sources in Terraform.

Ans ->

In Terraform, a data source allows you to query and retrieve existing information from
external systems or providers (outside of Terraform) without creating or managing
resources.
Key Points:

 Read-Only: Data sources do not create or modify resources.


 Fetching Existing Information: Retrieve details of existing infrastructure (e.g.,
AMIs, VPCs) or external data (e.g., DNS records).
 Dynamic Reference: Reference data dynamically based on conditions (e.g.,
fetch the latest AMI ID).

Example with GitHub:


data "github_repositories" "example" {
query = "user:<your_github_username>"
include_repo_id = true
}

Explanation:

The data "github_repositories" data source is used to retrieve


information about the list of repositories available for the specified
GitHub user name.
Note: All these information will be saved on .tfstate file.
32. Explain about Terraform LOG with different verbosity.

Ans ->
Terraform logging provides valuable insights into the internal operations and debugging
details of Terraform commands. The logging levels (verbosity) allow you to control the
amount of information you see when troubleshooting issues or understanding Terraform
behavior.
Log Verbosity Levels (decreasing order):

TRACE: Most detailed; logs everything, including internal operations. Useful for
deep debugging.
 DEBUG: Less detailed than TRACE but still very verbose. Useful for
resource/module issues.
 INFO: Default level. Shows general actions Terraform performs (planning,
applying changes).
 WARN: Highlights warnings like deprecated features or potential issues.
 ERROR: Only logs errors during operations.
 OFF: Disables logging entirely.
33. How to set Terraform Logs and path?

Ans ->
To set LOG verbosity:

 For Windows, command => set TF_LOG=<verbosity_level> (e.g., TRACE, INFO)


 For Linux & Mac, command => export TF_LOG=<verbosity_level> (e.g., TRACE,
INFO)
To set LOG destination file:

 For Windows, command => set TF_LOG_PATH=<fileName or filePath> (where


the logs should be stored)
 For Linux & Mac, command => export TF_LOG_PATH=<fileName or filePath)>
(where the logs should be stored)
Note: These methods will persist only for the current session. If you open a new
command window, you'll need to set it again. And if you want it to be permanent then
you have to explicitly set these as environment variable.

34. Explain about terraform fmt command.

Ans ->
The terraform fmt command is used to automatically format Terraform configuration
files to follow standard conventions, ensuring consistent style across your code.
Example:
If you have a file main.tf with misaligned formatting:
resource "aws_instance" "example" {
ami= "ami-123456"
instance_type ="t2.micro"
}
Running terraform fmt will fix the formatting.

After running the command, the file will be properly formatted:


resource "aws_instance" "example" {
ami = "ami-123456"
instance_type = "t2.micro"
}
This helps maintain readability and consistency in your Terraform files.
35. Explain about Dynamic Blocks in Terraform.

Ans ->
In Terraform, dynamic blocks allow you to generate multiple nested blocks dynamically based
on a condition or list. This is useful when you need to create multiple resource configurations
that depend on variable input or when repeating blocks with different values. Dynamic blocks
help reduce duplication and make your Terraform code more flexible and reusable.

Key Concepts:

 for_each: Iterates over a collection (like a list or map).


 content: Defines the structure of the nested blocks being generated.

When to Use:

 When you need to generate multiple similar blocks dynamically based on variable input.
 To avoid duplication when multiple similar configurations are required.

Example:

variable "ports" {
default = [80, 443]
}

resource "aws_security_group" "example" {


name = "example-security-group"

dynamic "ingress" {
for_each = var.ports
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
}
Explanation:

 The dynamic "ingress" block generates multiple ingress rules based on the ports
variable.
 for_each loops over the list of ports (80, 443), and for each port, an ingress block
is created with the specified configuration.

Dynamic blocks simplify complex configurations by allowing flexible and reusable code.
36. Explain about terraform validate command.

Ans ->
The terraform validate command is used to check the syntax and validity of Terraform
configuration files (.tf files) in the current directory. It helps ensure that the Terraform
code is syntactically correct and that the configuration is logically sound before applying
any changes. However, it does not check if resources will be successfully created or
interact with cloud providers—it only validates the structure of the Terraform code.
Key Points:

 Syntax Check: Ensures that the Terraform code follows proper syntax.
 Configuration Validity: Checks for issues like missing required arguments,
invalid types, or conflicting configurations.
 No Cloud Interaction: It does not connect to any external APIs or services, so it
can't validate if the resources exist or can be created.
 Safe to Run: It doesn't make any changes to your infrastructure.

37. Explain about terraform taint command.

Ans ->
In Terraform, the terraform taint command is used to manually mark a resource as
"tainted," which signals that Terraform should destroy and recreate that resource during
the next apply operation. This can be useful if a resource has become corrupt, manually
misconfigured, or is in an undesirable state, and you want to force Terraform to re-
create it even if no configuration changes have occurred.
Syntax: terraform taint RESOURCE_NAME

Where RESOURCE_NAME is the address of the resource in the Terraform state (e.g.,
aws_instance.example).
Important Notes:
 Destructive: Tainting a resource forces its destruction, potentially causing
downtime, data loss, or other side effects, depending on the resource.
In summary terraform taint forces the recreation of resources in Terraform-managed
infrastructure, ensuring resources are in a known, healthy state.

38. Terraform taint update in newer Terraform version.

Ans ->

In newer versions of Terraform (starting with Terraform 0.15.2 and later), the
-replace option was introduced as a more intuitive alternative to the taint command. This
option provides a cleaner way to replace specific resources without needing to manually
mark them as tainted.
Key Points About terraform -replace:

 The -replace option allows you to specify that a resource should be replaced
during the next terraform apply, without the need for manually tainting it using
terraform taint.
 Usage: You use the -replace flag with the terraform apply command to trigger
the replacement of specific resources.
 Syntax: terraform apply -replace="RESOURCE_NAME", Where
RESOURCE_NAME is the resource that you want to replace (e.g.,
aws_instance.example).

39. Explain about the Splat Expression in Terraform.

Ans ->
In Terraform, the splat expression (*) is used to extract multiple values from a
collection (like a list or map) and return them as a new collection. It's commonly used
when you want to access all elements of a list or all values of a map, or when you need
to extract specific attributes from resources.
Usage with Lists: When used with a list, the splat expression extracts all elements
from the list.
resource "aws_security_group" "example" {
name = "example"
description = "Example security group"
}

output "security_group_ids" {
value = aws_security_group.example[*].id
}
This extracts the id attribute from all security group instances and returns them as a list.
40. Explain about terraform graph command.

Ans ->
In Terraform, the terraform graph command generates a visual representation of the
Terraform configuration and its resources as a directed acyclic graph (DAG). This graph
illustrates the relationships and dependencies between resources and modules in your
Terraform configuration.
Key Points About terraform graph:

Purpose:
 It helps visualize the relationships and dependencies between resources
defined in your Terraform configuration.
 The output is useful for understanding the structure of your infrastructure
and how resources depend on each other.
 Output Format: The terraform graph command produces a Graphviz-
compatible DOT format output. This format can be used with Graphviz tools to
create a graphical diagram of the infrastructure.
41. Workflow of terraform graph command.

Ans ->

How It Works:

 Terraform analyzes the dependencies between your resources (e.g., which


resources need to be created before others).
 It then generates a directed graph where nodes represent resources and edges
represent dependencies between them.
Using Graphviz: To visualize the graph, you can pipe the output of terraform graph
into Graphviz tools: terraform graph | dot -Tpng > graph.png

This command generates a PNG image (graph.png) representing the infrastructure’s


dependencies.

Note: In order to use the above command, we have to download the graphviz tool for
the respected OS systems (eg. windows, linux, mac). Then we can run the above
command through the CLI then the graph.png file will be created as a browser view.
42. Explain about plan file in Terraform.

Ans ->

In Terraform, a plan file is a saved output of the terraform plan command that
describes the actions Terraform will take to align your infrastructure with your
configuration. It contains a detailed, machine-readable representation of the proposed
changes to your infrastructure, including the creation, modification, and deletion of
resources.
Key Points About Terraform Plan File:

 A plan file is in a binary format (cannot be read directly by humans) generated by


running the terraform plan command with the -out flag.
 To see the file content, we need to run the command: terraform show
<plan_file_name>
 It records the actions Terraform will take to reach the desired state as described
in the Terraform configuration files (.tf files).

Example: terraform plan -out tfplan.plan

This creates a file named tfplan.plan that stores the planned changes.

43. What is the purpose of the plan file? and why to use it?

Ans ->

Purpose:

 Preview Changes: View what Terraform will create, update, or delete without
applying changes.
 Reproducibility: Ensure consistent, repeatable changes across environments or
teams.
 Safety: Avoid unintended changes by reviewing the plan before applying.

Why Use a Plan File?


Collaboration: Teams can share and apply the same plan file across different
environments.
 Automation: Useful in CI/CD pipelines to review plans before applying changes
automatically.
 State Consistency: Ensures predictable, consistent changes, especially in multi-
team environments.
44. A quick WorkFlow of plan file.

Ans ->
WorkFlow:

terraform plan -out <file_name>.plan -> this will create the plan file.

terraform show <plan_file_Name> -> this will show the plan file contents.

terraform apply <plan_file_name> -> this will apply the configuration according to the
plan file.
45. Explain about terraform output command.

Ans ->
The terraform output command is used to display the values of output variables in a
Terraform configuration. Output variables are defined in your Terraform configuration
files and are used to expose important information about your infrastructure after it has
been created or modified, such as resource IDs, IP addresses, or other data.
Key Points About terraform output:

 Purpose:
 To retrieve and display the values of output variables defined in your
Terraform configuration.
 It provides a way to view useful information about the infrastructure after a
terraform apply has been run.
 Basic Usage: After running terraform apply, the terraform output command can
be used to see the values of all or specific output variables defined in the
configuration.

terraform output <output_local_variable_name>

46. Explain about Terraform Settings with terraform {} block.

Ans ->
The terraform {} block in a Terraform configuration file is used to specify essential
settings and configurations for Terraform itself. This block defines important options like
the required Terraform version, backend configurations, and provider requirements.

Key Elements:

 Required Version: Specifies the minimum Terraform version needed.


terraform {
required_version = ">= 1.0.0"
}

 Required Providers: Lists providers and their versions.


terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 3.0"
}
}
}
 Backend Configuration: Defines where to store the state (e.g., S3).

terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "path/to/my/statefile"
region = "us-west-2"
}
}

47. Explain about Resource Targeting in Terraform.

Ans ->

Resource targeting in Terraform allows you to apply or plan changes only for specific
resources rather than the entire configuration. It's useful for making changes to a subset
of resources without affecting others.
How to Use:
1. Targeting Specific Resources: You can use the -target flag to specify which
resources to apply or plan. For example: terraform apply -target
aws_instance.my_instance

This applies changes only to the aws_instance.my_instance resource.

2. Multiple Targets: You can target multiple resources by using the -target flag
multiple times:
terraform plan -target aws_instance.my_instance -target aws_s3_bucket.my_bucket
Caution! : Targeting individual resources can be useful for troubleshooting errors, but
should not be part of your normal workflow, it can lead to dependency issues or partial
infrastructure updates. It’s generally better to apply changes to the entire configuration.

48. When to use Resource Targeting in Terraform?

Ans ->

 Quick updates: When you need to apply changes to a specific resource without
affecting the entire infrastructure.
 Troubleshooting: For debugging or resolving issues with a particular resource.
 Partial deployments: When testing new configurations or updating only part of your
infrastructure.
Avoid downtime: To minimize impact by applying changes to essential resources
without affecting the rest.
 Resource isolation: For focusing on a resource without running unnecessary
updates on unrelated components.
49. Explain about Zipmap in Terraform.

Ans ->
In Terraform, zipmap is a function that creates a map (or dictionary) by combining two
lists: one list of keys and one list of values. It associates each element from the first list
(keys) with the corresponding element in the second list (values), effectively mapping
them together.
Syntax: zipmap(keys, values)

The function assumes that the two lists (keys and values) are of equal length. If they are
not, Terraform will return an error.

Example:
locals {
keys = ["a", "b", "c"]
values = [1, 2, 3]
}

output "zipmap_example" {
value = zipmap(local.keys, local.values)
}
Result:
zipmap_example = {
"a" = 1
"b" = 2
"c" = 3
}
In this case, the zipmap function combines the two lists:
 Keys: ["a", "b", "c"]
 Values: [1, 2, 3]
And creates a map where each key is paired with the corresponding value.

50. How to change the default behavior of terraform apply?


Example: Some modification happened in Real Infrastructure object manually that is not
part of Terraform, but you want to ignore those changes during terraform apply. How to
achieve this requirement?

Ans ->

To ignore manual changes during terraform apply, use the ignore_changes argument
within the lifecycle block. This allows you to specify which resource attributes should not
be modified by Terraform, even if they were changed manually outside of Terraform.
Example:
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"

tags = {
Name = "MyInstance"
}

lifecycle {
ignore_changes = [
tags, # Ignore changes to tags
instance_type # Ignore changes to instance_type
]
}
}

How it works:

 Terraform will ignore changes to the specified attributes (e.g., tags,


instance_type) during terraform apply.
 Other attributes will still be managed by Terraform.

Use this to avoid Terraform overwriting manual changes made outside of its control.

51. Explain about Meta-Arguments in Terraform with Examples.

Ans ->
In Terraform, meta-arguments are special arguments that can be used within a
resource, module, or data block to control the behavior of the configuration. These
arguments are not specific to any individual resource but apply to various aspects of
Terraform’s operations, such as lifecycle, dependencies, and execution order.
Meta-arguments provide additional functionality and flexibility in how resources and
modules are managed. They help Terraform manage resources in a more efficient and
predictable way.

Key Meta-Arguments in Terraform:

1. depends_on => Explicitly specifies the dependency between resources,


modules, or data sources.
2. count => Creates multiple instances of a resource based on a count value.
3. for_each => Creates multiple instances of a resource based on a collection (e.g.,
a map or list).
4. lifecycle => Configures lifecycle behavior of resources, such as how Terraform
handles creation, updates, and destruction.
5. provider => Specifies the provider for a resource or module.
6. alias => Defines an alias for a provider.
7. terraform (for required_providers and required_version) => Configures
Terraform-level settings, such as provider requirements and version constraints.

52. What are the different types of argument available for lifecycle {} block? explain in brief
about them.

Ans ->

There are four arguments available within lifecycle {} block:

create_before_destroy => New replacement object is created first, and the prior object
is destroyed after the replacement is created.
prevent_destroy => Terraform to reject with an error any plan that would destroy the
infrastructure object associated with the resource.

ignore_changes => Ignore certain changes to the live resource that does not match
the configuration.
replace_triggered_by => Replaces the resource when any of the referenced items
change

53. Explain about create_before_destroy argument of lifecycle block with an example.

Ans ->
The create_before_destroy argument is part of the lifecycle block in Terraform, and it
controls the order in which resources are created and destroyed during changes to your
infrastructure.
When create_before_destroy = true is set, Terraform will create a new resource
before it destroys the old one. This is particularly useful when updating resources where
you don't want downtime (i.e., you want the new resource to be ready before the old
one is removed).

Example:
resource "aws_instance" "example" {
ami = "ami-123456"
instance_type = "t2.micro"

lifecycle {
create_before_destroy = true
}
}
Here:
If you change the ami or instance_type, Terraform will first create a new EC2
instance with the updated configuration.
 After the new instance is successfully created, it will destroy the old one,
minimizing downtime.
54. Explain about prevent_destroy argument in lifecycle block.

Ans ->
The prevent_destroy argument is part of the lifecycle block in Terraform. When set to
true, it prevents Terraform from destroying the resource, even if the resource is marked
for destruction during a terraform destroy or terraform apply operation. This is useful for
protecting critical resources from accidental deletion.
Example:
resource "aws_s3_bucket" "example" {
bucket = "my-unique-bucket-name"

lifecycle {
prevent_destroy = true
}
}

 The aws_s3_bucket resource is protected from being destroyed.


 If someone tries to run terraform destroy or modify the configuration in a way that
would lead to the destruction of the S3 bucket, Terraform will raise an error and
prevent the deletion.

This is useful for important resources that should not be deleted unintentionally, such as
production databases or critical infrastructure.
55. What does ignore_changes = all will do inside lifecycle block?

Ans ->
The ignore_changes = all argument in a Terraform lifecycle block tells Terraform to
ignore any changes to the resource's attributes. It prevents Terraform from updating the
resource, even if the resource’s configuration changes.

Example:
resource "aws_s3_bucket" "example" {
bucket = "my-unique-bucket-name"

lifecycle {
ignore_changes = all
}
}
In this example, Terraform will ignore any changes to aws_s3_bucket.example
resource, even if its attributes (like bucket name) change. This is useful when you want
to avoid Terraform modifying a resource based on external changes.

56. Explain about set data type in Terraform.

Ans ->

In Terraform, the set data type is a collection type that represents a unique unordered
collection of values. It is similar to a list, but unlike lists, a set automatically removes any
duplicate values. The set type is useful when you want to ensure that there are no
duplicates in your data and when the order of the values does not matter.
Key Features:

 Unique Values: Duplicates are automatically removed.


 Unordered: The order of elements is not guaranteed.
 Dynamic Length: The number of elements can vary depending on input.

A set is defined in Terraform using the set() function or as a type in variable definitions
or resource configurations.

Example:
variable "example_set" {
type = set(string) # A set of strings
default = ["a", "b", "c"]
}
This variable is of type set(string), meaning it will hold a set of string values. The set will
automatically remove duplicates if they are added.

57. State the differences between set and list data types in Terraform.

Ans ->
Uniqueness:

 Set: Automatically removes duplicate values; only unique elements are stored.
 List: Allows duplicates; elements can repeat.

Order:

 Set: Unordered; the order of elements is not guaranteed.


 List: Ordered; the order of elements is preserved.

Indexing:

 Set: Does not support indexing or accessing elements by position.


 List: Supports indexing; elements can be accessed by position.
Use Case:
 Set: Used when uniqueness matters and order is not important.
 List: Used when both order and possible duplicates matter.

Dynamic Length:

 Both sets and lists can dynamically grow or shrink based on input.
58. Explain about for_each meta-argument in Terraform.

Ans ->

The for_each meta-argument in Terraform allows you to create multiple instances of a


resource or module based on a map or set of values. It iterates over the provided
collection and applies the resource configuration for each item in that collection. This is
useful when you need to create multiple similar resources with slightly different
configurations.
Key Points:

Iterates over a map or set: for_each can be used with both maps and sets.
Creates multiple instances: It creates a resource instance for each element in
the collection.
 Uses the item value: You can reference the current item within the resource
block using each.value for set data type and for the map data type, to read the
keys you can use each.key and for associated values you can use each.value
59. Give an example of for_each meta-argument with set data type.

Ans ->
variable "sg_names" {
type = set(string)
default = ["sg-web", "sg-db"]
}

resource "aws_security_group" "example" {


for_each = var.sg_names

name = each.value
description = "Security group for ${each.value}"
}

Explanation:

 The for_each iterates over the sg_names set.


 It creates two AWS security groups, one for sg-web and another for sg-db, using
the values from the set.
 each.value is used to reference the current security group name in the resource
block.
60. Give an example of for_each meta-argument with map data type.

Ans ->
variable "mymap" {
default = {
dev = "ami-123"
prod = "ami-456"
}
}

resource "aws_instance" "web" {


for_each = var.mymap
ami = each.value
instance_type = "t2.micro"

tags = {
Name = each.key
}
}

61. State the differences between for_each and count meta-arugment.

Ans ->
Iteration Type:

 for_each: Iterates over a map or set, creating resources with access to both key
and value.
 count: Iterates over a fixed number, creating identical resources.

Uniqueness:

 for_each: Creates resources with different configurations.


 count: Creates identical resources.

Indexing:

 for_each: Uses each.key (key) and each.value (value).


 count: Uses count.index for indexing.

Use Case:

 for_each: Ideal for dynamic or unique resource configurations.


 count: Best for creating a fixed number of identical resources.

Upside:

 for_each: Flexible for varied configurations.


 count: Simple for identical resources.
Downside:

 for_each: More complex with large maps.


 count: Less flexible for varied configurations.

62. Explain about Provisioners in Terraform.

Ans ->

In Terraform, provisioners are used to execute scripts or commands on a local or


remote machine after a resource is created or updated. They act as a bridge between
resource creation and configuration.
Key points:

 Provisioners help in bootstrapping instances or resources by running shell


commands, installing software, or configuring services.
 They are executed after the resource is provisioned and are primarily used for
customization.
 Common provisioners include local-exec (for running commands on the local
machine) and remote-exec (for running commands on remote machines, like
EC2 instances).
 Use cautiously: Terraform is declarative, so excessive use of provisioners can
lead to non-idempotent configurations.

Provisioners should be used as a last resort, especially when proper cloud-native


methods are not available.

63. Explain about the local-exec provisioner in Terraform with an example.

Ans ->
The local-exec provisioner in Terraform allows you to run local commands on the
machine where Terraform is being executed. It's useful for tasks like running scripts,
triggering notifications, or interacting with external systems after creating or updating a
resource.
Example:
resource "aws_instance" "example" {
ami = "ami-0614680123427b75e"
instance_type = "t2.micro"

provisioner "local-exec" {
command = "echo 'Instance created: ${self.id}'"
}
}
In this example, after the EC2 instance is created, the local-exec provisioner runs a
local command that prints the instance ID.
64. Explain about the remote-exec provisioner in Terraform.

Ans ->
The remote-exec provisioner in Terraform allows you to run commands on a remote
machine (such as an EC2 instance) after it's created. It connects to the machine using
SSH or WinRM (for Windows), and is Useful for tasks like installing software,
configuring services, or running custom scripts.
Example:
resource "aws_instance" "example" {
ami = "ami-0614680123427b75e"
instance_type = "t2.micro"

connection {
type = "ssh"
user = "ubuntu"
private_key = file("path_to_private_key_file")
host = self.public_ip
}

provisioner "remote-exec" {
inline = [
"sudo apt-get update",
"sudo apt-get install -y nginx"
]
}
}

In this example, once the EC2 instance is up, the remote-exec provisioner connects via
SSH and installs NGINX on the instance.
65. Differences between the local-exec and remote-exec provisioners in Terraform.

Ans ->

the differences between local-exec and remote-exec provisioners in Terraform:

local-exec:

 Runs commands on your local machine (where Terraform is being run).


 Useful for tasks like triggering scripts, sending notifications, or interacting with
external systems from your own environment.
 Example: Running a local script to notify a system that the infrastructure is
deployed.
remote-exec:

 Runs commands on the remote resource (like a virtual machine or instance


you've just created).
 Requires you to connect (usually via SSH or WinRM) to the resource and
execute commands directly on it.
 Example: Installing software or configuring the system on an EC2 instance after
it’s created.

In short:

 local-exec runs on your machine,


 remote-exec runs on the remote machine you just created.

66. Explain about Creation & Destroy time provisioners in Terraform.

Ans ->
In Terraform, creation-time and destroy-time provisioners define when provisioners
should run:
Creation-Time Provisioners: Run after the resource is created. These kind of
provisioners are only run during creation, not during updating or any other lifecycle.
They are used to set up or configure the resource (e.g., installing software on an EC2
instance).

Destroy-Time Provisioners: Run before the resource is being destroyed. They are
useful for cleanup tasks, like deregistering the resource from external systems, remove
and De-Link Anti-Virus software before EC2 gets terminated.

To specify a destroy-time provisioner, you use the when = destroy argument. By default,
provisioners are creation-time.
Example:

resource "aws_iam_user" "example_user" {


name = "provisioner-user"

provisioner "local-exec" {
command = "echo This is creation time provisioner"
}

provisioner "local-exec" {
command = "echo This is destroy time provisioner"
when = destroy
}
}
In the above terraform code, a IAM user is created and in the same block the creation
time and the destroy time provisioners are defined.
 Creation time provisioner will run at the time of the resource creation
 Destroy time provisioner will run at the time of resource destruction.

67. An important point about the Creation-time provisioner.

Ans ->

 If a creation-time provisioner fails, the resource is marked as tainted.


 A tainted resource will be planned for destruction and recreation upon the next
terraform apply.
 Terraform does this because a failed provisioner can leave a resource in a semi-
configured state.

How to deal with this default behavior:


In Terraform, adding on_failure = continue inside a provisioner block tells
Terraform to continue the resource creation or destruction process even if the
provisioner command fails.

Normally, a failed provisioner would halt the process and tainted the
corresponding resource, but with this option, Terraform proceeds regardless of
the failure and the resource is successfully created or destroyed.

Example:
resource "aws_iam_user" "lb" {
name = "demo-provisioner-user"

provisioner "local-exec" {
command = "echo1 This is creation time provisioner"
on_failure = continue
}
}

68. Explain about Terraform Modules.

Ans ->

Terraform modules are reusable, self-contained configurations that can be used to


organize and manage infrastructure code more effectively. A module typically consists of
a set of ‘.tf’ files that define resources, input variables, outputs, and optionally, other
nested modules.
 Reusability: Modules allow you to define a set of resources once and reuse them
across different parts of your infrastructure or across different projects.
 Encapsulation: They help encapsulate complex logic into a single package,
improving readability and maintainability of Terraform configurations.
 Input and Output Variables: Modules use input variables to receive values and
output variables to return results (like resource IDs).
 Root Module: The default module, where Terraform runs by default (usually the
current directory).
 Community Modules: Terraform’s public registry has a large collection of pre-
built modules for various cloud providers and services.

69. Give an example of Terraform Module.

Ans ->
module "ec2-instance" {
source = "terraform-aws-modules/ec2-instance/aws"
version = "5.7.1"
}

The code defines a Terraform module named ec2-instance that uses the terraform-aws-
modules/ec2-instance/aws module from the Terraform Registry.

 source specifies the location of the module (the EC2 instance module on AWS).
 version locks the module to version 5.7.1 for stability.

This module is used to create and manage an EC2 instance on AWS, with additional
configuration options passed to customize the instance.

Note: After declaring the module, before running the terraform plan or terraform
apply command we need to run the terraform init command, this will download the
module and initialize your working directory.

70. Explain about Module Outputs in Terraform.

Ans ->
In Terraform, module outputs allow data to be exposed from one module to another, or
to the root module. These outputs can be used to pass values between modules or
display information after an operation (like terraform apply).

Syntax: module.<Module_Name>.<Output_Name>

Key Points:

 Outputs are defined using the output block.


 They allow you to export information from a module that can be referenced in
other parts of the configuration.
 Outputs can be displayed to the user or passed to other modules.

Example:
This code is the content of the file named instance-module
resource "aws_instance" "example" {
ami = "ami-123456"
instance_type = "t2.micro"
}

output "instance_id" {
value = aws_instance.example.id
}
Instance-module is used here:
module "my_instance" {
source = "./instance-module" # path to the module
}

resource "aws_eip" "myEIP" {


instance = module.my_instance.instance_id
domain = "vpc"
}
In the above example, the configuration creates an EC2 instance in a module, exports
its ID, and uses that ID to attach an Elastic IP (EIP) to the instance in the main
configuration.
71. Explain about root and child modules in Terraform.

Ans ->
root module is the main configuration located in the root directory, where Terraform
starts execution. It includes files like main.tf, variables.tf, and outputs.tf, and is the entry
point when running Terraform commands like plan or apply.
Child modules are reusable modules stored in separate directories. They perform
specific tasks, such as creating resources or managing infrastructure components. The
root or other modules can call child modules, passing input variables and using their
outputs to simplify and organize the Terraform code.
72. Define the minimal recommended module structure in Terraform.

Ans ->
A minimal Terraform module typically includes the following files:

main.tf: Contains the core configuration, defining resources and data sources.

variables.tf (optional but recommended): Defines input variables for customization.

outputs.tf (optional but recommended): Specifies outputs that the module returns.

Although not required for functionality, a README.md file is recommended for


documentation. It explains the module's purpose, usage, and details about input
variables and outputs.

A basic module structure might look like this:


/my-module
├── main.tf
├── variables.tf
├── outputs.tf
└── README.md (recommended)

73. What are the requirements for publishing modules in Terraform Registry?

Ans ->

74. Explain about Workspaces in Terraform.

Ans ->

A Terraform workspace is an isolated environment used to manage separate


infrastructure states. It allows you to maintain different configurations (e.g., dev, staging,
prod) within a single project. Each workspace has its own state file, enabling
environment separation.
Key features:

 State isolation: Each workspace maintains its own separate state.


 Environment separation: Useful for managing different environments (e.g., dev,
staging, prod).
 Same configuration, different states: You can apply the same configuration
but with different resource values based on the workspace.
Commands:

 terraform workspace new <workspace_name> – Create a new workspace.


 terraform workspace select <workspace_name> – Switch to a different
workspace.
 terraform workspace list – List all available workspaces.
 terraform workspace delete <workspace_name> - Delete a workspace

Workspaces provide a lightweight mechanism for managing multiple configurations


without requiring separate directories or projects.
75. Explain about Terraform Backends.

Ans ->

A Terraform Backend is a configuration that defines where Terraform's state files are
stored. The state file is essential for Terraform to track the resources it manages, and
the backend determines both the storage and how Terraform interacts with it.

There are two main types of backends:

 Local Backend: The default backend, where the state file is stored locally on the
system where Terraform is run (e.g., terraform.tfstate).

 Remote Backend: The state file is stored in a remote system, like AWS S3, Azure
Blob Storage, or HashiCorp Consul, which helps in team collaboration and
ensures that the state is consistent across different users and systems. Remote
backends also often support state locking to prevent conflicts.

76. What are the advantages of using Terraform Backends?

Ans ->

Using a backend has several advantages:

 State management: Centralized state storage allows for safer collaboration.


 Security: Sensitive information in the state can be encrypted.
 Remote locking: Helps prevent concurrent modifications to the state.
 Some of the popular backend includes: S3, Consul, Azurerm, Kubernetes,
HTTP, ETCD
Following describes one of the recommended architectures:

1. The Terraform Code is stored in Git Repository.


2. The State file is stored in a Central backend.

77. Explain about state lock in Terraform.

Ans ->

In Terraform, a state lock is a mechanism used to prevent concurrent modifications to


the state file, which is critical for managing the infrastructure's current state. The state
file (terraform.tfstate) tracks the resources Terraform manages, and any changes to it
must be done carefully to avoid inconsistencies or corruption.

When Terraform performs actions (e.g., apply, plan, refresh), it locks the state to
ensure that only one operation is modifying the state at a time This lock is especially
important in collaborative or automated environments, like when using remote backends
(e.g., Amazon S3, Azure Storage, etc.).
The lock ensures that:

1. No other Terraform process can alter the state concurrently.


2. State consistency is maintained across different runs.

If an operation is already holding a lock, other Terraform commands will wait for the lock
to be released before proceeding.

78. Explain about Force-Unlock State in Terraform.

Ans ->
In Terraform, the force-unlock command is used to manually release a state lock when
it is stuck or not automatically cleared after an interrupted operation. This happens
when a process (e.g., terraform apply) is stopped abruptly, leaving the state file locked.

Syntax: terraform force-unlock <LOCK_ID>

Where <LOCK_ID> is the ID of the lock, which Terraform provides in the error message
when you try to run a command while the state is locked.
Caution: Use this command carefully, as unlocking the state while it's still in use can
cause state corruption. Only force-unlock if you're sure no other process is using the
state.

79. Explain about different types State Management terraform state commands.

Ans ->

 terraform state list:


 Lists all resources tracked in the current state.
 Use case: When you want to see the list of all resources managed by
Terraform.
 terraform state show <resource>:
 Shows details about a specific resource in the state file.
 Use case: To inspect a resource's attributes (like IDs, tags, etc.) that
Terraform manages.
 terraform state mv <source> <destination>:
 Moves a resource from one address to another.
 Use case: Helpful during refactoring or renaming resources without
recreating them.
 terraform state rm <resource>:
 Removes a resource from the state without affecting actual infrastructure.
 Use case: When you no longer want Terraform to manage a resource but
don't want to delete it.
 terraform state pull:
 Downloads and displays the current state from a remote or local backend.
 Use case: To view the most recent state file from remote backends like S3 or
Consul.
 terraform state push:
 Uploads a local state file to a remote backend.
 Use case: When you need to manually sync the local state with the remote
backend.
 terraform state replace-provider <source> <destination>:
 Replaces one provider with another in the state file.
 Use case: Useful when migrating resources between providers, such as from
AWS to Azure.

80. Explain about terraform import command.

Ans ->
The terraform import command allows you to import existing resources that were
created outside of Terraform (manually or by other tools) into your Terraform state file.
And starting from Terraform 1.5, you can generate configuration files (.tf) while
importing a resource. This simplifies importing resources and managing them through
Terraform as the .tf file is automatically generated for you.

Example:

At first we have to create a new .tf file and then have to write the below code
import {
to = aws_instance.importedEc2 // this is resource name
id = "i-020b9b253f2e24d40" // this is resource ID
}

Then from terminal we have to run the below command:

terraform import -generate-config-out=<new_tf_file_name>


This will:

Automatically generate the .tf configuration file (<new_tf_file_name>.tf) for the


imported resource.
81. Explain about Multiple Provider Configuration in Terraform.

Ans ->

Multi-provider configuration in Terraform allows you to manage resources across


multiple cloud providers or services in a single configuration. It enables you to define
and interact with resources from different platforms like AWS, Azure, Google Cloud,
etc., in one Terraform project.
Key Points:

 Multiple Providers: You can use multiple providers in one configuration by


defining multiple provider blocks, each specifying different platforms.
 Alias: Use the alias argument to define multiple configurations for the same
provider or different regions within the same provider.
 Example: Manage AWS and Google Cloud resources in the same project, or use
different AWS regions for different resources.

Example Code:
provider "aws" {
alias = "singapore"
region = "ap-southeast-1"
}

provider "aws" {
alias = "usa"
region = "us-east-1"
}

resource "aws_security_group" "sg_1" {


name = "prod_firewall"
provider = aws.usa
}

resource "aws_security_group" "sg_2" {


name = "staging_firewall"
provider = aws.singapore
}

Here in the above code:

Provider Aliasing: The alias argument allows managing resources in multiple regions
by referring to them using the provider attribute in each resource.
Cross-Region Management: This configuration manages security groups in different
AWS regions (USA and Singapore) using different provider blocks.

82. Explain about Sensitive Parameter in Terraform.

Ans ->
In Terraform, the sensitive parameter is used to mark specific values or outputs as
sensitive, meaning they should be treated with care to avoid accidental exposure.

Here's a brief overview:

 Purpose: Prevent sensitive data (like passwords, API keys, or secrets) from being
shown in CLI output, logs, or other places where they might be visible (excluding
state file).
 Usage: Can be applied to resource arguments or outputs using sensitive = true.
 Behavior: When marked as sensitive, the value is hidden in Terraform outputs and
logs, showing as *** or as (sensitive value) instead of the actual value.
 Example:
resource "aws_secretsmanager_secret_version" "example" {
secret_id = aws_secretsmanager_secret.example.id
secret_string = "my-super-secret-password"
sensitive = true
}

output "secret_value" {
value = aws_secretsmanager_secret_version.example.secret_string
sensitive = true
}
83. Explain about Sentinel in Terraform.

Ans ->
Sentinel in Terraform is a policy-as-code framework used to enforce governance and
compliance on your infrastructure. Integrated with Terraform Cloud/Enterprise, it allows
you to define rules (written in the Sentinel language) that validate Terraform
configurations before deployment.
Key features:

 Policy Enforcement: Ensures infrastructure meets security, compliance, and


operational standards.
 Custom Policies: Allows you to write custom rules (e.g., restricting resources or
ensuring cost control).
 Compliance Checks: Prevents Terraform apply if a policy is violated.

Sentinel helps automate compliance and governance in Terraform workflows, ensuring


infrastructure is consistent, secure, and cost-effective.
84. Explain about Air Gapped environments in the context of terraform.

Ans ->
An air-gapped environment refers to a network that is physically isolated from external
networks (like the internet), often for security or compliance reasons. In the context of
Terraform, this means working offline without relying on external resources.

Key Points:

 Manual Management: Providers, modules, and state files must be stored and
managed locally.
 Private Backends: You may use internal systems (e.g., private S3 buckets) for
storing state.
 Version Control: Terraform resources are managed through internal
repositories.
 Security: Common in sensitive environments where external access is
restricted.

Terraform in air-gapped environments requires extra setup but ensures high security.
85. What are the use cases of Air Gapped Systems?

Ans ->

Air Gapped Environments are used in various areas. Some of these include:

 Military/governmental computer networks/systems


 Financial computer systems, such as stock exchanges
 Industrial control systems, such as SCADA in Oil & Gas fields

You might also like