Terraform Interview Questions and Answers


What is Terraform?
  • Terraform is an open-source Infrastructure as Code (IaC) tool created by HashiCorp. It allows you to define and provision infrastructure using a declarative configuration language (HashiCorp Configuration Language - HCL).
What is Infrastructure as Code (IaC)?
  • IaC is the practice of managing and provisioning infrastructure through code and automation, rather than through manual processes. This allows infrastructure to be treated like software, enabling version control, testing, and automated deployments.
What are the benefits of using Terraform?
  • **Automation:** Automates the provisioning and management of infrastructure.
  • **Consistency:** Ensures consistent environments across different stages (dev, staging, prod).
  • **Idempotence:** Applying the same configuration multiple times results in the same desired state.
  • **Version Control:** Infrastructure configurations can be stored and tracked in version control systems (like Git).
  • **Collaboration:** Facilitates collaboration among teams managing infrastructure.
  • **Multi-Cloud Support:** Supports provisioning infrastructure across various cloud providers (AWS, Azure, GCP, etc.) and other services.
  • **Reduced Risk:** Decreases the chance of human error during manual provisioning.
What is the difference between Terraform and traditional configuration management tools like Chef, Puppet, or Ansible?
  • **Terraform (Provisioning/Orchestration):** Primarily focuses on provisioning and orchestrating infrastructure resources (creating VMs, networks, databases, etc.). It's declarative and focuses on the desired state.
  • **Chef, Puppet, Ansible (Configuration Management):** Primarily focus on configuring and managing software and services *on* existing infrastructure (installing packages, configuring web servers, managing users). They can be more procedural.
  • While there's overlap, Terraform is generally used for the *initial creation* of infrastructure, while configuration management tools are used for *configuring* that infrastructure after it's provisioned.
What is HCL (HashiCorp Configuration Language)?
  • HCL is the primary language used by Terraform for writing configuration files. It's designed to be human-readable and machine-friendly, supporting both declarative definitions and interpolation.
What are the key components of a Terraform configuration?
  • **Provider:** Specifies the cloud provider or service Terraform will interact with (e.g., `aws`, `azurerm`, `google`).
  • **Resource:** Defines an infrastructure object to be created and managed (e.g., `aws_instance`, `azurerm_virtual_network`, `google_compute_instance`).
  • **Variable:** Allows you to parameterize your configuration, making it reusable (e.g., `variable "region" {}`).
  • **Output:** Defines values that will be displayed after Terraform applies the configuration (e.g., `output "instance_ip" {}`).
  • **Data Source:** Allows you to fetch information about existing infrastructure or external data to use in your configuration (e.g., `data "aws_ami" {}`).
  • **Module:** Encapsulates and reuses groups of resources (e.g., a module for creating a VPC).
What is a Terraform Provider?
  • A Provider is a plugin that Terraform uses to interact with a specific infrastructure platform or service. It understands the API of that service and exposes resources that can be managed by Terraform.
How do you specify a Provider in a Terraform configuration?
  • You use the `provider` block.
    provider "aws" {
      region = "us-east-1"
    }
What is a Terraform Resource? Give an example.
  • A Resource is the most important element in a Terraform configuration. It declares an infrastructure object (like a virtual machine, network interface, or database) that you want to create and manage.
    resource "aws_instance" "web_server" {
      ami           = "ami-0abcdef1234567890"
      instance_type = "t2.micro"
    
      tags = {
        Name = "HelloWorldServer"
      }
    }
What is the purpose of the `terraform init` command?
  • `terraform init` initializes a Terraform working directory. It downloads and installs the necessary providers and modules defined in the configuration files, sets up the backend for state management, and performs other initialization tasks. It's typically the first command you run in a new or cloned Terraform project.
What is the purpose of the `terraform plan` command?
  • `terraform plan` creates an execution plan. It compares the desired state defined in your configuration files with the current state of the infrastructure (as recorded in the state file and by querying the providers). It then outputs a detailed list of actions Terraform will take (create, update, delete) to achieve the desired state, without actually performing those actions.
What is the purpose of the `terraform apply` command?
  • `terraform apply` executes the actions proposed in a Terraform plan (or generates and executes a plan if no plan file is provided). It provisions the infrastructure resources as defined in the configuration files. It requires user confirmation by default unless the `-auto-approve` flag is used.
What is the purpose of the `terraform destroy` command?
  • `terraform destroy` is used to tear down infrastructure managed by a Terraform configuration. It generates a plan to destroy all resources defined in the configuration and then executes that plan (after confirmation). Use with caution!
What is the Terraform state file (`terraform.tfstate`)?
  • The state file is a JSON file that Terraform uses to map your configuration to the real-world infrastructure resources it manages. It keeps track of the state of your infrastructure, including resource IDs, attributes, and metadata. Terraform uses the state file to understand the current state of the infrastructure when planning and applying changes.
Why is managing the Terraform state file important?
  • The state file is critical for Terraform to function correctly. It's the source of truth for the current state of your infrastructure.
    • It maps configuration to real resources.
    • It tracks metadata and dependencies.
    • It enables planning and diffing.
    • It prevents Terraform from creating duplicate resources.
What are the risks of using a local state file in a team environment?
  • **Concurrency Issues:** Multiple users running Terraform simultaneously can lead to state file corruption or conflicts.
  • **Lack of Collaboration:** Sharing the state file manually is cumbersome and error-prone.
  • **Security Concerns:** The state file can contain sensitive information (though you should avoid storing secrets directly).
  • **Durability:** The local file is vulnerable to loss if the machine is compromised or fails.
What is a Terraform Backend?
  • A Backend is used to configure how Terraform stores its state file. Remote backends (like S3, Azure Blob Storage, GCP Cloud Storage, HashiCorp Consul, Terraform Cloud/Enterprise) are recommended for team environments to enable collaboration, locking, and durability.
How do you configure a Terraform Backend?
  • You use the `terraform` block with the `backend` configuration.
    terraform {
      backend "s3" {
        bucket = "my-terraform-state-bucket"
        key    = "path/to/my/state.tfstate"
        region = "us-east-1"
      }
    }
What is State Locking? Why is it important?
  • State Locking prevents multiple users from concurrently running Terraform commands (like `apply` or `destroy`) against the same state file. This is crucial in team environments to avoid state corruption and race conditions. Most remote backends provide native state locking mechanisms.
What are Terraform Variables? How do you define and use them?
  • Variables allow you to parameterize your Terraform configurations, making them more flexible and reusable.
    • **Defining:** Use the `variable` block.
      variable "instance_type" {
        description = "The type of EC2 instance to launch"
        type        = string
        default     = "t2.micro"
      }
    • **Using:** Reference the variable using `var. `.
      resource "aws_instance" "web_server" {
        instance_type = var.instance_type
        # ...
      }
