Terraform Basic interview Questions and Answers:
1. What is the key features of Terrafrom?
Ans: Terraform is an open-source infrastructure as code (IaaC) tool developed by HashiCorp. It allows users to define and provision infrastructure resources using a high-level configuration language called HashiCorp Configuration Language (HCL) or JSON.
- Declarative Configuration
- Infrastructure as Code (IaC):
- Multi-Cloud and Multi-Provider
- Resource Graph
- State Management
- Resource Provisioning
- Modular Design
- Plan and Apply Workflow
- Integration with Other Tools
- Community and Ecosystem
1.Declarative Configuration: Terraform uses a declarative syntax to define infrastructure resources, which means you specify the desired state of the infrastructure rather than the steps to achieve that state. This makes it easier to understand and maintain configurations.
2. Infrastructure as Code (IaC): Terraform treats infrastructure as code, meaning that infrastructure configurations can be version-controlled, reviewed, and managed using the same practices as software code. This makes it easier to collaborate, track changes, and ensure consistency.
3. Multi-Cloud and Multi-Provider: Terraform supports multiple cloud providers, including AWS, Azure, Google Cloud Platform (GCP), and many others. It also supports other infrastructure providers such as Docker, VMware, and OpenStack. This enables users to manage infrastructure across multiple providers using a single configuration.
4. Resource Graph: Terraform creates a dependency graph of all the resources in the configuration. This allows it to automatically determine the correct order in which resources should be created, updated, or deleted to reach the desired state.
5. State Management: Terraform maintains a state file that keeps track of the current state of the infrastructure. This file is used to determine which resources need to be created, updated, or deleted when a configuration is applied. Terraform stores this state locally by default, but it can also be stored remotely in a shared backend, such as Amazon S3 or HashiCorp Consul.
6. Resource Provisioning: Terraform can automatically provision resources based on a configuration file. This includes creating, updating, and destroying resources as needed. Terraform also supports provisioning scripts and templates, which can be used to customize resource configurations.
7. Modular Design: Terraform has a modular design that allows users to organize configurations into reusable modules. Modules can be shared and reused across different projects, enabling users to build complex infrastructures more efficiently.
8. Plan and Apply Workflow: Terraform follows a plan and apply workflow. First, it creates an execution plan that shows the changes it will make to reach the desired state. Then, the user can review the plan and, if satisfied, apply it to make the changes.
9. Integration with Other Tools: Terraform can be integrated with other tools in the DevOps toolchain, such as version control systems (e.g., Git), continuous integration/continuous deployment (CI/CD) pipelines, and configuration management tools. This allows for a seamless integration of infrastructure changes into the software development lifecycle.
10. Community and Ecosystem: Terraform has a large and active community of users, contributors, and providers. This means that there are many resources, tutorials, and extensions available to help users get started with Terraform and extend its functionality.
2. Define IAC?
Ans: Infrastructure as Code (IAC) refers to the concept of managing and provisioning computing infrastructure through code and scripts rather than manual processes.
3. What is Terraform init?
Ans: Terraform init
is a command used to initialize a new or existing Terraform configuration. It prepares the working directory for Terraform configuration by downloading and installing the required provider plugins and modules specified in the configuration files
The init
command performs several key functions:
1.Initializing Backend: If the configuration specifies a remote backend (e.g. S3
, Azure Blob Storage
, HashiCorp Consul
), terraform init
initializes the backend and sets up remote state storage. This allows multiple users or automated systems to work together on the same Terraform configuration.
2. Installing Providers: If the configuration uses provider plugins (e.g., AWS, Azure, Google Cloud Platform), terraform init
downloads and installs the required provider plugins. This ensures that Terraform has access to the necessary resources and APIs to manage the specified infrastructure.
3. Downloading Modules: If the configuration uses Terraform modules (reusable units of configuration), terraform init
downloads and installs the specified modules. This allows for modularization and reuse of infrastructure configurations across projects.
4. Initializing Workspace: If the configuration uses workspaces (e.g., different environments like development
, staging
, production
), terraform init
initializes the workspace, creating a separate state file for each workspace. This allows for isolation and management of multiple environments within the same configuration.
4. What is Terraform D?
Ans: Terraform D is a plugin used on most in-service systems and Windows. Terraform init by default searches next directories for plugins.
5. Define null resource in Terraform?
Ans: null resource is a special resource type that performs a no-op operation. It is used to create dependencies between resources that are not directly managed by Terraform, such as external scripts or manual processes.
6. What do you mean by Terraform cloud?
Ans: Terraform Cloud is a service offered by HashiCorp that provides a managed platform for Terraform users to collaborate on infrastructure as code (IaC) projects. It includes features for infrastructure management, collaboration, and automation.
7. What is some key features of terraform cloud?
Ans: Below are some key features of terraform cloud.
- Remote state management
- Collaboration
- Version control integration
- API-Driven Architechture
- Remote Operations
- Cost Estimation
- Secure and Scalable
1.Remote State Management: Terraform Cloud provides a centralized location for storing and sharing the Terraform state file, which tracks the current state of the infrastructure. This allows multiple users or teams to work together on the same infrastructure project without conflicts.
2. Collaboration: Terraform Cloud supports collaboration by allowing multiple users to access and manage infrastructure configurations. It provides features such as access control, audit logging, and workspace locking to facilitate collaboration.
3. Version Control Integration: Terraform Cloud integrates with version control systems (VCS) such as GitHub, GitLab, and Bitbucket. This allows users to manage infrastructure configurations using familiar version control workflows.
4. API-Driven Infrastructure: Terraform Cloud provides an API that allows users to programmatically manage infrastructure resources. This enables automation and integration with other tools in the DevOps toolchain.
5. Remote Operations: Terraform Cloud supports remote operations, which allows users to apply changes to infrastructure resources directly from the Terraform Cloud interface. This is useful for managing infrastructure changes from a centralized location.
6. Cost Estimation: Terraform Cloud provides cost estimation features that allow users to estimate the cost of infrastructure changes before applying them. This helps users make informed decisions about infrastructure changes.
7. Secure and Scalable: Terraform Cloud is designed to be secure and scalable, with features such as role-based access control (RBAC), encryption at rest, and support for large-scale infrastructure deployments.
8. What is terraform backend?
Ans: Terrafrom backend is a type of configuration that determines where Terraform stores its state file, which keeps track of the current state of the infrastructure. The state file is used to compare the current state with the desired state defined in the Terraform configuration and to determine which actions (e.g., create, update, delete) should be performed to reach the desired state.
9. What is the types of terraform backend?
Ans: Below are the types of terraform backend.
- Local Backend
- Remote Backend
- Workspace backend
- Custom Backend
1. Local Backend: The local backend stores the state file on the local disk of the machine where Terraform is run. This is the default backend used when no other backend is specified. The local backend is simple and easy to use, but it is not suitable for collaborative or production environments because the state file is not shared with other users or systems.
2. Remote Backend: The remote backend stores the state file remotely, allowing multiple users or systems to access and manage the same infrastructure configuration. Terraform supports several remote backend providers, including Amazon S3, Azure Blob Storage, Google Cloud Storage, and HashiCorp Consul.
3. Workspace Backend: The workspace backend is a special type of backend that allows users to manage multiple environments (e.g., development, staging, production) within the same configuration. Each workspace has its own state file, allowing for isolation and management of multiple environments.
4. Custom Backend: Terraform also allows users to create custom backends using the terraform_backend
block. This allows for flexibility and customization in backend configuration.
10. What are the version controls supported by Terraform besides GitHub?
Ans: The version controls supported GitLab EE, GitLab CE, and Bucket Cloud.
11. What are the most useful Terraform commands?
Ans: Below are mostly used commands by terraform.
1.terraform init – initializes the current directory
2. terraform validate: Validates the config files
3. terrafrom plan: Give us the plan of resource
4. terraform apply: create the infrastructure resources
5. terraform refresh: refreshes the state file
6. terrafrom graph: creates a DOT-formatted graph
12. Describe the lifecycle of Terraform resource?
Ans:
- Writing Configuration: The lifecycle begins with the authoring of a Terraform configuration file
- Initialization: nitializes the configuration, setting up the backend and downloading any necessary provider plugins.
- Planning: The
terraform plan
command creates an execution plan. - Apply: Executing
terraform apply
applies the changes required to reach the desired state. Terraform will create, update, or destroy resources based on the plan previously generated. - Resource Creation: During the apply stage, if a resource does not exist in the current state, Terraform will create it.
- Resource Update: If a resource exists but its current state differs from the desired state, Terraform will modify it.
- Resource Destruction: Resources can be explicitly removed from the configuration file or implicitly if changes in configuration render them obsolete.
- Resource State Management: Throughout its lifecycle, Terraform maintains the state of resources in a state file. This file tracks the mappings between the resources defined in the configuration and the actual resources provisioned in the infrastructure.
- Dependencies and Order of Operations: Terraform handles resource dependencies automatically. It determines the order of operations based on these dependencies to ensure that resources are created, updated, or destroyed in the correct sequence.
- Output and Verification: After applying changes, Terraform provides output indicating the status of each operation (successful, failed, or changed). Users can verify the infrastructure to ensure it meets the desired state.
- Resource Import: Existing resources not managed by Terraform can be brought under Terraform management using the
terraform import
command - Destruction: The lifecycle concludes with resource destruction if the entire infrastructure needs to be decommissioned. The
terraform destroy
command will remove all resources defined in the configuration, cleaning up the infrastructure.
13. How you can specify the dependencies in terraform?
Ans: You can define the dependencies between resources in terraform using below attribute. you can define the explicit ordering of resource creation and ensure that one resource is created after another.
depends_on
14. what is the purpose of plan commands in terraform
Ans: Its primary purpose is to create an execution plan, outlining the changes Terraform will make to the infrastructure to reach the desired state defined in the configuration files.
Below are some key features of terraform plan:
- Preview Changes: provides a detailed preview of the actions Terraform will take.This includes creating, updating, or destroying resources. It allows you to see what will happen before any changes are actually made.
- Identify Errors and Issues: you can catch syntax errors, misconfigurations, and other issues early in the process. This helps in avoiding potential disruptions or failures during the apply phase.
- Understand Impact: The execution plan shows the specific changes to each resource, including attribute modifications, additions, or deletions. This helps in understanding the impact of your changes on the existing infrastructure.
- Collaboration and Review: Teams can use the plan output for collaboration and review. By examining the proposed changes, team members can provide feedback or approve the plan before applying it.
- Planning for Execution: The plan command generates an execution plan that Terraform can use to apply changes. This plan can be saved to a file and then applied separately, ensuring the exact set of changes previewed is applied, which is useful for automation and scripting.
- Infrastructure State Verification: It verifies the current state of the infrastructure against the desired state defined in the configuration. This helps ensure consistency and detect any drift or manual changes that might have occurred.
15. How does terraform handle secret and sensitive data?
Ans: Terraform provides several features to help handle secrets and sensitive data securely. Here are some best practices:
- Sensitive Input Variables: When configuring your infrastructure with sensitive or secret information (such as usernames, passwords, API tokens, or Personally Identifiable Information), use Terraform input variables. Mark input variables as “sensitive” using the
sensitive
flag. This ensures that Terraform redacts these values in the output of commands or log messages. - Environment Variables: Store secret values in environment variables.
- State File Encryption: By default, Terraform stores the state file locally in unencrypted JSON format. This means that anyone with access to the project files can read the secrets. TO protect the sensitive data, consider the storing state remotely in backend that automatically encrypt the data at rest
16. How can you use the “depends_on” attribute in Terraform resource blocks?
Ans: The “depends_on” attribute in Terraform resource blocks defines an explicit dependency between resources. It ensures that the resource with the “depends_on” attribute is created or modified before the dependent resources, regardless of any implicit ordering. This attribute is useful when there are dependencies that Terraform cannot automatically detect.
17. What is the purpose of the Terraform “import” command?
Ans: The “Terraform import” command is used to import existing resources into the Terraform state. It allows Terraform to manage and track existing resources that were not initially created using Terraform, enabling their inclusion in the Terraform configuration and state management.
18. What is the purpose of the “Terraform refresh” command, and when would you use it?
Ans: The “Terraform refresh” command retrieves the current state of the infrastructure resources and updates the Terraform state file to match the real-world resources. It is useful when changes have been made outside of Terraform’s control and the state file needs to be updated to accurately reflect the actual state of the infrastructure.
19. Explain the concept of remote state locking in Terraform and its importance in team collaboration.Ans: Remote state locking in Terraform prevents concurrent modifications to the same state file by multiple users. When a user runs a Terraform command that modifies the state, the lock is acquired to prevent conflicts.
Ans: This ensures consistency and prevents data corruption in team-based workflows, where multiple users might be working on the same infrastructure.
20. How can you manage infrastructure secrets securely in Terraform, such as API keys or passwords?
Ans: To manage infrastructure secrets securely in Terraform, you can use environment variables or external systems like HashiCorp Vault. Storing sensitive data directly in Terraform configuration files is discouraged. Instead, you can define variables for secret values and populate them from external sources at runtime, ensuring confidentiality and separation of secrets from the configuration.
Terraform Intermediate Interview Questions and Answers
1. What is modules in terraform?
Ans: Module is a container for multiple resources that are used together. Modules help you organize and encapsulate infrastructure code, making it reusable, manageable, and more modular. They enable you to define a set of resources, outputs, and variables in a single unit, which can then be instantiated and used multiple times within your Terraform configurations.
Key concepts of module:
- Root module
- Child Module
1. Root Module: The root module is the main configuration directory where you run Terraform commands. It includes the primary Terraform configuration files:
main.tf
variable.tf
outputs.tf
2. Child Module: Child modules are modules that are called by the root module or other modules. They help to encapsulate and reuse configurations. For example, you might create a module for a virtual machine, a database, or a networking setup.
How to use modules:
Local Modules: Refer to modules defined in directories relative to the root configuration.
module "web_server" {
source = "./modules/web_server"
instance_type = "t2.micro"
ami = "ami-123456"
}
Remote Module: Refer to modules stored in version control systems (like Git) or module registries (such as Terraform Registry).
module "network" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 2.0"
name = "my-vpc"
cidr = "10.0.0.0/16"
}
Module Directory structure:
web_server/
├── main.tf
├── variables.tf
└── outputs.tf
2. What is a Private Module Registry in Terraform?
Ans: A Private Module Registry is a repository or service that allows organizations to host, manage, and share their Terraform modules internally within their organization. It is an enterprise-level solution that provides a centralized location for storing and sharing reusable infrastructure components.
3. Is Terraform usable for an on-prem infrastructure?
Ans: Yes
, Terraform can be used for on-prem infrastructure.
4. Does Terraform support multi-provider deployments?
Ans: Yes
, Terraform supports multi-provider deployments, meaning you can use it to provision and manage resources across multiple cloud providers (e.g., AWS, Azure, Google Cloud Platform) or multiple infrastructure providers (e.g., Docker, VMware, OpenStack) within a single configuration.
5. Name all version controls supported by Terraform?
Ans:
- Github
- Gitlab
- Bitbucket
- Azure repos
- AWS CodeCommit
- Hashicorp VCS
6. What are some of the built-in provisioners available in Terraform?
Ans: Below are the build in provisioners:
- Local-exec
- remote-exec
- file
1. local-exec: This provisioner allows you to run shell commands or scripts on the local machine where Terraform is being executed.
2. remote-exec: This provisioner allows you to run shell commands or scripts on remote machines via SSH or WinRM connections.
3. file: This provisioner allows you to upload files or directories from the local machine to a remote machine via SSH or WinRM connections.
7. Define Resource Graph in Terraform?
Ans: A resource graph is a visual representation of the resources. It helps modify and create independent resources simultaneously. Terraform establishes a plan for the configuration of the graph to generate plans and refresh the state. It creates structure most efficiently and effectively to help us understand the drawbacks.
8. How to Store Sensitive Data in Terraform?
Ans: When working with Terraform, it’s important to handle sensitive data, such as passwords, API keys, and other credentials, in a secure manner. Terraform provides several options for managing sensitive data:
- Environment Variables
- Input Variable
- Terraform cloud and terraform enterprise
- Hashicorp valut
1.Environment Variables: One option is to use environment variables to pass sensitive data to Terraform. Terraform automatically recognizes environment variables prefixed with TF_VAR_
and allows you to use them in your configuration files. For example, if you have a variable named password
, you can set it using the TF_VAR_password
environment variable.
export TF_VAR_password="your-password"
Then, you can reference this variable in your Terraform configuration file using the var
interpolation syntax:
resource "aws_instance" "example" {
...
password = var.password
}
2. Input Variables: Another option is to use input variables in your Terraform configuration files. Input variables can be set using a terraform.tfvars
file, which is a plaintext file that contains variable definitions. You can use the variable
interpolation syntax to reference the input variables in your Terraform configuration files.
variable "password" {
description = "The password for the instance"
type = string
}
Then, you can set the value of the input variable in the terraform.tfvars
file:
password = "your-password"
And reference the variable in your Terraform configuration file using the var
interpolation syntax:
resource "aws_instance" "example" {
...
password = var.password
}
3. Terraform Cloud and Terraform Enterprise: If you’re using Terraform Cloud or Terraform Enterprise, you can use the sensitive
attribute to mark sensitive variables as such. This prevents them from being displayed in the Terraform UI or CLI output.
variable "password" {
description = "The password for the instance"
type = string
sensitive = true
}
Then, you can reference the variable in your Terraform configuration file as usual:
resource "aws_instance" "example" {
...
password = var.password
}
The password value will be encrypted in the Terraform state file and in the Terraform Cloud or Terraform Enterprise workspace.
4. HashiCorp Vault: HashiCorp Vault is a secrets management tool that can be used to store and manage sensitive data, such as passwords and API keys. Terraform can integrate with Vault to retrieve secrets at runtime and use them in your Terraform configuration files
data "vault_generic_secret" "example" {
path = "secret/data/my-password"
}
resource "aws_instance" "example" {
...
password = data.vault_generic_secret.example.data["password"]
}
This approach ensures that sensitive data is stored securely in Vault and is not exposed in plaintext in your Terraform configuration files or state files.
9. what is terraform provider?
Ans: A Terraform provider is a plugin that defines the logic for creating, managing, and destroying resources in a particular infrastructure platform or service. It essentially acts as an interface between Terraform and the API of the platform or service.
For example, if you want to manage resources in AWS, you would use the AWS provider. If you want to manage resources in Google Cloud, you would use the Google Cloud provider.
Each provider has its own set of resources and data sources that it supports. Resources represent the infrastructure objects you want to create or manage (e.g., virtual machines, databases, load balancers), and data sources represent existing infrastructure objects that you want to reference (e.g., an existing AWS VPC).
10. How can you handle resource failures and retries in Terraform?
Ans:
Terraform provides built-in mechanisms to handle resource failures and retries. When a resource creation or update fails, Terraform detects the failure and automatically rolls back changes for that resource. It can then retry the operation based on the specified retry settings. Terraform also supports various error-handling techniques, such as using count and conditional expressions to conditionally create or destroy resources based on the success or failure of other resources. These features help ensure the reliability and resilience of infrastructure deployments.
11. Explain the concept of Terraform backends and the available options?
Ans: Terraform backends define where Terraform stores the state file and how it interacts with it. Backends can be local or remote. Local backends store the state file on the local disk, which is suitable for individual use or small teams. Remote backends store the state file remotely, allowing for collaboration, locking, and centralized management. Terraform provides several remote backend options, including AWS S3, Azure Blob Storage, and HashiCorp Terraform Cloud. Each backend option has its configuration settings and benefits, enabling flexibility and scalability in state management.
12. How can you organize your Terraform codebase for better maintainability?
Ans: To organize a Terraform codebase for better maintainability, you can adopt various practices:
- Modularization: Break down the codebase into reusable modules, encapsulating related resources and configurations.
- Folder Structure: Organize files into logical folders based on resource types, environments, or modules.
- Naming Conventions: Use consistent and descriptive naming conventions for resources, variables, and modules.
- Documentation: Include comments, README files, or documentation to provide guidance and context for the codebase.
- Version Control: Utilize a version control system like Git to track changes, collaborate, and roll back if needed.
By following Above practices, you can enhance code readability, reusability, and collaboration, making the codebase easier to maintain and evolve.
13. Explain the difference between Terraform’s “apply” and “refresh” commands.
Ans: The “apply” command in Terraform is used to create or update the infrastructure based on the current configuration. It compares the configuration with the current state, determines the necessary changes, and applies them to the infrastructure.
On the other hand, the “refresh” command is used to reconcile the state with the actual resources in the infrastructure. It updates the state file by querying the infrastructure provider APIs and refreshing the resource information in the state. The “refresh” command does not make any changes to the infrastructure; it only updates the state file to reflect the current state accurately.
14. What are Terraform provisioners, and how can you use them?
Ans: Terraform provisioners are used to execute scripts or commands on a remote resource during the provisioning process. They are typically used to perform configuration tasks, such as software installations, package updates, or service configurations.
Terraform provides several types of provisioners, including local-exec
,remote-exec,
and file
. By configuring provisioners within resource blocks, you can define the necessary actions to be executed on the provisioned resources, ensuring they are properly configured after creation or update.
15. What is the purpose of Terraform’s “null_resource,” and when would you use it?
Ans: The “null_resource” in Terraform represents a resource that doesn’t directly correspond to a physical or virtual infrastructure object. It is a placeholder resource that can be used to execute provisioners or perform actions that are not tied to a specific resource type.
The “null_resource” can be helpful when you need to perform tasks like running local-exec provisioners, calling external scripts, or executing commands that are not related to a particular resource. It provides flexibility and allows for custom actions within the Terraform workflow.
16. How can you manage secrets and sensitive data in Terraform?
Ans: Managing secrets and sensitive data in Terraform require careful consideration to ensure security. Best practices include:
- Storing secrets outside of version-controlled files, using tools like HashiCorp Vault or cloud-specific secret management services.
- Utilizing Terraform input variables or environment variables to pass sensitive values securely during runtime.
- Encrypting sensitive data using tools like Terraform Vault provider or native encryption mechanisms provided by the infrastructure platform.
- Avoid writing secrets in plain text within Terraform configurations or logs.
17. What is the difference between Terraform modules and remote modules?
Ans: Terraform modules are self-contained packages of Terraform configurations that encapsulate a specific set of resources and their associated dependencies. They promote code reusability and modularity by allowing you to define and share infrastructure components across projects and teams.
Remote modules, on the other hand, refer to modules hosted remotely, typically in a version control repository or a module registry. Remote modules provide a way to retrieve and use pre-configured modules directly from a remote source. They enable code sharing, versioning, and collaboration by allowing users to consume modules without manually copying or managing the module code locally.
In summary, modules are the concept of reusable infrastructure configurations, while remote modules are a way to access and consume those reusable configurations from remote sources.
18. How can you perform targeted resource deployment in Terraform?
Ans: Targeted resource deployment in Terraform can be achieved by using the “-target” flag with the “apply” or “plan” command. By specifying the target resource’s address or name, Terraform focuses only on that particular resource and its dependencies during the deployment or planning process.
Targeted deployment is useful while isolating changes to specific resources without affecting the rest of the infrastructure.
19. Explain the concept of Terraform’s “data” blocks and their use cases?
Ans: Terraform’s “data” blocks allow the retrieval and use of data from remote systems or APIs during the Terraform execution. Data blocks can fetch information such as AWS AMI IDs, VPC details, or external configuration settings. They enable Terraform to incorporate external data into the configuration, making it dynamic and adaptable to the current state of the infrastructure or external services.
20. Describe how to use Terraform’s “count.index” and “count.indexes” for resource customization?
Ans: Terraform’s “count.index” and “count.indexes” allow for resource customization based on the count of a resource. The “count.index” variable represents the current index of a resource within a count block.
It can be used to generate unique resource names or perform conditional logic based on the index. The “count.indexes” variable provides a list of all indices within a counted block, allowing for more advanced resource customization based on multiple indices.
21. Explain how to use the Terraform “sensitive” argument to hide sensitive output values?
Ans: The “sensitive” argument in Terraform is used to hide sensitive output values when displaying the Terraform plan or applying the output. By marking an output variable as sensitive, its value will be masked in the output, preventing accidental exposure of sensitive information. This is useful when dealing with outputs that contain passwords, private keys, or other confidential data that should not be visible to everyone.
When working with sensitive data in Terraform, you can use the "sensitive"
argument to hide sensitive output values. This is particularly useful when secret information is part of the Terraform output that you want to protect. Let’s explore how to achieve this:
Marking Output as Sensitive: In your Terraform configuration, when defining an output, you can explicitly mark it as sensitive. By doing so, Terraform ensures that the value of that output is not displayed in the console output and is not stored in the Terraform state file.
There are two common approaches to handle sensitive output values:
- Using the
nonsensitive
Function: - Setting the
sensitive
Option Directly:
1. Using the nonsensitive
Function:
You can wrap the sensitive value with the nonsensitive
function.
output "token_value" {
value = nonsensitive(tfe_team_token.test.token)
}
2. Setting the sensitive
Option Directly:
Alternatively, you can set the sensitive
option directly in the output block.
output "token_value" {
value = tfe_team_token.test.token
sensitive = true
}
23. What is the purpose of Terraform’s “lifecycle” block and when would you use it?
Ans: Terraform’s “lifecycle” block allows the specification of lifecycle-specific configuration for resources. It provides control over resource behavior during creation, update, and deletion. The lifecycle block supports configuration options like resource creation and update timeouts, prevent destruction, ignore changes, and more.
It is useful when you need fine-grained control over resource management and want to define specific behavior for certain resources.
24. How can you use Terraform to manage non-cloud infrastructure resources?
Ans: Terraform can manage non-cloud infrastructure resources by utilizing various provisioners and external tools. Provisioners like “local-exec” or “remote-exec” can execute scripts or commands on local or remote instances, enabling the configuration of non-cloud resources.
Additionally, Terraform can be integrated with infrastructure deployment tools like Ansible or Chef to handle the provisioning and configuration of non-cloud resources, leveraging their respective capabilities.
25. Explain how Terraform handles drift detection and resource reconciliation.
Ans: Terraform handles drift detection and resource reconciliation by comparing the current state stored in the state file with the desired state defined in the configuration. During a Terraform application, it detects any differences between the two states and determines the necessary actions to converge the infrastructure to the desired state.
Terraform can create, update, or delete resources as needed to reconcile the differences and bring the infrastructure into the desired state.
26. Describe the process of using the Terraform “plan-out” flag for plan output preservation?
Ans: The “plan-out” flag in Terraform is used to preserve the planned output to a file for later use. By specifying the “-out” flag followed by a filename, Terraform saves the execution plan to that file. The preserved plan file can be used to apply the exact planned changes at a later time, ensuring consistency between the planned and applied changes.
Terraform Advanced Interview Questions and Answers
1. Explain State File Locking in terraform?
Ans: It is a mechanism to prevent concurrent access to the Terraform state file by multiple users or processes, which could lead to data corruption or inconsistent state.
When Terraform operates on a project, it creates and maintains a state file. This file keeps track of the resources managed by Terraform and their current state. To ensure that only one instance of Terraform is modifying the state file at a time, Terraform provides state file locking.
2. What do you understand by a Tainted Resource?
Ans: A tainted resource is a resource that is forced to be destroyed and recreated on the next apply command. When a resource is marked as tainted, the state files are updated, but nothing changes on infrastructure. The terraform plan out shows that help will get destroyed and recreated. The changes get implemented when the next apply happens.
3. How to lock Terraform module versions?
Ans: To lock Terraform module versions, you can utilize the source
parameter in your module block to specify a specific module version. This can be achieved by specifying the module address with the version number appended to it.
module "eks" {
source = "terraform-aws-modules/eks/aws"
version = "12.0.0"
// Other configuration settings...
}
ensure that Terraform always uses that version of the module, even if newer versions are available. This helps to maintain consistency and predictability in your Terraform deployments.
4. How to lock Terraform module versions in the github?
Ans: When using GitHub as the source for your Terraform modules, you can lock the module version by specifying the GitHub repository and the Git tag corresponding to the version you want to use
module "example" {
source = "github.com/terraform-aws-modules/terraform-aws-vpc"
version = "v2.0.0"
// Other configuration settings...
}
In this example, the module is sourced from a GitHub repository at github.com/terraform-aws-modules/terraform-aws-vpc
and uses version v2.0.0
. By specifying the version as a Git tag (prefixed with v
), you can ensure that Terraform always uses that specific version of the module, even if newer versions are available.
It’s important to note that when using GitHub as the source, the GitHub repository must be publicly accessible or accessible to the Terraform process running on your local machine or your CI/CD system. If the repository is private or requires authentication, you can use the git
parameter to specify the URL of the repository and the ref
parameter to specify the branch, tag, or commit hash
module "example" {
source = "git::https://github.com/terraform-aws-modules/terraform-aws-vpc.git?ref=branch-name"
// Other configuration settings...
}
In this example, the module is sourced from a private GitHub repository at https://github.com/terraform-aws-modules/terraform-aws-vpc.git
and uses the branch-name
branch.
5. What is Terraform Core? Tell us some primary responsibilities of it?
Ans: Terraform Core is the core component of HashiCorp’s Terraform infrastructure as code tool.
The primary responsibilities are as follows:s
- Infrastructure’s code functionalities include module and configuration file reading and interpolation.
- Building a Resource Graph
- RPC-based plugin communication
- Plan implementation
- Resource state management
6. How will you upgrade plugins on Terraform?
Ans:
Upgrading plugins in Terraform involves updating the plugin binaries to the latest version compatible with the Terraform CLI.
terraform init -upgrade
7. How will you control and handle rollbacks when something goes wrong?
Ans: You have to save your configuration in version control and commit it before making any changes, and then use the features of your version control system to revert to an earlier configuration if necessary. You must always recommit the previous version code in order for it to be the new version in the version control system.
8. How you can import the existing infrastructure into terraform?
Ans: Importing existing infrastructure into Terraform involves bringing resources that were created outside of Terraform under its management. This allows you to manage these resources using Terraform’s configuration files and state management. Here’s a step-by-step guide on how to import existing infrastructure into Terraform:
- Identify the resource
- Create a terraform configuration file
- initialize terraform
- Run
terraform import
- Update your configuration
- Apply the changes
1. Identify the resource:
First, identify the resource you want to import. It could be an AWS EC2 instance, a Google Cloud Storage bucket, or any other supported resource. You’ll need to know the resource’s unique identifier (e.g., an ARN, ID, or name).
2. Create a terraform configuration file:
Create a new Terraform configuration (.tf
file) in your project directory. Define the resource block for the type of resource you’re importing. Use the same provider and resource type as the existing infrastructure.
You don’t need to include all the resource attributes, but you should define the resource type and ID.
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "example" {
# Configuration will be updated after import
}
3. Initialiaze terraform:
Initialize the Terraform working directory. This sets up the backend and downloads any required provider plugins.
terraform init
4. Run the Import Command:
Use the terraform import
command to import the existing resource into the Terraform state. You need to specify the resource type and name defined in your configuration file, along with the resource’s identifier.
terraform import aws_instance.example i-1234567890abcdef0
In this example, aws_instance.example
is the resource name in the Terraform configuration, and i-1234567890abcdef0
is the actual ID of the AWS EC2 instance.
5. Update your configuration:
Update your Terraform configuration to match the current state of the imported resource. Ensure that all necessary attributes are included to prevent any unintended changes during the next apply.
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
# Add any other necessary attributes
}
6. Apply the changes:
Finally, apply the changes using terraform apply
. Terraform will update the existing resource to match your configuration.
9. how to use terraform workspace?
Ans: Terraform workspaces allow you to manage multiple deployments of the same configuration. They provide a way to isolate independent deployments while using the same state file. Let’s explore how to use Terraform workspaces:
1. Create an EC2 Instance
resource "aws_instance" "example_instance" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
2. Check the Current Workspace:
terraform workspace show
3. List Available Workspaces:
terraform workspace list
4. Create a New Workspace:
terraform workspace new dev
5. Verify the Setup:
terraform workspace select dev
10. Describe how you can use terraform to provision resources into different cloud providers simulteneously?
Ans: To provision the resources in different cloud provider simultenously, you can define multiple provider block in your terraform configuration. Each provider block specifies the provider plugin and its configuration specific to the cloud provider.
11. How does Terraform handle variable interpolation in strings?
Ans: Terraform allows variable interpolation in strings using the “${var.NAME}” syntax. When the configuration is processed, Terraform replaces the variable references with their corresponding value/
12. How can you leverage Terraform’s “count” and “for_each” features for resource iteration?
Ans: You can use the “count” and “for_each” features in resource blocks to iterate and create multiple instances of a resource.
count
allows you to create a fixed number of resource instances, while for_each
allows you to create instances based on a map or set of values
13. What is Terraform’s “force-unlock” command used for?
Ans: Terraform’s force-unlock command is commonly used in situations where the automatic locking mechanism fails to unlock due to system crashes or unexpected termination of Terraform commands. It manually unlocks the state for a particular workspace.
When you run commands such as terraform apply or terraform plan, Terraform locks your state files to prevent conflicts and inconsistency caused by concurrent writes. These locks help protect your infrastructure by preventing simultaneous modifications.
However, in some cases, you may need to manually unlock the state file using the force-unlock command. This situation could arise if a Terraform command is prematurely terminated and does not have the chance to unlock the state file.
14. What is the difference between Terraform’s “destroy” and “refresh” commands?
Ans: Terraform’s destroy and refresh commands are part of its suite of commands, but they serve vastly different purposes related to the lifecycle management of resources.
The destroy command is used to destroy or delete the Terraform-managed infrastructure. It is the opposite of terraform apply. Where the apply command creates or modifies infrastructure to match your configuration, destroy de-provisions all resources that the current Terraform configuration is managing.
On the other hand, the refresh command is used to reconcile the state Terraform has recorded with the real-world infrastructure. It does this by querying the provider to get the current status of resources.
15. what are plugins in terraform?
Ans: In Terraform, plugins extend its functionality and enable it to interact with various infrastructure providers and services. Plugins are executables that Terraform runs as subprocesses, communicating with them over RPC to perform tasks such as provisioning resources, managing providers, and more. There are two main types of plugins in Terraform: providers and provisioners.
Types of Plugins:
1.Providers: Providers are plugins responsible for understanding API interactions with various services (e.g., AWS, Azure, Google Cloud, Kubernetes, etc.). They allow Terraform to manage and provision resources on these platforms.
For example:
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "example" {
ami = "ami-123456"
instance_type = "t2.micro"
}
2. Provisioners: Provisioners are plugins used to execute scripts or commands on local or remote machines during the resource provisioning process. They are generally used for bootstrapping and configuring resources.
local-exec
: Executes commands on the machine running Terraform.
remote-exec
: Executes commands on remote machines via SSH or WinRM.
resource "aws_instance" "example" {
ami = "ami-123456"
instance_type = "t2.micro"
provisioner "local-exec" {
command = "echo ${self.private_ip} > ip_address.txt"
}
}
16. how to recover the .tfstate file if we accidently deleted?
Ans: Recovering a deleted .tfstate file can be critical, as it holds the current state of your Terraform-managed infrastructure. Without this file, Terraform won’t be able to accurately manage your resources.
- Check for Backups
- Restore from remote state backend
- Restore from local machine or Verision control system (Git)
1. Check for Backups:
- Local Backups: If you have local backups of your Terraform project directory, check to see if a copy of the
.tfstate
file is available. - Remote Backups: If you are using a remote backend (like AWS S3, Terraform Cloud, or Azure Blob Storage), check if the backend has a version history or backups from which you can restore the
.tfstate
file.
2. Restore from Remote State Backend:
If you’re using a remote state backend:
AWS S3: Check the S3 bucket for version history or backups. AWS S3 has versioning that can be used to recover deleted files.
Steps:
- Navigate to the S3 bucket.
- Check the “Versions” tab to see if previous versions of the
.tfstate
file are available. - Restore the required version.
Terraform Cloud/Enterprise: Terraform Cloud maintains a history of state versions.
Steps:
- Log in to Terraform Cloud.
- Go to the workspace where the state was stored.
- Navigate to the “States” section to view and restore previous state versions.
Azure Blob Storage: If using Azure Blob Storage with versioning enabled, restore the .tfstate
file from previous versions.
Steps:
- Go to the Azure portal.
- Navigate to the Blob Storage account.
- Check for previous versions of the
.tfstate
file.
3. Recover from Local Machine or VCS:
If you have version control (e.g., Git) set up:
Git: If the .tfstate
file was committed to a repository, you can recover it from the version history.
Steps:
- Check the commit history for the
.tfstate
file. - Checkout or restore the file from the relevant commit.
17. You have upgraded multiple eks worker nodes and one of node are not working, how you can troubleshoot issues?
Ans: When troubleshooting issues with EKS worker nodes after an upgrade, it’s essential to follow a structured approach to diagnose and resolve the problem. Here’s a step-by-step guide:
1. Identify the Problematic Node:
Check Node Status: Use kubectl
to check the status of the nodes.
kubectl get nodes
Identify the node that is not working as expected.
2. Check Node Details and Logs
- Describe the Node: Use
kubectl describe
to get detailed information about the node.
kubectl describe node <node-name>
2. Look for any errors or warnings in the node description.
3. Check the events at the bottom of the output for any clues about what might be wrong.
3. Check Node Logs: Access the logs on the problematic node.
# SSH into the node if necessary and check relevant logs, such as kubelet logs
ssh ec2-user@<node-ip>
# For Kubelet logs
sudo journalctl -u kubelet