Terraform Notes-1-1
Terraform Notes-1-1
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.
Ans ->
In Terraform, the provider block specifies the platform (like AWS, Azure, GCP) that
Terraform will interact with. It handles:
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"
}
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.
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:
Verified/Partner Providers:
Community Providers:
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:
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.
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:
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.
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 ->
Example:
provider "aws" {
region = "us-west-2"
version = "~> 3.50" # Ensures use of AWS provider versions from 3.50.x to
below 4.0
}
Ans ->
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.
Ans ->
Example:
resource "aws_vpc" "my_vpc" {
cidr_block = "10.0.0.0/16"
}
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:
You define variables in a variable block and reference them using ${var.<name>}.
variable "instance_type" {
default = "t2.micro"
}
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 ->
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 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:
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"
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:
$ 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.
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:
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
Ans ->
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"
}
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:
Explanation:
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:
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.
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:
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]
}
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.
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.
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).
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:
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:
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.
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.
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:
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "path/to/my/statefile"
region = "us-west-2"
}
}
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
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.
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.
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:
Use this to avoid Terraform overwriting manual changes made outside of its control.
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.
52. What are the different types of argument available for lifecycle {} block? explain in brief
about them.
Ans ->
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
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
}
}
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.
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:
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:
Indexing:
Dynamic Length:
Both sets and lists can dynamically grow or shrink based on input.
58. Explain about for_each meta-argument in Terraform.
Ans ->
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"]
}
name = each.value
description = "Security group for ${each.value}"
}
Explanation:
Ans ->
variable "mymap" {
default = {
dev = "ami-123"
prod = "ami-456"
}
}
tags = {
Name = each.key
}
}
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:
Indexing:
Use Case:
Upside:
Ans ->
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 ->
local-exec:
In short:
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:
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.
Ans ->
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
}
}
Ans ->
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.
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:
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
}
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.
outputs.tf (optional but recommended): Specifies outputs that the module returns.
73. What are the requirements for publishing modules in Terraform Registry?
Ans ->
Ans ->
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.
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.
Ans ->
Ans ->
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:
If an operation is already holding a lock, other Terraform commands will wait for the lock
to be released before proceeding.
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.
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 ->
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
}
Ans ->
Example Code:
provider "aws" {
alias = "singapore"
region = "ap-southeast-1"
}
provider "aws" {
alias = "usa"
region = "us-east-1"
}
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.
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.
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:
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: