Terraform
Terraform
Interview Questions
1. What is Terraform?
Answer: Terraform works by using configuration files written in HashiCorp Configuration Language
(HCL) or JSON to define the desired state of infrastructure. It performs the following steps:
Initialize: Use terraform init to initialize the working directory and download the necessary providers.
Plan: Use terraform plan to create an execution plan, showing changes required to achieve the
desired state.
Apply: Use terraform apply to execute the changes and provision or update infrastructure.
Destroy: Use terraform destroy to tear down the infrastructure managed by Terraform.
Answer: Providers are plugins that Terraform uses to interact with cloud platforms, SaaS providers, or
other APIs. Each provider defines the resources and data sources available for use in Terraform
configurations. Examples include AWS, Azure, Google Cloud, and Kubernetes providers.
Answer: A Terraform module is a container for multiple resources that are used together. Modules
help organize and reuse configurations. They can be defined locally within a Terraform configuration
or retrieved from the Terraform Registry or other sources.
Answer: The terraform init command initializes a Terraform working directory. It downloads and
installs provider plugins, initializes the backend configuration, and sets up the directory for use with
other Terraform commands.
6. How do you manage state in Terraform?
Answer: Terraform manages state through a state file (terraform.tfstate) that records the current
state of the infrastructure. The state file is crucial for tracking changes and ensuring that Terraform
can accurately update or destroy resources. Remote state storage options include AWS S3, Azure
Blob Storage, and Terraform Cloud.
Answer: The terraform plan command creates an execution plan that shows what changes will be
made to the infrastructure based on the current state and the configuration files. It helps users
review and confirm changes before applying them.
Answer: Terraform workspaces allow you to manage multiple environments (e.g., development,
staging, production) within the same configuration. Each workspace has its own state file and
configuration, enabling isolated infrastructure management.
Answer: Terraform automatically manages dependencies between resources based on the references
and relationships defined in the configuration files. It determines the correct order of resource
creation and updates to ensure that dependencies are satisfied.
Answer: The terraform apply command applies the changes required to reach the desired state of
the infrastructure, as defined in the configuration files. It executes the actions necessary to create,
update, or destroy resources.
Answer: A Terraform variable is a parameter that can be used to customize configurations. Variables
are defined in a variables.tf file and can be assigned values through variable files, environment
variables, or directly in the configuration.
variable "region" {
type = string
default = "us-east-1"
}
12. What is a Terraform output?
Answer: Outputs in Terraform are used to return information about the resources created or
managed by Terraform. They are defined in the configuration and can be accessed after terraform
apply to obtain useful information such as resource IDs or IP addresses.
output "instance_ip" {
value = aws_instance.my_instance.public_ip
Answer: A provider block in Terraform specifies the provider being used and its configuration. It is
where you define credentials, region, and other settings required for Terraform to interact with the
provider.
provider "aws" {
region = "us-east-1"
Answer: Data sources in Terraform allow you to retrieve and use information from existing resources
or services. They are useful for querying data that is not managed by Terraform but needed for
configuration.
most_recent = true
owners = ["amazon"]
variable "db_password" {
type = string
sensitive = true
}
16. What are Terraform resource blocks?
Answer: Resource blocks in Terraform define individual resources to be managed, such as virtual
machines, storage, or databases. They specify the resource type and its configuration.
ami = "ami-123456"
instance_type = "t2.micro"
Answer:
Modules are used to encapsulate and reuse Terraform configurations. You can create modules by
defining a directory with main.tf, variables.tf, and outputs.tf, and then use them in other
configurations.
module "network" {
source = "./modules/network"
cidr = "10.0.0.0/16"
Answer:
The Terraform Registry is a repository of publicly available Terraform modules and providers. It allows
users to find, share, and reuse modules and providers. The registry can be accessed at
registry.terraform.io.
Answer:
Terraform handles resource changes by using the state file to compare the current infrastructure
with the desired state defined in the configuration. Changes are identified during the terraform plan
phase and applied during terraform apply.
Answer:
The terraform refresh command updates the state file with the latest information from the
infrastructure. It synchronizes the state file with the actual state of the resources.
21. How do you perform a rolling update with Terraform?
Answer:
Rolling updates can be performed using Terraform by managing resource dependencies and
leveraging features like count and depends_on to ensure proper update sequences. For instance,
updating instances while ensuring that a minimum number of instances are available during the
process.
Answer:
Secrets and credentials should be managed securely using environment variables, Terraform Vault, or
other secret management tools. Avoid hardcoding sensitive information directly in configuration
files.
Answer:
The terraform fmt command formats Terraform configuration files to ensure consistent style and
readability. It helps to maintain code quality and conformity to HCL syntax standards.
Answer:
The terraform state file (terraform.tfstate) records the current state of the infrastructure managed by
Terraform. It maps the resources defined in the configuration to real-world resources and tracks
changes.
Answer:
26. What are terraform taint and terraform untaint used for?
Answer:
The terraform taint command marks a resource for recreation on the next terraform apply. The
terraform untaint command removes the taint mark, preventing the resource from being recreated.
27. What is the terraform destroy command used for?
Answer:
The terraform destroy command is used to delete all resources defined in the Terraform
configuration. It removes infrastructure and resources managed by Terraform, based on the current
state.
Answer:
The count parameter allows creating multiple instances of a resource. It can be used to scale
resources dynamically based on conditions or input variables.
count = 3
ami = "ami-123456"
Answer:
The terraform import command imports existing infrastructure into Terraform management. It allows
Terraform to create a state file entry for a resource that was created outside of Terraform.
Answer: An output variable in Terraform is used to extract and display information about resources
created or managed by Terraform. It can be used to pass information to other configurations or
modules.
output "instance_ip" {
value = aws_instance.my_instance.public_ip
Answer: Provisioners in Terraform are used to execute scripts or commands on resources after they
are created. They can be used for configuration tasks like installing software or performing custom
setup.
32. How do you use Terraform to manage resources across multiple cloud providers?
Answer: Terraform supports multiple cloud providers by defining separate provider blocks for each
provider in the configuration. Resources from different providers can be managed in a single
configuration file.
provider "aws" {
region = "us-east-1"
provider "azurerm" {
features {}
Answer: A Terraform backend defines where the state file is stored and how it is accessed. Common
backends include local files, remote storage solutions (e.g., AWS S3, Azure Blob Storage), and
Terraform Cloud.
• Idempotency: Ensure that applying the same configuration multiple times results in the same
state.
Answer: The terraform validate command checks the syntax and validity of Terraform configuration
files. It ensures that the configurations are syntactically correct and can be used by Terraform.
36. How do you use Terraform for resource scaling?
Answer: Resource scaling in Terraform can be managed using the count parameter for creating
multiple instances or using dynamic blocks and input variables to adjust resource properties based
on conditions.
desired_capacity = var.desired_capacity
min_size = var.min_size
max_size = var.max_size
Answer: A module output is a value that a Terraform module exposes for use by other configurations
or modules. It allows the module to share information such as resource attributes with other parts of
the configuration.
output "instance_id" {
value = aws_instance.my_instance.id
Answer: Errors during Terraform provisioning can be handled by reviewing error messages, checking
resource dependencies, and validating configurations. Using terraform plan to preview changes and
terraform apply to apply them can help identify and resolve issues.
Answer: The terraform graph command generates a visual representation of the dependency graph
of resources in a Terraform configuration. It helps to understand the relationships and dependencies
between resources.
40. How do you ensure Terraform configurations are compliant with organizational standards?
Answer: Terraform Sentinel is a policy as code framework that integrates with Terraform Enterprise
and Terraform Cloud. It allows users to define policies to enforce governance and compliance rules
for infrastructure provisioning.
Answer: Terraform can be integrated into CI/CD pipelines by adding steps to initialize, plan, apply,
and validate configurations. Automation tools like Jenkins, GitLab CI, or GitHub Actions can manage
Terraform deployments as part of the pipeline.
43. What are terraform workspaces and how are they different from environments?
Answer: Terraform workspaces allow managing multiple state files within a single configuration
directory. They are useful for managing different environments (e.g., development, staging,
production) without needing separate configuration directories.
Answer: A terraform.lock.hcl file is used to lock provider versions to ensure consistent deployments.
It records the versions of provider plugins used during initialization and prevents unintentional
updates.
Answer: Terraform manages network configurations by defining resources such as VPCs, subnets, and
security groups in configuration files. Providers offer modules and resources for creating and
managing network components.
cidr_block = "10.0.0.0/16"
Answer: Configuration drift can be managed by regularly running terraform plan to detect
discrepancies between the desired state and the actual state. Drift should be addressed by updating
the configuration and applying the necessary changes.
47. What are Terraform workspaces used for?
Answer: Terraform workspaces are used to create and manage multiple instances of the same
configuration, each with its own state file. They are helpful for managing different environments or
stages within the same configuration.
Answer: A terraform output block defines the values that Terraform should display after applying a
configuration. Outputs are useful for retrieving information about resources and passing data
between modules.
output "bucket_name" {
value = aws_s3_bucket.my_bucket.bucket
Answer: The terraform validate command checks whether the configuration files are valid and can be
processed by Terraform. It ensures that the configuration files are syntactically correct and do not
contain errors.
Answer: Terraform manages cloud security groups by defining resources that describe security rules
and group settings. For example, the aws_security_group resource allows configuring inbound and
outbound rules for AWS security groups.
name = "my_security_group"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
Answer: Secrets should be managed securely using environment variables, secret management tools
like HashiCorp Vault, or encrypted remote backends. Avoid hardcoding secrets directly in Terraform
configuration files.
Answer: A Terraform state lock prevents concurrent operations on the same state file. State locking is
crucial for preventing conflicts and ensuring that only one process modifies the state file at a time. It
is commonly used with remote backends that support locking.
ami = "ami-123456"
instance_type = "t2.micro"
Answer: Terraform manages Kubernetes resources using the Kubernetes provider. You can define
Kubernetes resources such as deployments, services, and namespaces in Terraform configuration
files.
provider "kubernetes" {
config_path = "~/.kube/config"
metadata {
name = "nginx-deployment"
spec {
replicas = 2
selector {
match_labels {
app = "nginx"
template {
metadata {
labels {
app = "nginx"
spec {
container {
name = "nginx"
image = "nginx:1.14.2"
# Configuration
depends_on = [aws_instance.web]
# Configuration
Answer: Terraform Cloud is a managed service by HashiCorp that provides a centralized platform for
Terraform operations. It includes features such as remote state management, collaboration,
governance, and integration with CI/CD pipelines.
Answer: Terraform supports multi-cloud deployments by defining multiple provider blocks in the
configuration. Each provider block can configure different cloud services, enabling the management
of resources across various cloud platforms.
provider "aws" {
region = "us-east-1"
provider "google" {
project = "my-project"
region = "us-central1"
Answer: terraform plan output files are generated files that store the proposed changes to the
infrastructure. They provide a detailed preview of what will be created, updated, or destroyed, and
are used to review and confirm changes before applying them.
61. How do you create and manage Terraform modules?
Answer: Create and manage Terraform modules by organizing configuration files into directories,
defining resources, variables, and outputs within the module, and using the module in other
configurations. Modules can be versioned and shared through the Terraform Registry or private
repositories.
Answer: Handle Terraform state file changes by using commands like terraform plan to preview
changes, terraform apply to apply them, and terraform state commands to manipulate the state file
directly if needed. Ensure state file consistency and accuracy.
Answer: The terraform console command opens an interactive console for evaluating Terraform
expressions and inspecting the state. It allows users to query resource attributes and evaluate
expressions within the Terraform context.
filename = "lambda_function_payload.zip"
function_name = "my_lambda_function"
role = aws_iam_role.lambda_exec.arn
handler = "index.handler"
source_code_hash = filebase64sha256("lambda_function_payload.zip")
runtime = "python3.8"
65. What are terraform providers and how are they used?
Answer: Terraform providers are plugins that enable Terraform to interact with various services and
platforms. Providers define the resources and data sources available for use in Terraform
configurations. They are specified in the configuration using provider blocks.
provider "aws" {
region = "us-east-1"
Answer: Perform resource updates with Terraform by modifying the configuration files and running
terraform plan to review changes. Apply the updates using terraform apply, which updates the
resources to match the desired state.
Answer: Dynamic blocks in Terraform allow for the generation of multiple nested blocks based on a
set of values. They are useful for creating configurations that need to iterate over lists or maps.
dynamic "ingress" {
for_each = var.allowed_ips
content {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = [ingress.value]
Answer: The terraform fmt command formats Terraform configuration files to ensure consistent style
and readability. It automatically adjusts the layout of configuration files according to Terraform's style
guidelines.
instance_type = "t2.micro"
70. How do you use terraform apply with a specific plan file?
Answer: Use terraform apply with a specific plan file by providing the plan file path as an argument.
This allows you to apply the changes described in the plan file.
Answer: terraform import allows you to import existing resources into Terraform management. It
creates a state file entry for a resource that was created outside of Terraform and enables Terraform
to manage it going forward.
Answer: The count parameter allows for the creation of multiple instances of a resource based on a
specified number. It helps in scaling resources dynamically.
count = 3
ami = "ami-123456"
Answer: Sensitive data should be managed securely using environment variables, secret
management tools, or encrypted storage solutions. Mark sensitive variables in Terraform with the
sensitive attribute to avoid exposing them in logs or outputs.
variable "db_password" {
type = string
sensitive = true
Answer: The terraform validate command checks the syntax and validity of Terraform configuration
files. It verifies that the configuration is well-formed and adheres to the required schema.
Answer: A Terraform backend defines how Terraform stores and manages the state file. It can be local
or remote, with remote options including cloud storage solutions like AWS S3, Azure Blob Storage, or
Terraform Cloud.
Answer: Manage Terraform modules by defining them in separate directories with their own main.tf,
variables.tf, and outputs.tf files. Use modules in configurations by referencing them with source and
passing variables as needed.
Answer: A Terraform provider block specifies the provider being used and its configuration settings,
such as credentials and regions. It allows Terraform to interact with the service or platform specified
by the provider.
provider "aws" {
region = "us-east-1"
Answer: Terraform manages Docker resources using the Docker provider. You can define Docker
containers, images, networks, and volumes in Terraform configuration files.
provider "docker" {}
image = "nginx:latest"
name = "my_nginx"
ports {
internal = 80
external = 8080
Answer: Perform rolling updates by managing resources with configurations that support updating in
a controlled manner. For example, use count and lifecycle settings to ensure a minimum number of
instances are always available during updates.
Answer: Terraform Sentinel is a policy as code framework integrated with Terraform Enterprise and
Terraform Cloud. It allows defining and enforcing policies to ensure compliance and governance for
infrastructure provisioning.
Answer: Terraform manages AWS ECS resources by defining services, task definitions, and clusters in
configuration files. It allows users to provision and configure ECS resources for containerized
applications.
name = "my-cluster"
family = "my-task"
container_definitions = jsonencode([{
name = "my-container"
image = "nginx:latest"
cpu = 256
memory = 512
essential = true
}])
}
83. What is a Terraform data source?
Answer: A Terraform data source allows querying and retrieving information from external sources
that are not managed by Terraform. It provides access to data that can be used in resource
configurations.
owners = ["amazon"]
most_recent = true
Answer: Terraform manages Azure resources using the Azure provider. Define Azure resources like
virtual machines, storage accounts, and networks in Terraform configuration files.
provider "azurerm" {
features {}
name = "example-resources"
Answer: Resource attributes define specific properties or settings of a resource. They are used to
configure and manage the behavior of the resource within the Terraform configuration.
ami = "ami-123456"
instance_type = "t2.micro"
Answer: A terraform plan file is an artifact generated by the terraform plan command that describes
the actions Terraform will take to achieve the desired state. It serves as a preview of changes before
applying them.
Answer: Terraform manages AWS S3 resources by defining aws_s3_bucket and related resources in
configuration files. It allows users to create and configure S3 buckets and manage their settings.
bucket = "my-bucket"
lifecycle {
prevent_destroy = true
identifier = "my-db-instance"
engine = "mysql"
instance_class = "db.t2.micro"
allocated_storage = 20
Answer: Terraform manages Google Cloud resources using the Google Cloud provider. Define
resources like virtual machines, storage, and networking components in configuration files.
provider "google" {
project = "my-project"
region = "us-central1"
name = "my-instance"
machine_type = "n1-standard-1"
zone = "us-central1-a"
boot_disk {
initialize_params {
image = "debian-cloud/debian-9"
Answer: Terraform variables are used to parameterize configurations and provide values dynamically.
They allow users to define and customize input parameters for resources and modules.
variable "region" {
type = string
}
Answer: Manage Terraform provider versions by specifying the version constraints in the provider
block. Use the version attribute to control which provider versions are used.
provider "aws" {
Answer: A Terraform resource type represents a specific kind of infrastructure object, such as an EC2
instance or an S3 bucket. Each resource type is associated with a provider and has attributes and
configuration options.
ami = "ami-123456"
instance_type = "t2.micro"
Answer: Terraform and AWS CloudFormation can be used together by managing CloudFormation
stacks using the aws_cloudformation_stack resource. This allows Terraform to provision and manage
resources defined in CloudFormation templates.
name = "my-stack"
template_body = file("template.yaml")
Answer: Terraform manages IAM roles using the aws_iam_role resource. You can define role policies,
attach policies, and configure IAM roles for various AWS services.
name = "my-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "ec2.amazonaws.com"
},
})
Answer: Terraform and Ansible can be used together by managing infrastructure with Terraform and
configuring it with Ansible. Terraform provisions the infrastructure, and Ansible performs post-
provisioning configuration tasks.
# Terraform configuration
Ansible playbook:
yaml
Copy code
hosts: all
tasks:
apt:
name: nginx
state: present
module "vpc" {
source = "./modules/vpc"
cidr_block = "10.0.0.0/16"
100. How do you manage Terraform state files with multiple users?
Answer: Manage Terraform state files with multiple users by using remote backends that support
locking and versioning, such as AWS S3 with DynamoDB for state locking. This ensures state
consistency and prevents concurrent modifications.