Terraform State¶
79 cards — 🟢 14 easy | 🟡 40 medium | 🔴 15 hard
🟢 Easy (14)¶
1. How to inspect current state?
Show answer
`terraform show` displays the current state in a human-readable format, listing all managed resources and their attributes. Use `terraform show -json` for machine-readable output. For individual resources: `terraform state show2. How do you manage Terraform state?
Show answer
Remote backends, usually S3 + DynamoDB locking. It avoids drift and makes collaboration safe.Remember: "terraform.tfstate is JSON." It contains resource IDs, attributes, and metadata. Treat it as sensitive — it often contains secrets.
3. What are the best practices for organizing Terraform code?
Show answer
Some best practices for organizing Terraform code include:* Use a modular structure with reusable modules.
* Separate environments using workspaces or directory structures.
* Leverage variables for flexibility and parameterization.
* Utilize version control (e.g., Git) for code management.
* Implement code review processes for collaboration.
* Use remote backends for state management and collaboration.
* Follow naming conventions for resources, variables, and modules.
* Document configurations with comments and README files.
4. What is a Terraform backend?
Show answer
A backend in Terraform determines how state is loaded and how operations like state locking are handled. For instance, using an S3 backend means your state file is stored in an S3 bucket (often with DynamoDB for locking), enabling team collaboration.Remember: "terraform state mv moves resources between state addresses." Use for refactoring without destroy/recreate.
5. What are output variables and what terraform output does?
Show answer
Output variables are named values that are sourced from the attributes of a module. They are stored in terraform state, and can be used by other modules through `remote_state`Remember: "terraform import adds existing infrastructure to state." Write the HCL first, then import.
6. What is the Terraform state file and why is it important?
Show answer
The state file (terraform.tfstate) is a JSON file that maps your Terraformconfiguration to real-world resources. It's the source of truth for Terraform.
What it stores:
- Resource IDs and attributes from the cloud provider
- Dependencies between resources
- Metadata about the Terraform version used
Why it's critical:
- Terraform uses it to determine what changes to make
- Without it, Terraform would try to recreate everything
- Enables plan/apply workflow to show differences
7. What is the effect of setting variable as "sensitive"?
Show answer
It doesn't show its value when you run `terraform apply` or `terraform plan` but eventually it's still recorded in the state file.Remember: "Workspaces create separate state files in the same backend." Default workspace is "default."
8. Explain what is a Terraform workspace
Show answer
[developer.hashicorp.com](https://developer.hashicorp.com/terraform/language/state/workspaces): "The persistent data stored in the backend belongs to a workspace. The backend initially has only one workspace containing one Terraform state associated with that configuration. Some backends support multiple named workspaces, allowing multiple states to be associated with a single configuration."9. Which command will produce a state file?
Show answer
`terraform apply` creates or updates the state file (`terraform.tfstate`) after successfully provisioning resources. The state file maps your configuration to real infrastructure and stores resource attributes.Gotcha: never edit the state file manually — use `terraform state mv` or `terraform import` to modify state safely. Store state remotely for team environments.
10. True or False? If you pass secrets from a centralized secrets store (like Hashicorp Vault) they are not visible in plan files (terraform plan)
Show answer
False. It doesn't matter where your secrets store (file, environment variables, centralized secrets store), they will be visible in both state file and plan output.Remember: "State is the record of truth for Terraform." Infrastructure exists → state maps it → config describes it.
11. What are Terraform "workspaces"?
Show answer
Allow for multiple state files within a single configuration.Remember: "State splitting = separate state files for separate concerns." Network, compute, database each get their own state.
12. What is the "state file"?
Show answer
The state file (`terraform.tfstate`) is a JSON file that tracks all managed resources and maps them to your Terraform configuration. It stores resource IDs, attributes, dependencies, and metadata.Gotcha: the state file may contain sensitive data (passwords, keys) — always use remote backends with encryption, never commit it to version control.
13. What is Terraform state and why is it needed?
Show answer
Terraform state is a JSON data file (terraform.tfstate) that Terraform uses to map your configuration to real-world resources. It records resource IDs, attributes, and metadata so Terraform knows what is already created and can plan updates accordingly. The state can be stored locally or remotely, and remote state backends support locking to prevent concurrent changes.Remember: "terraform state show RESOURCE shows all attributes in state." More detailed than terraform show.
14. What's a Terraform backend? What is the default backend?
Show answer
Terraform backend determines how the Terraform state is stored and loaded. By default the state is local, but it's possible to set a remote backend.🟡 Medium (40)¶
1. You have a Git repository with Terraform files but no .gitignore. What would you add to a .gitignore file in Terraform repository?
Show answer
```\n**/.terraform/*\n*.tfstate\n*.tfstate.*\n*.tfvars\n*.tfvars.json\n```You don't want to store state file nor any downloaded providers in .terraform directory. It also doesn't makes sense to share/store the state backup files.
Remember: "State = Terraform's map of config to real resources." Without state, Terraform can't know what it manages.
Gotcha: Losing state = Terraform forgets everything.
2. True or False? Each Terraform workspace has its own state file.
Show answer
TRUE.Workspace behavior:
- Each workspace maintains separate state
- Same configuration, different state
- Useful for dev/staging/prod environments
State location:
- Local backend: terraform.tfstate.d/
- Remote backend: Separate state per workspace
Commands:
- terraform workspace list
- terraform workspace new dev
- terraform workspace select prod
- terraform workspace show
Use cases:
- Multiple environments from same code
- Testing changes
- Feature branches
Alternatives:
- Separate directories per environment
- Terragrunt for environment management
- Separate state backends
Note: Some teams avoid workspaces, preferring explicit separation.
3. What is "Terraform Import," and when would you use it?
Show answer
terraform import is a Terraform command used to import existing infrastructure into Terraform management. It is useful when resources are created outside of Terraform, and you want to bring them under Terraform control. The syntax is:```terraform import
For example:
```terraform import aws_instance.example i-0123456789abcdef0\n```
After importing, Terraform can manage and track changes to the resource.
4. How do you configure an AWS S3 backend with DynamoDB state locking?
Show answer
Use a remote backend when you need a shared, durable source of truth. A minimal configuration looks like:```hcl\nterraform {\n required_version = ">= 1.6.0"\n\n backend "s3" {\n bucket = "my-tfstate-bucket"\n key = "prod/network/terraform.tfstate"\n region = "us-east-1"\n dynamodb_table = "tf-locks"\n encrypt = true\n }\n}\n```
- Create the S3 bucket with versioning, default encryption, and block public access before enabling the backend.
- Provision a DynamoDB table with the primary key `LockID` so Terraform can acquire locks.
- Use IAM least privilege policies that allow only state operations on the bucket and table to reduce blast radius.
5. True or False? it's NOT possible to use variable in a backend configuration
Show answer
That's true and quite a limitation as it means you'll have to go to the resources of the remote backend and copy some values to the backend configuration.One way to deal with it is using partial configurations in a completely separate file from the backend itself and then load them with `terraform init -backend-config=some_backend_partial_conf.hcl`.
6. What would be the process of switching back from remote backend to local?
Show answer
1. You remove the backend code and perform `terraform init` to switch back to `local` backend.2. You remove the resources that are the remote backend itself.
3. Archive the latest remote state file so you can recover if the local copy gets corrupted.
7. How do you manage different environments (dev, staging, prod) in Terraform?
Show answer
Managing different environments in Terraform can be achieved using workspaces or by maintaining separate configuration files for each environment. Workspaces provide a cleaner approach, allowing you to switch between environments easily using commands like terraform workspace select or terraform workspace new. Alternatively, you can use separate directories or naming conventions for environment-specific configurations, each with its own Terraform state file.8. What is "Terraform Cloud," and how does it enhance Terraform workflows?
Show answer
Terraform Cloud is a fully managed service by HashiCorp that provides collaboration, automation, and governance features for Terraform workflows. Key features include:* Remote Execution: Run Terraform operations in a managed environment.
* Remote State Management: Store and share Terraform state securely.
* Collaboration: Enable multiple team members to work concurrently on the same configuration.
* Policy as Code: Enforce policies and compliance through Sentinel policies.
* Private Module Registry: Host and version private Terraform modules.
9. What is "Terraform Import," and what considerations should be taken when using it?
Show answer
terraform import is used to import existing resources into Terraform. Considerations include:* Resource Structure: Understanding the structure of the resource to be imported.
* ID Specification: Providing the existing resource's ID for accurate import.
* State File Update: Ensuring that the Terraform state file is updated post-import.
* Reversibility: Verifying that the imported resource can be managed by Terraform going forward.
10. Explain the purpose of a Terraform state file.
Show answer
The Terraform state file (.tfstate) is a crucial component that stores the current state of the infrastructure managed by Terraform. It contains information about the resources, their configurations, and the relationships between them. The state file is essential for Terraform to understand the existing infrastructure and track changes over time. It serves as a source of truth, enabling Terraform to determine what needs to be added, modified, or destroyed to align the actual infrastructure state with the desired state defined in the Terraform configuration.11. State two use cases where you would use terraform import
Show answer
1. You have existing resources in one of the providers and they are not managed by Terraform (as in not included in the state)2. You lost your tfstate file and need to rebuild it
Remember: "State locking = no concurrent modifications." DynamoDB for S3 backend. terraform force-unlock for stuck locks.
12. What's your Terraform experience?
Show answer
I've used Terraform for provisioning core AWS resources — EC2, IAM roles, VPC components, and security groups. I'm comfortable with modules, variables, and remote backends. If a team uses deeper patterns like workspaces, Terragrunt, or custom providers, I adapt quickly by reviewing examples and building small test modules. My strength is understanding infrastructure patterns and applying them consistently.13. How does Terraform handle remote backends, and why are they important?
Show answer
Terraform remote backends store the Terraform state file remotely, outside the local working directory. Remote backends provide benefits such as collaboration, locking, and centralized state management. Examples of remote backends include Amazon S3, Azure Storage, or HashiCorp Consul. By using remote backends, multiple team members can work collaboratively on the same infrastructure, and state locking prevents concurrent modifications, ensuring consistency.14. What does terraform import do?
Show answer
It brings an existing external resource under Terraform management by importing its current state into the Terraform state file. For example, you can run terraform import aws_instance.myvm i-0123456789 to map an existing EC2 instance into your Terraform config (after you've defined the resource in code).15. What terraform taint does?
Show answer
`terraform taint resource.id` manually marks the resource as tainted in the state file. So when you run `terraform apply` the next time, the resource will be destroyed and recreated.Remember: "terraform state rm removes a resource from state WITHOUT destroying it." The resource still exists in the cloud.
16. Is there a way to obtain information from a remote backend/state using Terraform?
Show answer
Yes, using the concept of data sources. There is a data source for a remote state called "terraform_remote_state".You can use it the following syntax `data.terraform_remote_state.
Remember: "State file contains sensitive data." Encrypt the backend, restrict access, never commit to git.
17. Can you name three different things included in the state file?
Show answer
- The representation of resources - JSON format of the resources, their attributes, IDs, ... everything that required to identify the resource and also anything that was included in the .tf files on these resources- Terraform version
- Outputs
18. Explain the concept of "remote backends" and their importance in Terraform.
Show answer
Remote backends in Terraform refer to external storage locations for the Terraform state file. Instead of storing the state file locally, remote backends store it in a shared and centralized location, often in cloud object storage or a dedicated service. This is important for several reasons:* Collaboration: Enables teams to work concurrently on the same infrastructure.
* Locking: Supports state locking to prevent conflicts during simultaneous updates.
* Consistency: Ensures that all team members have a consistent and up-to-date view of the infrastructure state.
* Security: Centralized and secure storage mitigates the risk of state file loss or unauthorized access.
19. Why does Terraform keep state and how do local and remote state differ?
Show answer
Terraform stores state to map real infrastructure objects to the resources declared in code, keep track of dependencies, detect drift, and speed up planning by caching attribute data.- Local state is stored in a `terraform.tfstate` file on disk and is suitable for quick experiments or single-operator workflows.
- Remote state lives in a backend (such as S3, GCS, Terraform Cloud) that can enforce locking, access controls, and versioning so teams share a single source of truth.
Always choose a remote backend once there is more than one operator or automation pipeline touching the configuration.
20. How does a remote state backend improve collaboration for a Terraform project?
Show answer
By storing the state file in a shared location enabling multiple people or processes to work with the same state.A remote state backend improves collaboration on Terraform projects by addressing the core challenge of sharing infrastructure state. When a team works on infrastructure, everyone needs access to the current state to safely make changes, and locking prevents clashing applies.
21. Discuss the use of "Terraform State Migrations" and when they might be necessary.
Show answer
Terraform State Migrations are necessary when:* Resource Changes: Resources are modified, added, or removed, requiring state updates.
* Schema Changes: Terraform configuration schema evolves, necessitating state adjustments.
* Module Updates: Module versions change, impacting the structure of the state.
* Infrastructure Refactoring: Refactoring the infrastructure layout or dependencies.
* State Upgrades: Upgrading Terraform versions may require state format changes.
* Collaborative Development: Multiple developers or teams collaborate, necessitating state synchronization.
22. How do you apply changes using Terraform?
Show answer
After reviewing the execution plan using terraform plan, you can apply the changes by running the terraform apply command. This command executes the planned changes and prompts for confirmation before making any modifications to the infrastructure. During the apply process, Terraform updates the state file to reflect the current state of the infrastructure based on the applied changes. The terraform apply command is a critical step in deploying or modifying infrastructure resources.23. Explain the process of handling Terraform state locking and backends.
Show answer
State locking is crucial to prevent conflicts when multiple users or automation processes attempt to modify the Terraform state simultaneously. The process involves:* Acquiring a Lock: Before performing any Terraform operations, a lock is acquired on the state file.
* Performing Operations: Once the lock is obtained, Terraform can safely read or modify the state.
* Releasing the Lock: After completing the operations, the lock is released, allowing others to acquire it.
Examples of backends include Amazon S3, Azure Storage, and HashiCorp Consul.
24. Discuss the advantages of using Terraform workspaces over multiple state files.
Show answer
Terraform workspaces offer a more flexible and manageable approach compared to maintaining multiple state files. Workspaces allow you to use a single configuration file with different values for variables based on the selected workspace. This is particularly useful for managing environments like development, staging, and production. It simplifies the structure, reduces redundancy, and makes it easier to switch between environments without duplicating or managing multiple state files.25. Which commands help you inspect, migrate, and safely manipulate Terraform state?
Show answer
```bash\nterraform init -migrate-state\nterraform plan -refresh-only\nterraform state list\nterraform show -json | jq '.values.root_module.resources[].address' | head\nterraform state mv module.vpc.aws_subnet.public[0] module.vpc.aws_subnet.public_a\n```- `terraform init -migrate-state`: moves an existing local state file into the configured backend with locking.
- `terraform plan -refresh-only`: detects drift by refreshing remote object attributes without proposing changes.
26. Explain Terraform's import functionality
Show answer
`terraform import` is a CLI command used for importing an existing infrastructure into Terraform's state.It's does NOT create the definitions/configuration for creating such infrastructure.
Remember: "terraform state pull downloads state. terraform state push uploads." Both are dangerous — use with care.
27. Discuss the use of "Terraform Remote Backends" for state storage and collaboration.
Show answer
Terraform Remote Backends are used for centralized state storage and collaboration. Key aspects include:* State Storage: Storing the Terraform state file remotely for accessibility.
* Collaboration: Facilitating collaboration among team members by sharing a common state.
* Concurrency Control: Preventing conflicts by enabling state locking.
* Remote Execution: Allowing remote execution of Terraform commands.
Remember: "terraform plan -refresh-only detects drift without applying changes." Run periodically to catch manual changes.
28. How terraform apply workflow is different when a remote backend is used?
Show answer
It starts with acquiring a state lock so others can't modify the state at the same time. The apply will also download the latest state snapshot before planning and upload the updated state atomically after the run completes.29. What are Terraform workspaces, and how are they used?
Show answer
Terraform workspaces allow you to manage multiple instances of the same set of Terraform configurations. Each workspace maintains its own state file, enabling the isolation of resources for different environments or purposes within a single Terraform configuration. For example, you can have workspaces for development, staging, and production environments. Workspaces make it easy to switch between different sets of infrastructure configurations without duplicating code, simplifying the management of infrastructure at scale.Remember: "terraform state replace-provider updates the provider for resources in state." Useful when providers are forked.
30. Explain "Remote State". When would you use it and how?
Show answer
Terraform generates a `terraform.tfstate` json file that describes components/service provisioned on the specified provider. RemoteState stores this file in a remote storage media to enable collaboration amongst team.
31. Explain the concept of "Terraform Backends" and their types.
Show answer
Terraform Backends determine where Terraform state files are stored. Types of backends include:* Local: Stores the state file locally on the machine. Not suitable for collaboration.
* Remote: Stores the state file remotely, enabling collaboration. Examples include Amazon S3, Azure Storage, and HashiCorp Consul.
* Enhanced Remote: Remote backends with additional features, like Terraform Cloud or Terraform Enterprise.
* lArtifacts: Backends that store and retrieve artifacts, suitable for large-scale deployments.
Remember: "terraform force-unlock removes a stuck lock." Only use when certain no other operation is running.
32. How do you migrate from local state to a new remote backend?
Show answer
1. Provision backend resources (for example an S3 bucket with versioning and a DynamoDB table) from a separate bootstrap configuration.2. Add the backend block to your Terraform configuration and run `terraform init -migrate-state`.
3. Verify the migration with `terraform state list` or `terraform state pull` and keep a secure backup of the previous file.
4. Remove or archive the local `terraform.tfstate` only after confirming new plans operate against the remote backend.
33. How do you handle the state file when collaborating with multiple Terraform developers?
Show answer
Collaborating with multiple developers in Terraform involves using remote backends to store the state file centrally. This ensures:* Concurrency Control: Prevents conflicts by locking the state during operations.
* Consistency: Maintains a single source of truth for infrastructure state.
* Visibility: Enables collaboration and visibility into changes.
Terraform Cloud, AWS S3, or Azure Storage are common choices for remote backends.
34. How do you import existing resource using Terraform import?
Show answer
1. Identify which resource you want to import.2. Write terraform code matching configuration of that resource.
3. Run terraform command `terraform import RESOURCE ID`
eg. Let's say you want to import an aws instance. Then you'll perform following:
1. Identify that aws instance in console
2. Refer to its configuration and write Terraform code which will look something like:
```\nresource "aws_instance" "tf_aws_instance" {\n ami = data.aws_ami.ubuntu.id\n instance_type = "t3.micro"\n\n tags = {\n Name = "import-me"\n }\n}\n```
3. Run terraform command `terraform import aws_instance.tf_aws_instance i-12345678`
35. How does Terraform manage state for resources that might be deleted outside of Terraform?
Show answer
Terraform relies on the local state file to track the state of managed resources. If a resource is deleted outside of Terraform, it becomes "orphaned." Terraform's terraform import command can be used to reconcile the local state with the actual infrastructure by associating the existing resource with the Terraform state. Importing the resource allows Terraform to manage it going forward.36. Explain "State Locking"
Show answer
State locking is a mechanism that blocks an operations against a specific state file from multiple callers so as to avoid conflicting operations from different team members. Once the first caller's operation's lock is released the other team member may go ahead tocarryout his own operation. Nevertheless Terraform will first check the state file to see if the desired resource already exist and
if not it goes ahead to create it.
Remember: "State file paths match config addresses." Renaming in config without a moved block = destroy + create.
37. Why does it matter where you store the tfstate file? In your answer make sure to address the following:
Show answer
* tfstate contains credentials in plain text. You don't want to put it in publicly shared location.* tfstate shouldn't be modified concurrently so putting it in a shared location available for everyone with "write" permissions might lead to issues. (Terraform remote state doesn't has this problem).
* tfstate is an important file. As such, it might be better to put it in a location that has regular backups and good security.
As such, tfstate shouldn't be stored in git repositories. secured storage such as secured buckets, is a better option.
38. True or False? If you pass secrets with environment variables, they are not visible in your state file
Show answer
False. State files include sensitive data as it is. Which means it's very important that wherever you store your state file, it's encrypted and accessible only to those who should be able to access it.Remember: "State environments: dev, staging, prod should each have separate state files." Never share state across environments.
39. True or False? it's common to edit terraform state file directly by hand and even recommended for many different use cases
Show answer
False. You should avoid as much possible to edit Terraform state files directly by hand. Prefer supported commands such as `terraform state mv`, `terraform state rm`, or `terraform state replace-provider` so the CLI keeps metadata consistent.40. How and why concurrent edits of the state file should be avoided?
Show answer
If there are two users or processes concurrently editing the state file it can result in invalid state file that doesn't actually represents the state of resources.To avoid that, Terraform can apply state locking if the backend supports that. For example, AWS s3 supports state locking and consistency via DynamoDB. Often, if the backend supports it, Terraform will make use of state locking automatically so nothing is required from the user to activate it. Automation pipelines should wait for locks to clear instead of forcing unlocks.
Remember: "State file should never be committed to git." Add *.tfstate and *.tfstate.backup to .gitignore.
🔴 Hard (15)¶
1. How does Terraform handle the state across a team of developers working concurrently?
Show answer
Terraform uses a state file to keep track of the infrastructure's current state. When working in a team, it's crucial to use a shared remote backend (like Amazon S3 or Azure Storage) to store the state file. This ensures that all team members are working with the same state. Terraform state locking mechanisms prevent concurrent modifications to the state, avoiding conflicts. Collaborative features, such as workspaces and Terraform Enterprise, provide additional tools for managing state across teams, supporting concurrent development, and maintaining consistency.2. Why storing state file locally on your computer may be problematic?
Show answer
In general, storing state file on your computer isn't a problem. It starts to be a problem when you are part of a team that uses Terraform and then you would like to make sure it's shared. In addition to being shared, you want to be able to handle the fact that different teams members can edit the file and can do it at the same time, so locking is quite an important aspect as well.3. Why storing the state in versioned control repo is not a good idea?
Show answer
- Sensitive data: some resources may specify sensitive data (like passwords and tokens) and everything in a state file is stored in plain text.- Prone to errors: when working with Git repos, you mayo often find yourself switch branches, checkout specific commits, perform rebases, ... all these operations may end up in you eventually performing `terraform apply` on non-latest version of your Terraform code. Keeping state outside Git eliminates that risk.
- Lack of locking and audit trails compared to managed backends.
4. How do you handle sensitive data (like passwords) in Terraform?
Show answer
Avoid putting secrets in plaintext in .tf files. Use Terraform variables (mark them sensitive in 0.15+), use environment variables or .tfvars files that aren't committed, or integrate with secret managers. Terraform also supports vault and other providers for secrets, and the state can be encrypted by the backend (e.g., using secure backend or not storing state locally).5. Discuss the role of Terraform in managing infrastructure drift.
Show answer
Infrastructure drift occurs when the actual infrastructure deviates from the defined configuration. Terraform helps mitigate drift by enforcing the desired state defined in the configuration. When infrastructure is modified outside of Terraform (manual changes or other tools), Terraform detects drift during subsequent runs. It then plans and applies changes to bring the infrastructure back to the desired state. Managing drift ensures consistency and prevents unintended changes.6. Mention some best practices related to tfstate
Show answer
- Don't edit it manually. tfstate was designed to be manipulated by terraform and not by users directly.- Store it in secured location (since it can include credentials and sensitive data in general).
- Backup it regularly so you can roll-back easily when needed.
- Store it in remote shared storage. This is especially needed when working in a team and the state can be updated by any of the team members.
- Enabled versioning if the storage where you store the state file, supports it.
7. Discuss the challenges and best practices of managing Terraform state in a team.
Show answer
Challenges:* Concurrency: Avoid concurrent modifications by using state locking mechanisms.
* Visibility: Ensure visibility into state changes, modifications, and who made them.
* Consistency: Use remote backends for centralized state storage to maintain consistency.
**Best Practices:**
* Shared Remote Backend: Use a shared backend to store the state centrally.
* Access Controls: Implement fine-grained access controls for state files.
* Audit Logging: Enable audit logging to track changes and modifications.
* Backup and Recovery: Implement regular backups of state files for recovery.
8. How does Terraform support infrastructure drift detection and correction?
Show answer
Infrastructure drift occurs when the actual state deviates from the expected state. Terraform addresses this by:* Regular Validation: Running terraform plan to detect discrepancies.
* State Comparison: Comparing the expected state with the actual state in the Terraform state file.
* Rollback Strategies: Implementing rollback in case of unexpected changes.
* Automation: Incorporating drift detection into automated workflows.
9. What best practices keep Terraform state secure and reliable?
Show answer
- Encrypt and version your remote backend (for example `aws_s3_bucket_versioning` plus SSE-KMS on S3).- Enforce locking (DynamoDB, GCS locking, or Terraform Cloud workspaces) and monitor stuck locks.
- Grant IAM minimum privileges and rotate access keys; automation should assume roles with short-lived credentials.
- Schedule automated backups of the backend (S3 replication, DynamoDB PITR) and periodically test restores.
- Document "state owner" responsibility, incident response, and break-glass steps for unlocks or manual edits (should be last resort).
10. Describe how you manage state file(s) when you have multiple environments (e.g. development, staging and production)
Show answer
Probably no right or wrong answer here, but it seems, based on different source, that the overall preferred way is to have a dedicated state file per environment.Common patterns:
- Separate backend configurations per environment (different S3 prefixes or even different buckets and DynamoDB tables).
- Distinct workspaces or directories when you need isolated state plus different credentials.
- Terraform Cloud organizations/workspaces mapped to environments with role-based access control.
11. Explain the challenges and best practices for managing Terraform state in a CI/CD pipeline.
Show answer
Challenges include state consistency and concurrent modifications. Best practices involve:* Remote Backends: Use remote backends for centralized state storage.
* State Locking: Employ state locking to prevent concurrent modifications.
* Separate Workspaces: Use separate workspaces for different environments.
* Automated Pipelines: Automate pipeline workflows to apply changes.
* Infrastructure as Code: Treat CI/CD pipeline configurations as code.
12. How do you implement rollback strategies in Terraform in case of failed deployments?
Show answer
Rollback strategies in Terraform involve:* VCS Tagging: Tagging successful commits to mark deployable states.
* Backups: Regularly backing up Terraform state files.
* Manual Intervention: Manually reverting to a previous known-good state.
* Pipeline Notifications: Implementing alerts in CI/CD pipelines to catch failures early.
13. What is the "Terraform Enterprise" product, and how does it differ from open-source Terraform?
Show answer
Terraform Enterprise is HashiCorp's commercial offering for team collaboration and governance of Terraform deployments. It provides features such as:* Collaboration: Enables multiple team members to work on Terraform configurations concurrently.
* Remote State Management: Offers centralized and secure storage of Terraform state.
* Access Control: Provides fine-grained access controls and permissions.
* Private Module Registry: Supports a private registry for sharing and versioning Terraform modules.
14. What is "drift detection"?
Show answer
Drift detection identifies differences between the state file (what Terraform thinks exists) and the actual infrastructure. `terraform plan` performs drift detection automatically — any manual changes made outside Terraform appear as differences. Terraform Cloud can run continuous drift detection on a schedule.Gotcha: some resources have attributes that change frequently (timestamps, ETags), causing false-positive drift.
15. What is "Terraform State Locking," and why is it crucial in a team environment?
Show answer
Terraform State Locking is the practice of preventing concurrent modifications to the Terraform state. In a team environment, state locking is crucial for:* Concurrency Control: Avoiding conflicts when multiple team members apply changes simultaneously.
* Data Integrity: Ensuring consistency and preventing data corruption.
* Collaboration: Facilitating collaborative development with shared infrastructure.
Terraform state locking is achieved through remote backends, and tools like Terraform Cloud provide built-in locking mechanisms.
Remember: "Disaster recovery for state: S3 versioning + DynamoDB backups + periodic state pull snapshots."