How can you provide values for Terraform Variables?
  • Command-line flags (`-var 'instance_type=t2.small'`)
  • Variable definition files (`terraform.tfvars`, `*.auto.tfvars`, `-var-file`)
  • Environment variables (`TF_VAR_`)
  • Interactively (Terraform prompts if no value is provided and no default exists)
What are Terraform Outputs? How do you define and use them?
  • Outputs are used to expose values from your Terraform configuration that you want to easily access after applying the configuration (e.g., IP addresses, domain names, IDs).
    • **Defining:** Use the `output` block.
      output "instance_public_ip" {
        description = "The public IP address of the web server instance"
        value       = aws_instance.web_server.public_ip
      }
    • **Using:** After `terraform apply`, the output values are displayed. You can also use `terraform output `.
What are Terraform Data Sources? Give an example.
  • Data Sources allow you to fetch information about existing infrastructure or external data to use in your configuration. They do not create or manage resources, only query existing ones.
    data "aws_ami" "ubuntu" {
      most_recent = true
      owners      = ["099720109477"] # Canonical
    
      filter {
        name   = "name"
        values = ["ubuntu/images/hvm-ssd/ubuntu-*-20.04-amd64-server-*"]
      }
    
      filter {
        name   = "virtualization-type"
        values = ["hvm"]
      }
    }
    
    resource "aws_instance" "web_server" {
      ami           = data.aws_ami.ubuntu.id # Use the AMI ID from the data source
      instance_type = "t2.micro"
      # ...
    }
What are Terraform Modules? Why use them?
  • Modules are self-contained packages of Terraform configurations that can be reused across different projects or within the same project. They allow you to encapsulate and abstract away complex infrastructure patterns.
  • **Benefits:** Reusability, organization, consistency, maintainability.
How do you define and use a Terraform Module?
  • **Defining:** Create a separate directory with Terraform configuration files (`.tf`). This directory becomes the root of your module. Define variables for input and outputs for exposed values.
  • **Using:** Use the `module` block in your main configuration file. Specify the source of the module (local path, Git repository, Terraform Registry).
    module "vpc" {
      source = "./modules/vpc" # Local path
    
      vpc_cidr      = "10.0.0.0/16"
      subnet_cidrs  = ["10.0.1.0/24", "10.0.2.0/24"]
    }
Where can you get Terraform Modules from?
  • Terraform Registry (Public or Private)
  • Local paths
  • Git repositories (GitHub, GitLab, Bitbucket, etc.)
  • HTTP URLs
  • S3 Buckets
What is the Terraform Registry?
  • The Terraform Registry is a repository for discovering and sharing Terraform providers and modules. It hosts official providers, verified providers, and community providers, as well as thousands of public and private modules.
What is the purpose of the `.terraform` directory?
  • The `.terraform` directory is created by `terraform init`. It contains downloaded providers, modules, and other internal files used by Terraform. You should typically not commit this directory to version control.
What is the purpose of the `.terraform.lock.hcl` file?
  • This file is created by `terraform init` and records the exact versions of providers and modules used by your configuration. It acts as a dependency lock file, ensuring that subsequent `terraform init` runs use the same dependency versions, promoting consistency and preventing unexpected changes due to version updates. You *should* commit this file to version control.
What is the `depends_on` argument? When would you use it?
  • The `depends_on` argument is used to explicitly define dependencies between resources that are not automatically inferred by Terraform. It ensures that a resource is created or updated only after its dependencies are successfully created or updated. Use it sparingly, as Terraform usually infers dependencies based on resource references.
    resource "aws_instance" "web_server" {
      # ...
      depends_on = [
        aws_security_group.web_sg
      ]
    }
