1. Explain the difference between module sources in Terraform. When would you use a local module versus a remote module, and what are the trade-offs?
Local modules are stored in your repository (e.g., ./modules/vpc) and are version-controlled with your code, making them ideal for internal standardization and rapid iteration. Remote modules from registries (terraform.io, private registries) provide versioning, discoverability, and team sharing but require careful version pinning to prevent breaking changes. Use local modules for organization-specific patterns, remote modules for shared infrastructure components across teams or projects. Trade-offs: local modules offer speed and flexibility but poor reusability; remote modules ensure consistency and decoupling but add dependency management complexity.
2. You're debugging a Terraform module that works locally but fails in CI/CD with 'module not found'. What are the most likely causes and how would you troubleshoot?
First, verify the module source path is correct relative to the working directory—CI/CD often runs from a different root than local execution. Check that remote module sources have proper credentials configured (SSH keys, git tokens) in the CI/CD environment via `terraform init -upgrade` with debug logs. Confirm `.terraform/modules` is not cached from previous runs or gitignored. Run `terraform init -backend=false` to isolate module loading issues from backend problems. Use `TF_LOG=DEBUG terraform init` to inspect exact URL resolution and authentication attempts.
3. Design a module structure for a multi-tenant SaaS platform where each tenant has isolated VPC, RDS, and application infrastructure. What are the key module boundaries and how would you parameterize them?
Create three primary modules: network (VPC, subnets, route tables, security groups), database (RDS instance, parameter groups, backups), and application (ECS, ALB, IAM roles). Parameterize each by tenant_id, environment (dev/prod), and region. Use a root module or wrapper module to compose these for each tenant deployment, accepting tenant_config as a variable or data source. Implement module outputs (vpc_id, rds_endpoint, alb_dns) for cross-module references. For 100+ tenants, avoid creating separate state files per tenant—use workspaces or external data sources to manage configuration; use a single state with tenant_id as a key to prevent state bloat and drift.
4. What is module versioning, and how do you enforce semantic versioning in a private module registry? Provide a practical example.
Module versioning allows consuming modules to pin specific releases (e.g., `source = "git::ssh://git@github.com/org/terraform-aws-vpc.git?ref=v2.1.0"`), preventing unintended breaking changes. In a private registry (Terraform Cloud, Artifactory, or git tags), publish releases as git tags following semver (v1.2.3): major for breaking changes (variable/output renames), minor for new features (optional variables), patch for fixes. Example: if you add a required variable `enable_nat_gateway`, bump to v2.0.0; if you add an optional variable `nat_gateway_count` with default, bump to v1.1.0. Enforce via CI/CD by requiring tag-based releases and preventing direct main branch consumption in production root modules.
5. You're on-call and a module update in production causes 50 EC2 instances to be recreated. How would you have prevented this, and what's your immediate remediation strategy?
Prevention: always pin module versions in production (use exact versions like `v2.1.4`, not `>= v2.0`) and test major updates in staging first with `terraform plan` before applying. Use `lifecycle { create_before_destroy = true }` to minimize downtime, or implement blue-green deployments for critical infrastructure. Immediate remediation: identify which module change caused the recreation using `terraform plan -detailed-exitcode` and git diff, then either revert the module version in code and re-apply, or use `terraform refresh` followed by targeted `terraform apply -target` to skip unaffected resources. Finally, conduct a post-incident review to add pre-production testing gates in CI/CD.
6. How do you handle sensitive variables (database passwords, API keys) within Terraform modules? What's the difference between passing them as variables versus using AWS Secrets Manager or similar?
Pass sensitive data as `sensitive = true` variables in module inputs, never hardcode or store in module defaults; use `terraform.tfvars` (gitignored) locally or Terraform Cloud/Enterprise for secure variable storage. For cross-team or long-lived secrets, integrate AWS Secrets Manager (via `data "aws_secretsmanager_secret_version"`), HashiCorp Vault, or Parameter Store to externalize secret rotation. Passing as variables offers fine-grained control per deployment but requires careful credential handling in CI/CD; external managers decouple rotation from Terraform and enforce audit trails. Mark module variables with `sensitive = true` to redact values from logs: `variable "db_password" { type = string; sensitive = true }`.
7. Describe the difference between module composition (nesting modules) and module inheritance. When is deep nesting problematic?
Module composition chains modules together: a root module calls network module, which doesn't call other modules, while a wrapper module might call network + database modules. There is no true inheritance in Terraform, but you can approximate it by creating a root module that standardizes calls to child modules with consistent values. Deep nesting (root → wrapper → network → subnet-specific modules) becomes problematic because it obscures resource dependencies, makes debugging harder (terraform plan output is complex), and introduces variable forwarding overhead. Best practice: limit nesting to 2 levels (root → child), and use a single wrapper module per pattern rather than a chain.
8. Design a module that enables different cloud providers (AWS, Azure, GCP) for the same infrastructure component (e.g., a VM). What challenges does this create, and is it worth it?
Use a `provider` variable to conditionally instantiate provider-specific resources: `count = var.provider == "aws" ? 1 : 0` for AWS resources, similar for Azure/GCP. This quickly becomes unmaintainable because APIs differ substantially (EC2 vs. Azure VMs, security group vs. NSGs), requiring extensive conditional logic and increasing test burden. A better approach: create separate modules per provider (terraform-aws-vm, terraform-azure-vm) and let the root module choose which to call based on var.provider. Challenges: provider-specific state, authentication, and feature parity increase complexity exponentially. It's usually not worth it unless you're building a multi-cloud abstraction layer with strict feature constraints; instead, use separate Terraform workspaces or repositories per cloud.
9. Explain how module outputs work and provide an example where you'd use output chaining across multiple modules. What are the risks?
Module outputs expose resource attributes for consumption by the calling module: a VPC module outputs vpc_id and subnet_ids, which a compute module uses in its security_group.vpc_id. Output chaining: root module calls network module, extracts its vpc_id, passes it to application module. Example: `module "network" { source = "./modules/network" }` then `module "app" { source = "./modules/app"; vpc_id = module.network.vpc_id }`. Risks: tight coupling reduces modularity (changing network module's output breaks app module), hidden dependencies complicate refactoring, and state drift between modules can cause orphaned resources. Mitigate by documenting dependencies and using clear naming conventions; prefer loose coupling via data sources when possible (e.g., `data "aws_vpc" { filter { name = "tag:Name" } }`).
10. You're refactoring a 2000-line monolithic root module into smaller modules. How do you extract and test modules without breaking production, and what's your state migration strategy?
Create new modules in parallel (e.g., ./modules/vpc, ./modules/compute) without touching production state initially. Write local tests using `terraform plan -out=plan.tfplan` on a feature branch against a non-prod environment. Once tested, use `terraform state mv` to migrate resources from the monolithic module to new modules in-place (e.g., `terraform state mv 'aws_vpc.main' 'module.network.aws_vpc.main'`), then verify with `terraform plan` shows zero changes. Perform this migration in a non-prod environment first, then schedule a maintenance window for production. Use git reflog and state backups to enable rollback. Alternatively, use Terraform's import functionality if state mv causes issues: `terraform import module.network.aws_vpc.main vpc-12345`.
11. What are the trade-offs between using a large, feature-rich module versus multiple small, single-purpose modules?
Large modules (e.g., terraform-aws-eks with VPC, node groups, add-ons) reduce boilerplate and ensure consistency but increase coupling, slow plan/apply times, and force upgrades even when you only need one feature. Small modules (VPC, node-group, add-on as separate modules) offer flexibility and reusability but require more composition code, create more state files to manage, and fragment responsibility. Best practice: aim for medium-sized, cohesive modules around a functional boundary (VPC module handles network, not compute). Size by use case—if 80% of users need feature X and Y together, bundle them; if 20% need only Y, split them. Monitor module adoption and complexity metrics (input variable count, resource count) to detect bloat.
12. How would you implement a module that applies consistent tagging and compliance policies (encryption, logging) across all resources without hardcoding them into each module?
Use a locals block in the root module to define standard tags, then pass them via a `common_tags` variable to all child modules: `common_tags = merge(var.environment_tags, var.corporate_tags)`. In each module, apply tags uniformly: `tags = merge(local.common_tags, { Name = var.resource_name })`. For compliance policies (encryption defaults, logging buckets), expose optional variables with secure defaults: `variable "enable_encryption" { type = bool; default = true }`, `variable "log_bucket_name" { type = string; default = data.aws_s3_bucket.logging.id }`. Use dynamic blocks to conditionally attach logging: `dynamic "logging" { for_each = var.enable_logging ? [1] : []; content { } }`. Enforce via policy-as-code (Sentinel in TFC, Checkov) that scans all module calls.
13. Explain how Terraform's dependency graph works and how it differs from explicit depends_on declarations. When should you use depends_on versus relying on implicit dependencies?
Terraform automatically builds a dependency graph by parsing resource references (e.g., aws_instance.web.id used in aws_security_group_rule.allow_web), allowing it to parallelize and order operations correctly. Explicit depends_on is a meta-argument that creates artificial dependencies when implicit ones don't exist, such as when a resource needs another to complete but doesn't directly reference it. You should use depends_on only when there's a hidden dependency—for example, a Lambda function that requires an IAM role to exist first but doesn't reference the role's ARN in its configuration. Overusing depends_on reduces parallelism and makes modules harder to refactor because the dependency logic becomes opaque.
14. You're designing a module that must support both count and for_each meta-arguments for users to choose how they iterate. What are the structural and testing challenges, and is this flexibility worth implementing?
Supporting both count and for_each requires separate output patterns: count uses output indexing (module.example[0].id) while for_each uses keys (module.example["key1"].id), forcing users to adapt their consuming code to whichever pattern the module implements. Testing becomes complex because you must validate both iteration modes produce identical resource behavior and state structure. In practice, this dual-mode flexibility is rarely worth the maintenance burden; best practice is to document a single recommended iteration pattern and accept that power users can wrap the module if they need a different approach. If you must support both, use clear documentation and separate test suites, but expect integration issues when users mix patterns across their codebase.
15. Describe a scenario where using terraform_data as a trigger mechanism is preferable to using null_resource with triggers. What problem does terraform_data solve?
terraform_data was introduced to replace the common pattern of using null_resource with a triggers argument solely to force re-runs on input changes. null_resource required the null provider as a dependency, whereas terraform_data is a built-in resource in Terraform 1.4+ that explicitly documents its purpose: tracking arbitrary input values and triggering dependent resources when those inputs change. For example, if you need to re-run a local-exec provisioner whenever a list of configuration files changes, terraform_data with an input argument is cleaner and more semantically clear than null_resource. This improves readability and eliminates an external provider dependency, making modules more portable and reducing potential version conflicts.
16. You have a module that generates 200+ lines of computed locals to construct complex resource arguments. How would you refactor this to improve maintainability and testability?
Extract the complex logic into separate local files or even a dedicated module that returns structured data, using Terraform's type system to document the shape of computed values. Use locals only for intermediate calculations and keep them grouped by purpose; if locals span more than 50 lines, you've likely crossed into logic that deserves abstraction. Consider moving computation into external data sources or custom scripts if the logic becomes business-domain-specific or requires versioning independently from the module. Test the output structure using Terraform's testing framework (terraform test, available in 1.6+) or by writing a simple root module that consumes the local outputs and validates their shape, ensuring refactors don't break consumers.
17. Explain the difference between using a variable default value and using Terraform's coalesce or try functions to provide fallback values in a module. When is each appropriate?
A variable default value is static and set at variable declaration time, making it immediately visible in documentation and IDE hints; it's appropriate for safe, unchanging defaults like instance counts or common region names. The coalesce and try functions allow dynamic fallbacks based on runtime logic—for example, coalesce(var.custom_name, aws_instance.default.tags["Name"]) uses a computed value if the variable is null, which is useful when you want a default derived from other infrastructure. Use variable defaults for simple, predictable values that don't depend on other resources; use try and coalesce when you need conditional logic that depends on infrastructure state or external inputs that might not exist. Mixing both can make module behavior confusing, so document clearly which approach you're using for each logical concern.
18. Design a module that manages a Kubernetes namespace with RBAC, network policies, and resource quotas. How would you structure the variables and outputs to keep the module reusable across different security requirements?
Create a root variables object (kubernetes_namespace_config) with nested blocks for rbac, network_policies, and resource_quotas, each with their own type definitions and optional flag if some organizations don't require them. Use for_each loops to iterate over roles, policies, and quota definitions passed as maps, allowing consumers to define only what they need without module modifications. Output the namespace name, created roles, and network policy IDs separately so consumers can reference them for additional Kubernetes resources; avoid outputting the entire resource state as it couples consumers to internal structure. This approach lets you add new sub-modules (e.g., pod security policies) without breaking existing usage, and consumers can selectively enable features by providing or omitting their respective input blocks.
19. A module uses dynamic blocks to construct complex argument structures. Under what conditions does this pattern become an anti-pattern, and what's a better alternative?
Dynamic blocks are anti-patterns when they obscure the actual resource configuration, making code harder to read or when the number of dynamic blocks exceeds two or three per resource; at that point, the resource shape is no longer immediately understandable. They're also problematic when the dynamic logic depends on deeply nested locals or external data sources, because troubleshooting becomes difficult and small input changes can have cascading effects. A better alternative is to pre-compute the argument structure in a local variable or external data source, then pass it to the resource as a static argument; for example, instead of a dynamic block, build a list of security group rules in a local and use for_each on that pre-computed list. This keeps resource declarations readable and moves the complexity into a clearly separated calculation block that can be tested and understood independently.
20. Explain how Terraform handles provider version constraints in modules and root configurations. If a module pins provider version 4.x and the root configuration requires 5.x, what happens and how would you resolve it?
Terraform uses the most restrictive version constraint across all modules and the root configuration; if a module requires provider >= 4.0, < 5.0 and the root requires >= 5.0, Terraform init will fail with a version conflict error and refuse to proceed. Resolution requires either updating the module's required_providers block to accept the newer provider version, or downgrading the root configuration constraint—you cannot run with conflicting version pins. The best practice for module authors is to use loose constraints (e.g., >= 4.0 without an upper bound) unless there's a known breaking change, allowing root configurations flexibility to upgrade providers independently. Always test modules against the minimum and maximum supported provider versions in CI/CD to catch compatibility issues early.
21. You're building a module that needs to validate user input (e.g., ensuring a subnet CIDR doesn't overlap with existing VPC CIDRs). How would you implement this validation, and what are the limitations?
Use variable validation blocks (available in Terraform 0.13+) to enforce constraints like regex patterns, allowed values, or custom conditions using the condition argument with error_message; for example, validation { condition = cidrhost(var.subnet_cidr, 0) != null error_message = "Invalid CIDR format" }. However, Terraform validation runs at plan time and cannot make external API calls, so it cannot check against live infrastructure state like existing VPC CIDRs or API rate limits. For complex runtime validations, use a local-exec provisioner to call external scripts or APIs, or implement the check as a separate data source that fails if constraints are violated; note this adds complexity and can introduce non-deterministic behavior. Document clearly what validations the module performs and which checks must be done externally by the operator, keeping the module focused on Terraform-native validations.
22. Describe a scenario where using a module source as a Git branch (e.g., git::https://github.com/org/module.git?ref=feature-branch) in production is necessary, and explain the risks and mitigation strategies.
Using feature branches in production is rarely necessary and extremely risky; it's sometimes justified during emergency hotfixes when a release version would be too slow, but only if that branch is thoroughly tested and immediately promoted to a release tag. The risks include: unfinished code merging into production unexpectedly, losing track of which code version is deployed, difficulty rolling back if the branch is deleted, and breaking CI/CD assumptions that track releases via tags. Mitigation requires strict process controls: document the temporary branch reference with an expiration date, create alerts if the branch reference appears in production after the expiration, mandate code review and testing equal to release candidates, and automatically promote the branch to a tagged release within 24 hours. Best practice is never to use branches in production; instead, cut a release candidate tag immediately and use that, reserving branch references only for development and staging environments.
23. A module consumer is passing a sensitive variable (database password) via a .tfvars file committed to Git. As the module author, what safeguards and documentation should you implement to prevent this?
Document in the module README that sensitive variables should never be committed to version control and provide examples using environment variables, Terraform Cloud/Enterprise, or external secret stores like AWS Secrets Manager. Mark sensitive variables explicitly with sensitive = true in the variable definition, which masks their values in plan and apply output, reducing accidental exposure in logs or CI/CD console output. Consider providing a separate example module or documentation that shows how to integrate aws_secretsmanager_secret_version as a data source, allowing the module to fetch secrets at runtime instead of accepting them as inputs. However, recognize that ultimately the consumer is responsible for their secret management strategy; the module can only enforce best practices through clear documentation and by making the dangerous path (committing secrets) visibly harder through sensitive flags and examples of the secure path.
24. Explain how Terraform's moved block works and provide a real example of when you'd use it to refactor a module without causing resource destruction and recreation.
The moved block (Terraform 1.1+) allows you to tell Terraform that a resource has been relocated in code without actually changing the underlying infrastructure resource; it updates the state file to track the new address, preventing unnecessary destroy-and-recreate cycles. For example, if you refactor a module by extracting aws_security_group.app into a separate submodule, you'd add moved { from = aws_security_group.app to = module.security.aws_security_group.app } in the root module, instructing Terraform to update state references without touching the actual security group. This is critical when refactoring large modules or migrating resources between modules in production, as it preserves infrastructure continuity and avoids downtime from recreating resources. Without moved blocks, the old resource address would appear destroyed and a new one created, potentially causing attachment and network disruption; moved blocks make refactoring safe by decoupling code structure changes from infrastructure changes.