What is the difference between implicit and explicit dependencies?
  • **Implicit Dependencies:** Terraform automatically infers dependencies when one resource refers to another resource's attributes. This is the preferred way to define dependencies.
    resource "aws_eip" "ip" {
      instance = aws_instance.web_server.id # Implicit dependency on aws_instance.web_server
    }
  • **Explicit Dependencies:** Defined using the `depends_on` argument. Used when Terraform cannot infer the dependency automatically (e.g., when a resource needs to be created *after* another resource, but there's no direct attribute reference).
How does Terraform handle updates and changes to infrastructure?
  • When you run `terraform plan` and `terraform apply` after modifying your configuration, Terraform compares the new desired state with the current state (from the state file). It identifies the differences and generates a plan to update, create, or delete resources to match the new configuration. It attempts to update resources in place where possible to minimize downtime.
How does Terraform handle resource drift?
  • Resource drift occurs when the actual state of your infrastructure resources deviates from the state recorded in your Terraform state file (e.g., manual changes made outside of Terraform). When you run `terraform plan`, Terraform queries the provider to fetch the current state of the resources and compares it to the state file. It will detect the drift and propose actions to bring the infrastructure back in line with the configuration and state file.
What is the purpose of the `terraform refresh` command? (Note: Implicitly run by `plan` and `apply`)
  • `terraform refresh` updates the state file to reflect the current state of the infrastructure as reported by the providers. It does not modify the actual infrastructure. This command is often implicitly run by `terraform plan` and `terraform apply`. While you can run it manually, it's less common now.
What is the purpose of the `terraform import` command?
  • `terraform import` is used to bring existing infrastructure resources under Terraform management. It imports the state of a resource from the provider into your Terraform state file. You still need to write the corresponding resource block in your configuration files *after* importing.
    terraform import aws_instance.existing_server i-1234567890abcdef0
What are the limitations of `terraform import`?
  • It only imports the state of a single resource at a time.
  • It doesn't automatically generate the HCL configuration code for the imported resource; you have to write that manually.
  • It can be challenging for complex resources with many nested attributes.
What is the `count` argument? How do you use it?
  • The `count` argument is used to create multiple instances of a resource or module based on a given number.
    resource "aws_instance" "web_server" {
      count = 3 # Create 3 instances
    
      ami           = "ami-0abcdef1234567890"
      instance_type = "t2.micro"
    
      tags = {
        Name = "web-server-${count.index}" # Use count.index to differentiate
      }
    }
What is the `for_each` argument? How do you use it?
  • The `for_each` argument is used to create multiple instances of a resource or module based on a map or a set of strings. It provides more flexibility and better handling of resource lifecycles compared to `count`.
    variable "instance_names" {
      description = "Map of instance names and types"
      type = map(string)
      default = {
        web1 = "t2.micro"
        app1 = "t2.small"
      }
    }
    
    resource "aws_instance" "servers" {
      for_each = var.instance_names
    
      ami           = "ami-0abcdef1234567890"
      instance_type = each.value # Use each.key and each.value
    
      tags = {
        Name = each.key
      }
    }
What is the difference between `count` and `for_each`?
  • `count`: Creates instances based on an integer index (0, 1, 2...). Removing an item from the middle of a list used with `count` can cause subsequent resources to be recreated due to index shifts.
  • `for_each`: Creates instances based on map keys or set values. This provides stable identifiers for each instance, meaning that removing an item from a map/set will only affect the corresponding resource instance, leaving others untouched. `for_each` is generally preferred for managing collections of resources.
What is the purpose of the `lifecycle` block? Name some common arguments.
  • The `lifecycle` block allows you to customize the behavior of Terraform during resource creation, update, and deletion.
  • Common arguments:
    • `create_before_destroy`: Forces Terraform to create the new resource before destroying the old one during an update (useful for resources that cannot be updated in place).
    • `prevent_destroy`: Prevents Terraform from destroying the resource (a safety mechanism).
    • `ignore_changes`: Tells Terraform to ignore changes to specific attributes of a resource after it has been created.
What is `create_before_destroy`? When would you use it?
  • `create_before_destroy` is a `lifecycle` argument that forces Terraform to create a new instance of a resource before destroying the old one when an update requires replacement. This is useful for resources that are critical and cannot have downtime during an update (e.g., databases, load balancers) or when the provider doesn't support in-place updates for a specific attribute.
What is `prevent_destroy`? When would you use it?
  • `prevent_destroy` is a `lifecycle` argument that prevents Terraform from destroying a resource. If you try to run `terraform destroy` or apply a change that would delete a resource with this flag set to `true`, Terraform will return an error. This is a safety mechanism to prevent accidental deletion of important infrastructure.
What is `ignore_changes`? When would you use it?
  • `ignore_changes` is a `lifecycle` argument that tells Terraform to ignore changes to specific attributes of a resource after it has been created. This is useful when certain attributes of a resource are managed outside of Terraform (e.g., tags added by another automation process) or when a provider attribute is read-only after creation.
What is the difference between a local-exec and a remote-exec provisioner?
  • Provisioners are used to execute scripts on a local machine or a remote resource *after* it has been created by Terraform. They should generally be avoided in favor of configuration management tools like cloud-init, Chef, Puppet, or Ansible for configuring instances.
    • `local-exec`: Executes a command on the machine where Terraform is being run.
    • `remote-exec`: Executes a command on the newly created remote resource (e.g., an EC2 instance) using SSH or WinRM.
Why are provisioners generally discouraged in favor of configuration management tools?
  • Provisioners are less idempotent and harder to manage than dedicated configuration management tools.
  • They run only during creation or destruction of a resource, not for ongoing configuration.
  • They can make your Terraform runs less reliable if the provisioning step fails.
  • Configuration management tools are designed for managing the state of software and services on instances over time.
What is the Terraform Cloud/Enterprise?
  • Terraform Cloud (SaaS) and Terraform Enterprise (self-hosted) are commercial platforms provided by HashiCorp for collaboration, governance, and automation of Terraform workflows. They offer features like remote state storage, state locking, remote execution, team management, policy enforcement (Sentinel), and private module registries.
What is Sentinel?
  • Sentinel is a policy-as-code framework developed by HashiCorp. It's available in Terraform Cloud/Enterprise and allows you to define policies that enforce compliance and security rules for your infrastructure provisioning workflows. For example, you can write policies to prevent the creation of overly permissive security groups or expensive instance types.
What is Terraform Vault integration?
  • Terraform can integrate with HashiCorp Vault, a tool for managing secrets and sensitive data. This integration allows Terraform to fetch secrets (like database credentials or API keys) from Vault and use them during provisioning, without storing the secrets directly in the Terraform state or configuration files.
How can you handle secrets in Terraform?
  • **Avoid storing secrets directly in `.tf` files.**
  • Use environment variables.
  • Use a secrets management system like HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, or GCP Secret Manager and fetch secrets using Data Sources.
  • Use encrypted state backends where available.
  • Use tools like `sops` to encrypt secrets within your repository (less ideal as Terraform needs to decrypt them).
What is the difference between `terraform validate` and `terraform fmt`?
  • `terraform validate`: Checks the syntax and configuration of your Terraform files for correctness. It validates variable types, resource attributes, and other configuration elements.
  • `terraform fmt`: Formats your Terraform configuration files to a canonical style. This helps maintain consistent code style across your team.
What is the Terraform graph command?
  • `terraform graph` generates a visual representation of your Terraform configuration's resource dependencies. It outputs a DOT language graph that can be rendered using tools like Graphviz. This is useful for understanding the relationships between your resources.
What is the purpose of the `terraform taint` command? (Note: Deprecated in favor of `terraform apply -replace`)
  • `terraform taint` manually marks a resource as tainted, forcing Terraform to destroy and recreate it on the next `terraform apply`. This command is now deprecated, and the recommended way to force recreation is using `terraform apply -replace=`.
What is the purpose of the `terraform state` command? Name some subcommands.
  • The `terraform state` command is used for advanced state manipulation. Use these commands with caution, as incorrect usage can corrupt your state file.
  • Subcommands:
    • `list`: Lists resources in the state file.
    • `show`: Shows the attributes of a resource in the state file.
    • `rm`: Removes a resource from the state file (does NOT destroy the actual infrastructure).
    • `mv`: Moves a resource's address in the state file.
When would you use `terraform state rm`?
  • You would use `terraform state rm` to remove a resource from the Terraform state file without destroying the actual resource in your infrastructure. This is useful if you want to stop managing a specific resource with Terraform and manage it manually or with another tool.
When would you use `terraform state mv`?
  • You would use `terraform state mv` to move a resource's address in the state file. This is necessary if you refactor your Terraform code, changing the name or location of a resource block, while still wanting Terraform to recognize it as the same resource in the state file.
What is the difference between `terraform destroy` and manually deleting resources through the cloud provider console?
  • `terraform destroy`: Uses the state file to identify all resources managed by the configuration and systematically deletes them in the correct order based on dependencies. It updates the state file to reflect the destroyed resources.
  • Manual Deletion: Deleting resources through the console or API outside of Terraform will cause resource drift. Terraform will still see these resources in its state file on the next `plan`, but the provider will report them as missing. This can lead to errors or unexpected behavior. It's best to manage the full lifecycle of resources with Terraform.
What is the order of operations for `terraform apply`?
  • Refresh state (queries providers for current state).
  • Compare current state with desired state (from configuration).
  • Build a dependency graph.
  • Generate a plan (list of actions).
  • Execute the plan (creates, updates, or deletes resources based on dependencies).
  • Update the state file to reflect the new state.
  • Display outputs.
What is the order of operations for `terraform destroy`?
  • Refresh state.
  • Identify all managed resources.
  • Build a reverse dependency graph.
  • Generate a plan to destroy resources (starting with those that have no dependencies).
  • Execute the plan.
  • Update the state file (removes destroyed resources).
What is the difference between a Block, an Argument, and an Attribute in HCL?
  • **Block:** A container for other blocks or arguments. Defined by a type and zero or more labels, followed by curly braces `{}`. Examples: `resource "aws_instance" "web_server" {}`, `provider "aws" {}`, `variable "region" {}`.
  • **Argument:** Assigns a value to a name within a block. Defined by a name, an equals sign `=`, and a value (string, number, boolean, list, map, etc.). Examples: `region = "us-east-1"`, `instance_type = "t2.micro"`.
  • **Attribute:** A value exposed by a resource or data source *after* it has been created or fetched. You access attributes using dot notation. Examples: `aws_instance.web_server.id`, `data.aws_ami.ubuntu.id`.
How do you loop or iterate in Terraform?
  • You can use `count` or `for_each` to create multiple instances of resources or modules.
  • You can use `for` expressions to transform lists or maps.
    locals {
      instance_ids = [for instance in aws_instance.servers : instance.id]
    }
What are Local Values? How do you use them?
  • Local values (or `locals`) are used to assign a name to an expression's result for use within a module. They are useful for avoiding repetition, simplifying complex expressions, and making your configuration more readable.
    locals {
      common_tags = {
        Environment = "dev"
        ManagedBy   = "Terraform"
      }
    
      instance_names = ["web-01", "web-02"]
    }
    
    resource "aws_instance" "web" {
      count = length(locals.instance_names)
    
      tags = merge(locals.common_tags, { Name = locals.instance_names[count.index] })
      # ...
    }
What is the difference between Variables and Local Values?
  • **Variables:** Inputs to a module or the root configuration. Their values are typically provided from outside the configuration (command line, `.tfvars`, env vars).
  • **Local Values:** Named expressions *within* a module or the root configuration. Their values are computed from other variables, resource attributes, or expressions defined within the same scope. They cannot be set from outside.
What is the difference between a state file and a plan file?
  • **State File (`.tfstate`):** Records the actual state of the infrastructure that Terraform is currently managing. It's the source of truth for the deployed resources.
  • **Plan File (`.tfplan`):** A binary file generated by `terraform plan -out=planfile`. It contains the proposed changes (create, update, delete) that Terraform will make to achieve the desired state. It's a snapshot of the execution plan at a specific point in time. You can pass a plan file to `terraform apply` to ensure you apply the exact plan that was generated.
What is the purpose of the `terraform workspace` command?
  • `terraform workspace` is used to manage multiple distinct state files for a single Terraform configuration. Workspaces allow you to manage different environments (e.g., dev, staging, prod) or separate instances of the same infrastructure pattern using the same configuration code. Each workspace has its own independent state file.
When would you use workspaces?
  • To manage multiple environments (dev, staging, prod) using the same configuration.
  • To manage multiple instances of a reusable module (though using `for_each` with a map of configurations is often preferred for this).
What are the risks or downsides of using workspaces?
  • Workspaces provide isolation for the state file, but they don't provide isolation for the configuration code itself. Changes to the configuration affect all workspaces.
  • Managing complex logic within the configuration to handle differences between workspaces (e.g., using `count` with conditional logic based on the workspace name) can become cumbersome.
  • Can sometimes lead to confusion if not used carefully.
What are different ways to manage multiple environments without using workspaces?
  • Using separate directories for each environment, each with its own root configuration and state file.
  • Using a modular approach where environment-specific configurations call reusable modules, and each environment's root configuration has its own state file. This is often considered a cleaner approach than relying heavily on workspaces for significant environmental differences.
What is the Terraform Cloud/Enterprise Remote Execution?
  • Remote Execution in Terraform Cloud/Enterprise allows you to run `terraform plan` and `terraform apply` on HashiCorp's infrastructure or your own agents, rather than on your local machine. This provides a consistent and controlled environment for execution, integrates with version control, and centralizes state management.
What is the difference between provisioning and configuration management?
  • **Provisioning:** Setting up the basic infrastructure resources (VMs, networks, storage, etc.). (Terraform excels here).
  • **Configuration Management:** Installing, configuring, and managing software and services *on* the provisioned infrastructure. (Chef, Puppet, Ansible excel here).
How can Terraform integrate with configuration management tools?
  • Terraform can provision the infrastructure and then trigger configuration management tools (like Ansible or Chef) to configure the instances using provisioners (less recommended) or by passing information (like IP addresses) as outputs to the configuration management tool.
What is the purpose of the `terraform output -json ` command?
  • This command retrieves the value of a specific output in JSON format. This is useful for scripting or integrating Terraform outputs into other tools or pipelines.
    terraform output -json instance_public_ip
How can you validate a Terraform configuration before applying it?
  • `terraform validate`: Checks syntax and basic configuration validity.
    terraform validate
  • `terraform fmt`: Formats the code for consistency.
    terraform fmt
  • `terraform plan`: Generates an execution plan, which is the best way to see what changes Terraform *would* make. Reviewing the plan output is crucial before applying.
    terraform plan
  • Using static analysis tools or linters specific to HCL.
What is the state backend configuration `force_unlock`? When would you use it?
  • `force_unlock` is a subcommand of `terraform state unlock` (not a backend configuration argument itself, though related to locking). If a state lock fails to clear automatically (e.g., due to a crashed process), you can use `terraform state unlock ` to manually release the lock. The `--force` flag is used to bypass safety checks and force the unlock. Use with extreme caution, as forcing an unlock when another process is still running can lead to state corruption.
    terraform state unlock -force 
How do you manage different provider versions in Terraform?
  • You can specify required provider versions in the `terraform` block.
    terraform {
      required_providers {
        aws = {
          source  = "hashicorp/aws"
          version = "~> 4.0" # Use a version constraint
        }
      }
    }
  • `terraform init` will download the specified version. The `.terraform.lock.hcl` file locks the exact version.
What are the benefits of using version constraints for providers and modules?
  • Ensures consistency across team members.
  • Prevents unexpected changes or breakages caused by automatic updates to newer, potentially incompatible versions.
  • Allows you to control when you upgrade dependencies.
What is the difference between a variable of type `list` and `set`?
  • `list`: An ordered collection of values. Elements are accessed by index. Can contain duplicate values.
  • `set`: An unordered collection of unique values. Cannot contain duplicate values. Elements are accessed by value.
What is the difference between a variable of type `map` and `object`?
  • `map`: An unordered collection of key-value pairs where all values must be of the *same* type.
  • `object`: An unordered collection of key-value pairs where values can be of *different* types. You must define the schema (attribute names and types) for an object.
Explain the concept of implicit destruction and creation in Terraform.
  • When you change an argument of a resource that cannot be updated in place by the provider, Terraform will plan to *destroy* the existing resource and *create* a new one with the updated configuration. This is implicit destruction and creation. You can control this behavior with the `create_before_destroy` lifecycle argument.
How do you handle secrets when using environment variables with Terraform?
  • While using `TF_VAR_` is a way to pass secrets, they might still be visible in process lists or command history. For sensitive secrets, using a dedicated secrets manager integrated with Terraform is generally a more secure approach.
What is the difference between a null_resource and a local_file resource?
  • `null_resource`: A resource that does nothing but allows you to define arbitrary actions using provisioners (`local-exec`, `remote-exec`) that depend on other resources or can be triggered by changes to certain inputs (`triggers`). It's often used to run scripts *after* a resource is created or before it's destroyed.
    resource "null_resource" "configure_instance" {
      depends_on = [aws_instance.web_server]
    
      provisioner "local-exec" {
        command = "echo ${aws_instance.web_server.public_ip} >> inventory.txt"
      }
    }
  • `local_file`: A resource provided by the `local` provider that manages files on the local filesystem where Terraform is being run. It can create, update, or delete files.
    resource "local_file" "inventory" {
      filename = "inventory.txt"
      content  = "Web Server IP: ${aws_instance.web_server.public_ip}"
    }
How do you manage sensitive output values?
  • Mark the output as `sensitive = true`.
    output "database_password" {
      description = "The password for the database"
      value       = random_password.db_password.result
      sensitive   = true
    }
  • Sensitive outputs are redacted in the console output of `terraform plan` and `terraform apply`. However, they are still stored in the state file (which should be secured). In Terraform Cloud/Enterprise, sensitive outputs are also redacted in the UI.
What is the `taint` state command replacement?
  • The recommended replacement for `terraform taint ` is `terraform apply -replace= `. This command tells Terraform to plan to replace the specified resource during the apply operation.
    terraform apply -replace=aws_instance.web_server
What is the purpose of the `-target` flag? When should you use it?
  • The `-target= ` flag tells Terraform to only perform operations on the specified resource(s) and their dependencies.
  • **Use Cases:** Debugging, recovering from errors involving a specific resource.
  • **Caution:** Avoid using `-target` for routine operations in shared environments, as it can lead to state file inconsistencies or resource drift if not used carefully. It bypasses the full graph analysis.
    terraform apply -target=aws_instance.web_server
What is the purpose of the `-refresh=false` flag?
  • The `-refresh=false` flag disables the state refresh step during `terraform plan` or `terraform apply`. This means Terraform will rely solely on the current state file without querying the providers for the actual state of the infrastructure.
  • **Use Cases:** Debugging, working offline (though less common).
  • **Caution:** Using this flag can lead to applying a plan based on outdated or incorrect state information, potentially causing unexpected changes or errors. Use with extreme caution.
    terraform plan -refresh=false
What is the difference between a resource and a data source?
  • **Resource:** Declares an infrastructure object to be created, updated, or deleted and managed by Terraform.
  • **Data Source:** Fetches information about an existing infrastructure object or external data to be used in the configuration. It does not manage the lifecycle of the object it queries.
What is the significance of the `source` argument in a module block?
  • The `source` argument specifies the location of the module's source code (local path, Git repository, Terraform Registry address, etc.). Terraform uses this to download and use the module.
How does Terraform handle provider authentication?
  • Provider authentication is configured within the `provider` block or via environment variables, shared credential files, or IAM roles/managed identities (depending on the provider and cloud). Terraform uses these credentials to authenticate with the cloud provider's API to manage resources.
What is the default behavior when a resource block is removed from a configuration?
  • When a resource block is removed from the configuration files, Terraform will detect this during the next `terraform plan` by comparing the configuration to the state file. It will propose to *destroy* the corresponding resource in the infrastructure.
What is the default behavior when an argument within a resource block is removed?
  • If an argument with a default value is removed, Terraform will revert the resource attribute to its default value (if supported by the provider API). If the argument is required and has no default, removing it will typically cause a validation error. If the argument is optional and has no default, removing it might simply remove the setting from the resource, depending on the provider.
What is the purpose of the `ignore_changes` lifecycle argument?
  • (Already covered, but worth reinforcing) It tells Terraform to ignore changes to specific attributes of a resource after it has been created.
What is the purpose of the `count.index` and `each.key`/`each.value`?
  • `count.index`: In a resource or module block using `count`, `count.index` is the zero-based index of the current instance being created (0, 1, 2, ...). Used to differentiate instances or access elements from lists.
  • `each.key`: In a resource or module block using `for_each` with a map, `each.key` is the key of the current map element.
  • `each.value`: In a resource or module block using `for_each` with a map or set, `each.value` is the value of the current map element or the current set element. Used to access the data for each instance being created.
How can you manage different environments using a modular approach?
  • Create reusable modules for common infrastructure patterns (e.g., a VPC module, an application module).
  • Create a separate root module directory for each environment (e.g., `environments/dev`, `environments/staging`, `environments/prod`).
  • Each environment's root module configures the backend (often pointing to a different state path or bucket per environment).
  • Each environment's root module calls the reusable modules, providing environment-specific variable values (often loaded from `.tfvars` files). This keeps the core logic in modules consistent while allowing environmental variations.
What is the purpose of the `terraform console` command?
  • `terraform console` provides an interactive console for evaluating expressions based on your Terraform configuration and state. You can test interpolations, access resource attributes, and perform calculations.
    terraform console
    > aws_instance.web_server.public_ip
    > var.region
    > length(aws_instance.web_server.*.id)
    > { a = 1, b = 2 }["a"]
How do you handle dependencies between modules?
  • Terraform automatically infers dependencies between modules based on their inputs and outputs. If Module B uses an output from Module A as an input, Module B implicitly depends on Module A. Terraform will ensure Module A is applied before Module B.
  • You can also use `depends_on` on the module block itself for explicit dependencies if necessary, though implicit dependencies are preferred.
What is the difference between a required provider and a required version?
  • `required_providers`: Declares which providers are required by your configuration and their source (e.g., `hashicorp/aws`). This is mandatory.
  • `version`: A constraint on the version of the required provider. This is highly recommended to ensure consistent behavior.
How do you perform a "dry run" in Terraform?
  • The `terraform plan` command acts as a dry run. It shows you exactly what changes Terraform *would* make without actually applying them. Reviewing the plan is essential before proceeding with `terraform apply`.
What are the benefits of using Terraform Cloud/Enterprise?
  • Centralized state management with locking.
  • Remote execution for consistent environments.
  • Version control integration (VCS-driven workflows).
  • Team and access control.
  • Policy as Code (Sentinel).
  • Private module and provider registries.
  • Cost estimation.
  • Structured logging and history of runs.
What is the difference between `terraform destroy` and `terraform apply -destroy`?
  • `terraform destroy`: The standard command for destroying all resources managed by the current configuration.
  • `terraform apply -destroy`: Generates and executes a destroy plan. This is functionally equivalent to `terraform destroy` but allows you to use options applicable to `apply`, such as `-auto-approve` or `-target`.
How do you handle resource lifecycle management in Terraform?
  • Terraform manages the full lifecycle: create, read, update, and delete (CRUD).
  • `terraform apply` handles create, update, and read (refresh).
  • `terraform destroy` handles delete.
  • The state file tracks the current state.
  • `lifecycle` blocks allow customization of update and delete behavior.
What is the purpose of the `output` block's `value` argument?
  • The `value` argument in an `output` block specifies the data that will be exposed as an output. This is typically an expression that references resource attributes, variables, or local values.
How can you pass data between modules?
  • Modules accept input variables.
  • Modules can define output values.
  • The calling module provides values for the child module's input variables and can access the child module's outputs.
  • # In the child module (modules/vpc/outputs.tf)
    output "vpc_id" {
      value = aws_vpc.main.id
    }
    
    # In the root module (main.tf)
    module "vpc" {
      source = "./modules/vpc"
      # ... inputs
    }
    
    resource "aws_subnet" "app_subnet" {
      vpc_id = module.vpc.vpc_id # Accessing the output from the vpc module
      # ...
    }
What is the difference between a provisioner and a connection block?
  • **Provisioner:** Defines actions to be executed *after* a resource is created or before it is destroyed.
  • **Connection Block:** Configures how Terraform will connect to a remote resource (usually an instance) to run remote provisioners (like `remote-exec`). It specifies connection details like `type` (ssh, winrm), `user`, `password`, `private_key`, `host`, etc.
What is the purpose of the `terraform graph -type=plan` command?
  • This command generates a graph representing the operations in a previously saved plan file (`.tfplan`). This is useful for visualizing the execution order of changes in a specific plan, especially for complex configurations.
How do you handle the situation where a resource needs to be updated, but the update requires downtime?
  • If the provider supports `create_before_destroy` for the specific change, use the `lifecycle` block with `create_before_destroy = true`. Terraform will create the new resource before deleting the old one, minimizing downtime.
  • If `create_before_destroy` isn't supported or appropriate, you might need to plan for a maintenance window, potentially using blue/green deployment strategies managed outside of this specific Terraform apply.
What is the purpose of the `terraform show` command?
  • `terraform show` reads the state file and outputs a human-readable representation of the resources and their attributes managed by Terraform. It can also show a saved plan file.
    terraform show
    terraform show terraform.tfstate
    terraform show tfplan
How do you manage Terraform configurations in a CI/CD pipeline?
  • Store Terraform code in a version control system (Git).
  • Use a remote backend for state management.
  • Implement automated checks (linting, `terraform fmt`, `terraform validate`).
  • Run `terraform plan` in the pipeline, saving the plan file as an artifact. Review the plan.
  • On approval (manual or automated), run `terraform apply ` to apply the exact planned changes.
  • Consider using Terraform Cloud/Enterprise for integrated CI/CD workflows.
What are some best practices for writing production-ready Terraform code?
  • Use a remote backend with state locking.
  • Implement a modular structure.
  • Use version constraints for providers and modules.
  • Use variables for parameterization and avoid hardcoding values.
  • Store sensitive data in a secrets manager, not in `.tf` files or state.
  • Use `for_each` instead of `count` where applicable for collections.
  • Use the `lifecycle` block cautiously for specific needs.
  • Regularly run `terraform fmt` and `terraform validate`.
  • Thoroughly review `terraform plan` output before applying.
  • Implement CI/CD pipelines for automated testing and deployment.
  • Use clear naming conventions for resources and variables.
  • Add descriptions to variables, outputs, and resources.
  • Implement tagging policies for resources.
What is the purpose of the `terraform login` command?
  • `terraform login` is used to authenticate Terraform CLI with Terraform Cloud or Terraform Enterprise. It obtains an API token and stores it locally, allowing subsequent commands to interact with the platform.
What is the difference between a null value and an empty string in HCL?
  • `null`: Represents the absence of a value. Often used for optional arguments where you want to explicitly indicate that no value is provided.
  • `""`: An empty string. It is a valid string value, just with zero characters.
  • Providers may treat `null` and `""` differently for optional arguments.
How do you handle external data or configuration outside of Terraform?
  • Use Data Sources to fetch information from cloud providers or other services.
  • Use the `external` data source to run an external program and use its JSON output in your configuration.
  • Use `local_file` data source to read files.
  • Use `http` data source to fetch data from an HTTP endpoint.
What is the purpose of the `terraform apply -auto-approve` flag? When should you use it?
  • The `-auto-approve` flag bypasses the interactive confirmation prompt before applying a plan.
  • **Use Cases:** Automation in CI/CD pipelines.
  • **Caution:** Never use `-auto-approve` in manual workflows or without a preceding `terraform plan` step that has been reviewed. It removes a critical safety check.
What is the default state locking mechanism for the S3 backend?
  • The S3 backend typically uses DynamoDB for state locking. You need to configure a DynamoDB table and specify its name in the backend configuration.
How do you force Terraform to re-read the configuration and state without making changes?
  • `terraform plan -refresh-only`: This command performs a state refresh and then outputs the differences between the refreshed state and the configuration, without proposing any changes to the infrastructure itself. It's useful for checking for resource drift.
What is the difference between `terraform import` and managing resources with `terraform apply` from the start?
  • `terraform import`: Used for bringing *existing* infrastructure under Terraform management. Requires manual creation of the corresponding HCL code after import.
  • Managing from the start: You write the HCL code first and then use `terraform apply` to create the resources. This is the standard and recommended workflow for new infrastructure.
How do you handle destroyed resources in the state file?
  • When a resource is destroyed by `terraform destroy` or `terraform apply`, it is removed from the state file.
  • If a resource is manually deleted outside of Terraform, it will still be in the state file but marked as "tainted" or "missing" during the next refresh. Terraform will typically propose to recreate it on the next apply unless you remove it from the state using `terraform state rm`.
What is the purpose of the `terraform output` command without any arguments?
  • `terraform output` (without arguments) lists all the output values defined in your configuration and their current values after the last apply.
What is the significance of the `.tf` file extension?
  • Terraform automatically loads all files ending with `.tf` and `.tfvars` in the working directory. `.tf` files contain the main configuration (resources, providers, variables, outputs, locals, modules).
What is the significance of the `.tfvars` file extension?
  • Terraform automatically loads variable definitions from `terraform.tfvars` and any file ending with `.auto.tfvars` in the working directory. These files are used to provide values for variables defined in your `.tf` files. You can also specify variable files explicitly using the `-var-file` flag.
How do you handle different operating systems or architectures in your Terraform code?
  • This is typically handled by the provider (e.g., selecting the correct AMI for AWS based on OS).
  • Within your configuration, you might use variables or conditionals based on input variables to select appropriate configurations (e.g., different instance types, different software packages to install via configuration management).
What are some common Terraform errors you might encounter?
  • Syntax errors in HCL.
  • Provider authentication errors.
  • Resource not found (often due to drift or incorrect resource addresses).
  • Dependency cycles.
  • State locking issues.
  • API rate limiting from the cloud provider.
  • Insufficient permissions for the configured credentials.
  • Errors during provisioning (if using provisioners).
  • Issues with module sources or versions.
How do you troubleshoot Terraform errors?
  • Read the error message carefully – Terraform usually provides helpful context.
  • Use `terraform validate` to check syntax.
  • Use `terraform plan` to see the proposed changes and identify issues before applying.
  • Enable detailed logging by setting the `TF_LOG` environment variable (e.g., `TF_LOG=DEBUG`).
  • Check the state file (`terraform show`) to compare it with the actual infrastructure.
  • Verify provider authentication and permissions.
  • Check the provider documentation for the specific resource and arguments.
  • Use `terraform console` to test expressions.
  • Simplify the configuration to isolate the problem.
What is the purpose of the `backend "local"` configuration?
  • The `local` backend stores the state file on the local filesystem where Terraform is run. This is the default behavior if no backend is configured. It is **not recommended** for team environments due to the risks of concurrency issues and lack of collaboration features.
What is the purpose of the `required_version` argument in the `terraform` block?
  • The `required_version` argument specifies the minimum and/or maximum version of the Terraform CLI itself that is compatible with your configuration. This ensures that everyone using the configuration is using a compatible version of Terraform.
    terraform {
      required_version = ">= 1.0.0, < 2.0.0" # Example constraint
      # ...
    }
How do you upgrade Terraform providers?
  • Update the version constraint in the `required_providers` block in your configuration files.
  • Run `terraform init -upgrade`. This will download the specified newer version of the provider and update the `.terraform.lock.hcl` file.
  • Run `terraform plan` to see if the provider upgrade introduces any changes to your infrastructure.
How do you upgrade Terraform CLI?
  • Download the new binary from the HashiCorp Terraform website.
  • Replace the existing `terraform` executable with the new one.
  • Check the `required_version` constraint in your configurations to ensure compatibility.
What is the difference between a Root Module and a Child Module?
  • **Root Module:** The top-level directory containing your main Terraform configuration files (`.tf`). This is where you run Terraform commands (`init`, `plan`, `apply`). It often calls child modules.
  • **Child Module:** A reusable collection of `.tf` files in a separate directory or source. It is called by a root module or another child module. Child modules have their own variables and outputs but do not have a backend configuration directly within the module itself (the backend is configured in the root module).
What is the purpose of the `terraform graph -type=plan` command? (Duplicate, but good to reinforce)
  • This command generates a visual representation of the execution plan contained in a saved plan file. It helps visualize the order of operations for a specific set of changes.
How do you manage different configurations for the same module?
  • Pass different values to the module's input variables from the calling module.
  • If using `for_each` with a module, the map or set used with `for_each` can contain configuration data for each instance.
What is the difference between `terraform state mv` and moving resources manually in the configuration files?
  • Moving resources manually in the configuration files changes the resource's address in the HCL code. Without `terraform state mv`, Terraform would see this as deleting the old resource and creating a new one with the new address, even if the underlying infrastructure is the same.
  • `terraform state mv` updates the state file to reflect the change in the resource's address in the HCL code, allowing Terraform to recognize the resource at its new location in the configuration and manage it correctly.
What is the purpose of the `terraform output -state=` command?
  • This command allows you to retrieve output values from a specific state file, rather than the default state file in the current working directory. This is useful when working with multiple state files or backups.
What are the benefits of using a structured approach to your Terraform project (e.g., using modules and separate environments)?
  • Improved organization and readability.
  • Increased reusability of code through modules.
  • Reduced duplication.
  • Easier management of different environments.
  • Better collaboration among team members.
  • Simplified maintenance and updates.
How do you handle sensitive data in your Terraform state file?
  • The state file *will* contain sensitive data if your resources or outputs include it (e.g., database passwords, API keys).
  • **Best Practice:** Use a secrets management system (Vault, Secrets Manager, etc.) to store secrets and fetch them using data sources or integrations *during* the apply process, rather than storing them as literal values in variables or outputs.
  • Use encrypted state backends where available (e.g., S3 with server-side encryption, Terraform Cloud/Enterprise).
  • Restrict access to the state file.
What is the purpose of the `terraform workspace select ` command?
  • This command switches the current working directory's workspace to the specified name. Subsequent `terraform plan` and `terraform apply` commands will use the state file associated with that workspace.
What is the purpose of the `terraform workspace new ` command?
  • This command creates a new workspace with the specified name and switches to it. It also creates a new, empty state file for that workspace.
What is the purpose of the `terraform workspace list` command?
  • This command lists all available workspaces for the current configuration, indicating the currently selected workspace.
What is the purpose of the `terraform workspace delete ` command?
  • This command deletes the specified workspace and its associated state file. You cannot delete the currently selected workspace or a workspace that still contains resources.
What is the default workspace?
  • The default workspace is named `default`. When you initialize a new Terraform directory without specifying a workspace, it uses the `default` workspace.
How do you manage the lifecycle of a resource created with `count` or `for_each`?
  • If you decrease the `count` or remove an item from the map/set used with `for_each`, Terraform will plan to destroy the corresponding resource instance(s).
  • If you increase the `count` or add an item to the map/set, Terraform will plan to create the new resource instance(s).
  • Changes to attributes within the resource block will apply to all instances or the specific instance identified by `each.key`.
What is the difference between a required variable and an optional variable?
  • **Required Variable:** A variable defined without a `default` value. Terraform will require a value to be provided for this variable (via command line, `.tfvars`, or environment variable) before it can proceed.
  • **Optional Variable:** A variable defined with a `default` value. If no value is provided externally, Terraform will use the default value.
How do you make a variable required?
  • Define the variable without a `default` argument.
    variable "instance_ami" {
      description = "The AMI ID for the instance"
      type        = string
    }
How do you make a variable optional?
  • Define the variable with a `default` argument.
    variable "instance_type" {
      description = "The type of EC2 instance to launch"
      type        = string
      default     = "t2.micro"
    }
What is the purpose of the `description` argument in variable and output blocks?
  • The `description` argument provides a human-readable explanation of the variable's purpose or the output's value. This documentation is displayed when running `terraform plan` or `terraform apply` (for variables) and `terraform output` (for outputs). It is highly recommended for making your configurations understandable.
How do you refer to resources managed by a different Terraform configuration?
  • You can use the `terraform_remote_state` data source to read the state file of another Terraform configuration. This allows you to obtain outputs from one configuration and use them as inputs in another.
    data "terraform_remote_state" "vpc" {
      backend = "s3"
      config = {
        bucket = "my-terraform-state-bucket"
        key    = "vpc/terraform.tfstate"
        region = "us-east-1"
      }
    }
    
    resource "aws_subnet" "app_subnet" {
      vpc_id = data.terraform_remote_state.vpc.outputs.vpc_id
      # ...
    }
What are the considerations when using `terraform_remote_state`?
  • The remote state file must be accessible by the configuration reading it.
  • This creates a dependency between the two configurations. The configuration providing the outputs must be applied before the configuration consuming them.
  • Changes in the providing configuration's outputs will require a refresh in the consuming configuration.
What is the purpose of the `null_data_source`?
  • The `null_data_source` is a data source that does nothing but allows you to define arbitrary attributes based on input variables or other data. It can be useful for transforming data or creating complex data structures that are then used elsewhere in the configuration.
How do you manage Terraform state for multiple environments using separate directories?
  • Create a top-level directory (e.g., `infrastructure`).
  • Inside, create directories for each environment (e.g., `infrastructure/dev`, `infrastructure/staging`, `infrastructure/prod`).
  • Each environment directory is a separate root module.
  • Each environment's root module has its own `backend` configuration pointing to a unique state file location (e.g., `s3://my-state-bucket/dev/terraform.tfstate`, `s3://my-state-bucket/staging/terraform.tfstate`).
  • Share reusable code using modules (e.g., `infrastructure/modules`).
  • Run Terraform commands from within the specific environment directory.
What is the purpose of the `terraform` block's `cloud` configuration?
  • The `cloud` block is used to configure integration with Terraform Cloud or Terraform Enterprise directly within the configuration, replacing the need for a separate `backend` configuration for the platform.
    terraform {
      cloud {
        organization = "my-organization"
        workspace    = "my-workspace"
      }
      # ...
    }
How does Terraform handle drift detection in Terraform Cloud/Enterprise?
  • Terraform Cloud/Enterprise can be configured to automatically perform `terraform plan` runs on a schedule or when changes are pushed to the connected version control repository. This helps detect drift and provides visibility into the current state of your infrastructure compared to your configuration.
What is the purpose of the `override` file (`override.tf`, `override.tf.json`, etc.)?
  • Override files allow you to override argument values or add new arguments to blocks defined in other configuration files without modifying the original files. This can be useful for making minor, temporary adjustments or for applying environment-specific settings without changing common module code. Use with caution, as it can make configurations harder to understand if overused.
What is the order of processing configuration files by Terraform?
  • Terraform loads all `.tf` and `.tfvars` files in the working directory in alphabetical order.
  • Within a directory, files are processed alphabetically.
  • The order of blocks within a file generally doesn't matter, as Terraform builds a dependency graph.
  • Override files are processed after the regular configuration files, allowing them to override settings.
What is the purpose of the `validate_variables` argument in the `terraform` block?
  • `validate_variables = true` (default) tells Terraform to validate that all required variables have been provided and that the provided values match the declared types. Setting it to `false` disables this validation, which is generally not recommended.
How can you ensure consistency and prevent unauthorized changes to infrastructure managed by Terraform?
  • Use a remote backend with state locking.
  • Implement strict access controls to the state file and the remote backend.
  • Use a CI/CD pipeline where all changes go through a review and automated apply process.
  • Use Policy as Code (Sentinel in Terraform Cloud/Enterprise) to enforce rules.
  • Restrict manual access to the cloud provider console for resources managed by Terraform.
  • Regularly run `terraform plan` to detect drift.
What is the purpose of the `terraform init -backend-config` flag?
  • This flag allows you to provide backend configuration arguments from the command line or a file, rather than hardcoding them in the `backend` block. This is useful for configuring the backend dynamically or for providing sensitive backend credentials via environment variables or a secure file.
    terraform init -backend-config="bucket=my-state-bucket" -backend-config="key=prod/terraform.tfstate"
How do you manage Terraform configurations for multiple applications in a single repository?
  • Use a structured directory layout, perhaps with a top-level `environments` directory and an `applications` directory.
  • Each application might have its own set of modules or root configurations.
  • Environments can have root configurations that call modules for specific applications.
  • Use separate state files for different applications or environments to maintain isolation.
What is the purpose of the `terraform apply -lock=false` flag?
  • This flag disables state locking for the current `apply` operation.
  • **Caution:** Use this flag with extreme caution, only when you are absolutely certain no other process is accessing the state file. Disabling locking can lead to state file corruption if concurrent operations occur. It is generally not recommended.
How do you handle the case where a resource creation fails during `terraform apply`?
  • Terraform will stop the apply process and report the error.
  • The state file will be partially updated to reflect the resources that were successfully created or modified before the failure.
  • Troubleshoot the error (check logs, provider documentation, permissions).
  • Fix the issue in your configuration or the environment.
  • Run `terraform plan` again to see the new plan (it will attempt to create the failed resource and potentially clean up inconsistent state).
  • Run `terraform apply` to resume the process.
  • You might need to use `terraform state rm` or `terraform apply -replace` in some cases to resolve complex inconsistencies.
What is the purpose of the `check_constrained_type` argument in variable blocks?
  • `check_constrained_type = true` (default for Terraform 1.3+) enables validation that values assigned to a variable match the declared type constraints (e.g., ensuring a string is provided if `type = string`). Setting it to `false` disables this validation. It's generally best to leave this enabled.
What is the purpose of the `force_new_remote_state` argument in the `backend` block?
  • `force_new_remote_state = true` is used when changing the backend configuration. It tells Terraform to ignore any existing state data in the new backend destination and write the current in-memory state to it instead. Use with extreme caution, as it can overwrite existing state and potentially cause resources to be lost from management.
How do you manage different versions of your Terraform configurations themselves?
  • Use a version control system like Git. Each commit represents a version of your infrastructure code.
  • Use Git tags to mark specific releases or versions of your infrastructure deployments.
  • Integrate with CI/CD pipelines to build and deploy specific commits or tags.