HashiCorp · Free Practice Questions · Last reviewed May 2026
48real exam-style questions organised by domain, each with the correct answer highlighted and a plain-English explanation of why it's right — and why the others are wrong.
13% of exam · 6 sample questions below
A team is adopting Terraform to manage infrastructure. One requirement is that all configuration changes must be reviewed and approved before being applied. The team wants to ensure that the Terraform state file reflects the actual deployed infrastructure at all times. Which practice should they implement to meet these requirements?
Store state locally and use a manual approval process outside of Terraform.
Store state remotely and use a version control system with pull requests to review changes before applying.
Remote state enables team collaboration and VCS with PRs enforces review.
Store state locally and use a shared network drive for team access.
Have each team member run terraform apply from their local machine after informal discussion.
An organization manages multiple environments (dev, staging, prod) using Terraform. They want to minimize code duplication while allowing environment-specific variable values. Which approach best achieves this goal?
Use a separate Git branch for each environment, each with its own Terraform configuration.
Write a single Terraform configuration that uses count and conditional expressions to create resources based on environment variable.
Use Terraform workspaces with a single configuration and define all variable values in one .tfvars file.
Organize the repository with a shared modules directory and separate subdirectories for each environment that call the same modules with environment-specific .tfvars files.
Organizing the repository with a shared modules directory and separate subdirectories for each environment is a best practice that maximizes code reuse and maintains clear separation of concerns. Common infrastructure patterns are encapsulated in reusable modules, while each environment's subdirectory instantiates these modules using its own dedicated `.tfvars` files. This structure ensures consistency, simplifies environment-specific parameter management, and enhances overall maintainability and scalability.
A junior administrator wants to practice Terraform by deploying a single web server in AWS. They write a configuration file and run terraform init and terraform apply. The deployment succeeds but they notice the web server is not accessible from the internet. What is the most likely reason?
The instance type chosen does not support public IP addresses.
The terraform init command failed and the apply did not actually create resources.
The subnet is configured as private and does not have a route to the internet.
The security group does not allow inbound HTTP/HTTPS traffic from 0.0.0.0/0.
The security group does not allow inbound HTTP/HTTPS traffic from 0.0.0.0/0. This is the most probable cause. Security groups function as stateful virtual firewalls that control inbound and outbound traffic for instances. For a web server to be accessible over HTTP (port 80) or HTTPS (port 443) from any IP address on the internet (represented by 0.0.0.0/0), explicit inbound rules must be configured within the associated security group. Without these specific rules, all connection attempts on those ports will be silently dropped, making the web server appear inaccessible even if it is running and has a public IP address.
A company uses Terraform to manage infrastructure on AWS. They have a configuration that creates an S3 bucket and a DynamoDB table for state locking. The team notices that sometimes when two members run terraform apply simultaneously, they get a state locking error. However, they want to allow concurrent operations on different workspaces. What is the best approach?
Remove the DynamoDB table and use local state files to avoid locking issues.
Configure all team members to use the same workspace so that only one person can apply at a time.
Keep the current setup because the error is harmless and users can retry.
Use separate state files per workspace and ensure each workspace has its own lock entry in DynamoDB; the current setup already supports this.
Terraform workspaces inherently create separate state files within the configured remote backend, such as an S3 bucket. Each of these distinct state files is then protected by its own unique lock entry in the DynamoDB table, preventing concurrent modifications to that specific workspace's state. This design allows multiple team members to concurrently apply changes to different workspaces without conflict, leveraging the robust locking mechanisms provided by the remote backend.
You are a DevOps engineer at a growing startup. The infrastructure currently consists of a single AWS EC2 instance running a web application, manually configured. The company plans to scale to multiple instances and environments (development, staging, production). They want to adopt Infrastructure as Code using Terraform. The team has limited experience with Terraform and wants to start small, then gradually adopt more advanced features. The current manual infrastructure must be imported into Terraform. The team also wants to ensure that code changes are reviewed via pull requests before being applied. Which of the following is the best course of action to meet these requirements?
Install Terraform on the existing instance, run terraform init and apply directly to manage it, and store state locally. Have team members share the state file via a shared folder.
Write Terraform configuration from scratch to match the existing instance, but do not import; instead, destroy the old instance and recreate it with Terraform.
Create separate Git branches for each environment (dev, staging, prod) and have each team member work independently on their branch, merging occasionally.
Create a Git repository with a main branch. Write a minimal Terraform configuration that describes the existing EC2 instance. Use terraform import to bring the instance under Terraform management. Store the state file remotely in S3 with DynamoDB locking. Set up a CI pipeline that runs terraform plan on pull requests and requires approval before merging.
Creating a Git repository with a main branch provides version control and a single source of truth for infrastructure code. Using `terraform import` allows existing resources to be brought under management non-disruptively, while remote state in S3 with DynamoDB locking ensures collaborative safety and prevents concurrent state modifications. A CI pipeline with `terraform plan` on PRs and approval enforces code review and validates changes before deployment, establishing robust operational practices.
Which TWO statements about Infrastructure as Code (IaC) are correct?
IaC is only applicable to cloud-based infrastructure.
IaC eliminates configuration drift entirely.
IaC enables automated provisioning and management of infrastructure.
This statement is correct because a primary advantage of Infrastructure as Code is its ability to automate the entire lifecycle of infrastructure resources, from initial provisioning to ongoing management and eventual deprovisioning. By defining infrastructure in machine-readable files, IaC tools can interpret these definitions and automatically interact with underlying APIs to create, update, and destroy resources without manual intervention. This automation drastically reduces human error and accelerates deployment cycles.
IaC allows the same configuration to be applied multiple times with the same result.
This statement is correct, describing the crucial property of idempotency inherent in most Infrastructure as Code tools. Idempotency ensures that applying the same IaC configuration multiple times will consistently yield the identical infrastructure state, regardless of the initial state or how many times it has been applied. The tools intelligently determine necessary changes, creating resources if they don't exist, updating them if they differ, and doing nothing if they already match the desired state.
IaC tools require manual execution of scripts.
Want more Understand IaC concepts practice?
Practice this domain13% of exam · 6 sample questions below
A DevOps engineer is writing a Terraform configuration to provision an AWS EC2 instance. They want to ensure that the instance is replaced if the AMI ID changes, but not if the instance type changes. Which lifecycle meta-argument should be used?
Set `prevent_destroy = true`
Set `ignore_changes = all`
Set `create_before_destroy = true` and add `instance_type` to `ignore_changes`
This solution effectively combines two distinct `lifecycle` rules to achieve the desired outcome. `create_before_destroy = true` ensures that when a change *does* necessitate a resource replacement (e.g., an AMI update), the new instance is fully provisioned and operational before the old one is terminated, minimizing service disruption. Concurrently, adding `instance_type` to `ignore_changes` specifically instructs Terraform to disregard modifications to this attribute, preventing it from triggering an unintended resource replacement solely due to an `instance_type` modification.
Set `create_before_destroy = true` only
A team is using Terraform to manage infrastructure across multiple environments (dev, staging, prod). They want to reuse the same root module configuration but with different variable values. Which approach is the most efficient?
Use environment variables to switch between configurations
Use a single state file that includes all environments
Copy the entire configuration into separate directories for each environment
Use Terraform workspaces
Terraform workspaces provide an elegant solution for managing multiple distinct environments using a single, shared configuration. Each workspace maintains its own isolated state file within the configured backend, ensuring that operations in one environment do not affect others. This approach promotes code reusability, reduces duplication, and simplifies the management of infrastructure across development, staging, and production environments effectively.
A Terraform configuration includes a module from the Terraform Registry. After running `terraform init`, the module is downloaded. However, a subsequent `terraform plan` fails with an error that a required provider is not installed, even though it is declared in the module. What is the most likely cause?
The module uses a different Terraform version
The provider version constraint is incompatible
The `required_providers` block is not declared in the root module
Terraform's provider installation mechanism primarily relies on the `required_providers` block within the root module to determine which providers need to be downloaded and configured. Even if a child module internally declares a provider, Terraform will not install it unless the root module explicitly includes that provider in its own `required_providers` block. This omission leads to a "provider not found" error when Terraform attempts to use the provider during `plan` or `apply`.
The module source URL is incorrect
Which TWO of the following are valid ways to reference a resource attribute in Terraform?
`module.vpc.output`
`data.aws_ami.ubuntu.id`
`var.instance_type`
`module.vpc.vpc_id`
This is a valid way to reference an attribute. It correctly accesses the `vpc_id` output from a child module named `vpc`. Module outputs are commonly used to expose specific attributes or computed values from resources managed within that module, making them accessible to the parent module or other parts of the configuration. This effectively references a value derived from a resource within the module, making it a valid answer.
`aws_instance.web.id`
This is a valid and direct way to reference a resource attribute. It specifies the `id` attribute of an `aws_instance` resource that has been given the local name `web`. This syntax, `resource_type.resource_name.attribute_name`, is the standard and most common method for accessing specific attributes of managed infrastructure resources within a Terraform configuration. It directly retrieves a property of an infrastructure component managed by Terraform.
Refer to the exhibit. A developer runs `terraform apply` and the operation succeeds. Later, they manually terminate the EC2 instance through the AWS console. What will happen when the developer runs `terraform apply` again?
Terraform will recreate the EC2 instance and reassociate the Elastic IP
When an EC2 instance managed by Terraform is manually terminated, Terraform detects this as drift during the `plan` phase. The `aws_instance` resource will be marked for recreation. Since the `aws_eip_association` resource explicitly depends on the `id` of the EC2 instance, Terraform will also identify that the existing Elastic IP needs to be reassociated with the *new* instance. Consequently, Terraform will first provision a new EC2 instance and then update the `aws_eip_association` to link the existing Elastic IP to this newly created instance, restoring the desired state.
The Elastic IP will be disassociated and the instance will be recreated
Terraform will only recreate the EC2 instance without reassociating the Elastic IP
The apply will fail because the Elastic IP is still attached to the terminated instance
You are a platform engineer at a fintech company. Your team manages a multi-region application on AWS using Terraform. The infrastructure includes VPCs, subnets, EC2 instances, and an Application Load Balancer (ALB). The configuration uses modules from the Terraform Registry and remote state in S3 with DynamoDB locking.
Recently, after a colleague ran `terraform apply` in the us-east-1 region, the application experienced downtime because the ALB's target group was accidentally updated to point to instances in us-west-2 instead of us-east-1. The root cause was that the Terraform configuration for the ALB used a variable `target_region` which was hardcoded to us-west-2 in a `terraform.tfvars` file that was not intended for that workspace.
Your team wants to prevent such misconfigurations in the future. Which course of action would most effectively reduce the risk of using incorrect variable values across workspaces?
Implement a CI/CD pipeline that runs `terraform plan` for every workspace and requires manual approval before apply
Use the same S3 backend for all regions but with different state file keys, and enforce naming conventions
Store all variables in a single `terraform.tfvars` file and use conditionals with `terraform.workspace` to select values
Create separate Terraform configurations for each region, each with its own backend configuration and variable files, and use directory structure to enforce separation
Creating separate Terraform configurations for each region, each within its own dedicated directory, provides the strongest form of isolation. This approach ensures that each region has its own backend configuration, state file, and explicitly defined variable files (e.g., `region.tfvars`). This physical separation makes it virtually impossible to accidentally apply variables or configurations meant for one region to another, as the `terraform` command must be executed from the correct, isolated directory.
Want more Understand Terraform basics practice?
Practice this domain13% of exam · 6 sample questions below
A company wants to manage its infrastructure as code using Terraform. The team has a mix of on-premises servers and cloud resources in AWS and Azure. Which of the following best describes Terraform's purpose in this scenario?
Terraform is a configuration management tool for installing software on existing servers.
Terraform is a cloud-specific orchestration tool that only works with AWS.
Terraform is a monitoring and logging tool for cloud resources.
Terraform is an infrastructure-as-code tool for provisioning and managing any infrastructure across multiple providers.
This statement accurately describes Terraform's fundamental purpose. As an infrastructure-as-code tool, Terraform enables users to define infrastructure declaratively using HCL, allowing for version-controlled, repeatable, and automated provisioning and management of resources. Its robust provider framework supports a vast array of platforms, including major cloud providers, on-premises virtualization, and SaaS applications, facilitating consistent infrastructure deployment across diverse environments.
A developer runs `terraform plan` and sees that Terraform will create a new S3 bucket and modify a security group. Which Terraform feature allows the developer to review these changes before applying them?
The `terraform apply` command
The `terraform validate` command
The `terraform plan` command
The `terraform plan` command generates an execution plan, detailing the actions Terraform will take to achieve the desired state defined in the configuration files. This command compares the current infrastructure state (from the state file) with the desired state (from the configuration) and displays a comprehensive preview of resources to be added, changed, or destroyed, without making any actual modifications to the infrastructure.
The `terraform state` command
A team is using Terraform to manage multiple environments (dev, staging, prod) with the same configuration but different variable values. They want to avoid duplicating configuration files. Which Terraform feature is best suited for this?
Terraform modules with separate directories for each environment
Terraform data sources to fetch environment-specific variables
Using multiple Terraform configuration files in a single directory
Terraform workspaces
Terraform workspaces provide a robust mechanism for managing multiple distinct infrastructure environments using a single, consistent Terraform configuration. Each workspace maintains its own isolated state file, allowing for independent deployments and modifications without affecting other environments. This approach significantly reduces configuration duplication, simplifies environment management, and ensures consistency across development, staging, and production deployments.
An organization uses Terraform Cloud for remote state management. A user runs `terraform apply` locally but receives an error that the state is locked. What is the most likely cause?
The Terraform configuration has a syntax error.
The user does not have access to the remote state backend.
Another user or process is currently running a Terraform operation that modifies the same state.
Terraform state locking is a crucial mechanism designed to prevent concurrent write operations from corrupting the remote state file. When an operation like `terraform apply` or `terraform destroy` begins, Terraform attempts to acquire an exclusive lock on the state. If another user or automated process is already performing a state-modifying operation, that lock will be held, causing subsequent operations to fail with a 'state locked' error, thereby ensuring data integrity.
The remote backend is temporarily unavailable.
Which THREE of the following are valid Terraform providers?
hashicorp/azurerm
Correct. hashicorp/azurerm is the official Azure provider from HashiCorp.
kreuzwerker/docker
Correct. kreuzwerker/docker is a community provider that is widely used and valid.
hashicorp/kubernetes
Correct. hashicorp/kubernetes is the official Kubernetes provider.
hashicorp/aws
Correct. hashicorp/aws is the official AWS provider.
hashicorp/cloudwatch
Your organization manages a multi-cloud infrastructure using Terraform. The infrastructure includes an AWS VPC with subnets and EC2 instances, and an Azure resource group with virtual networks and VMs. The Terraform configuration is stored in a Git repository, and state is stored in an S3 bucket with DynamoDB locking. Recently, a developer updated the configuration to add a new security group rule in AWS, but after running `terraform apply`, the rule was not created. The developer verified that the configuration file contains the rule. Additionally, the developer noticed that the state file shows the security group exists but without the new rule. The developer ran `terraform plan` again, and it shows that the rule will be created. However, when applying, it fails with a 'timeout' error. The operations team suspects network connectivity issues to the S3 backend. What is the best course of action to resolve this issue?
Run `terraform init` again to reinitialize the backend.
Migrate the state backend to Terraform Cloud, and use remote operations for applies.
Migrating the state backend to Terraform Cloud and utilizing remote operations offloads the execution of `terraform apply` from the local machine to HashiCorp's managed infrastructure. This approach effectively bypasses local network instability, proxy configurations, or firewall restrictions that might be causing timeouts when accessing the state backend or provider APIs from the local environment. Terraform Cloud's robust and highly available execution environment ensures reliable communication with the state backend and target cloud providers.
Increase the timeout value in the Terraform provider configuration.
Disable state locking by removing the DynamoDB table reference.
Want more Understand Terraform's purpose practice?
Practice this domain13% of exam · 6 sample questions below
A developer runs `terraform plan` and it fails with a provider plugin error. Which command should they run first to resolve the issue?
terraform validate
terraform apply
terraform fmt
terraform init
terraform init is the foundational command that prepares a working directory for all subsequent Terraform operations. It performs several crucial setup steps, including discovering and downloading the necessary provider plugins specified in the configuration, initializing the chosen backend for state storage, and setting up module sources. A "provider not found" error during `terraform plan` indicates that the required provider binaries were not downloaded or properly configured, which `terraform init` specifically addresses by fetching them.
A team uses Terraform Cloud for remote state management. They want to ensure that state file changes are only made through the Terraform Cloud API and not through direct access to the storage backend. Which feature should they enable?
Sentinel policy enforcement
Remote state locking
Remote state locking is a critical mechanism within Terraform Cloud that ensures state modifications occur exclusively through its controlled API. When a Terraform operation (like a plan or apply) begins, Terraform Cloud acquires a lock on the state, preventing concurrent modifications and ensuring consistency. This lock is managed by Terraform Cloud, effectively forcing all state-altering operations to pass through its API, thereby preventing any direct, uncontrolled access or modification of the state file.
VCS integration
Team tokens
A company uses Terraform with multiple cloud providers and wants to integrate with their existing CI/CD pipeline. They need to enforce that all infrastructure changes go through code review and automated testing before being applied to production. Which approach best meets these requirements?
Store state in a remote backend and use terraform apply in the pipeline
Configure Terraform Cloud with run triggers and policy checks
Terraform Cloud provides a robust platform for managing Terraform workflows, offering features like run triggers that automate infrastructure changes upon code commits. Its integrated policy checks, powered by Sentinel, enforce compliance and security standards by evaluating plans before application. This setup ensures mandatory code review and automated policy enforcement, creating a secure and auditable change management process.
Use the Terraform CLI in the CI/CD pipeline with remote state
Run terraform apply locally after manual approval
An operator runs `terraform apply` and receives an error that the state file is locked. What is the most likely cause?
The state file is outdated and needs refresh
The configuration has a syntax error
Another user is running a Terraform operation
Terraform state locking is a critical mechanism designed to prevent data corruption when multiple operators attempt to modify the state file concurrently. When one user initiates a `terraform apply` or other state-modifying operation, Terraform attempts to acquire an exclusive lock on the state. If another user is already holding that lock, the subsequent operation will fail with a state lock error, indicating that the state is currently in use and preventing simultaneous, conflicting updates.
The user lacks write permissions to the state file
An organization wants to use Terraform to manage infrastructure in multiple environments (dev, staging, prod) with the same configuration but different variable values. Which approach should they use?
Create separate directories with duplicated configurations
Use Terraform workspaces and separate variable files
Terraform workspaces allow for managing multiple distinct states for a single configuration, effectively isolating environments like `dev`, `staging`, and `prod` within the same codebase. By combining workspaces with separate `*.tfvars` files for each environment, organizations can reuse the core infrastructure definition while providing environment-specific values for variables. This method ensures state isolation and parameter differentiation without duplicating the underlying configuration, promoting consistency and maintainability.
Use a single state file with environment variables
Use different versions of Terraform for each environment
A team uses Terraform Cloud with a VCS-backed workflow. They notice that a recent commit triggered a run that failed because of an invalid configuration. The team fixed the configuration and wants to re-run the plan without committing again. Which action should they take?
Amend the previous commit and force push
Create a new commit with the fix
Creating a new commit with the fix is the correct and standard procedure for a VCS-backed workflow in Terraform Cloud. This action pushes the updated configuration to the remote repository, which Terraform Cloud actively monitors for changes. Upon detecting the new commit, Terraform Cloud automatically initiates a new run (plan and potentially apply) using the corrected code, ensuring the infrastructure aligns with the intended state.
Use the 'Queue Plan' button in the Terraform Cloud UI
Run terraform plan locally and apply
Want more Use Terraform outside the core workflow practice?
Practice this domain12% of exam · 6 sample questions below
An engineer is refactoring a monolithic Terraform configuration into reusable modules. One module outputs a list of subnet IDs. Another module needs to use these subnet IDs to create resources. What is the best way to pass this data between modules?
Use a Terraform data source in the second module to query the subnets directly.
Define the subnet IDs as a variable in the first module and pass them to the second module via a remote state data source.
Store the subnet IDs in a local file and use the 'file' function to read them in the second module.
Output the subnet IDs from the first module and reference that output as an input variable in the second module's block.
This is the correct pattern: module outputs are consumed as module input variables.
A developer creates a module that provisions an AWS EC2 instance and an S3 bucket. The module outputs the instance ID and bucket ARN. When using this module, the root configuration references module.my_module.instance_id and module.my_module.bucket_arn. After running terraform apply, they notice that the bucket ARN is empty. What is the most likely cause?
The output is defined in the module but not in the root configuration.
The S3 bucket creation depends on another resource that hasn't been created yet.
The output value in the module is defined incorrectly, e.g., referencing a non-existent attribute.
When an output block within a module attempts to reference an attribute that does not exist on the specified resource, or uses an incorrect attribute path, Terraform often evaluates this expression to an empty string or a null value. This results in the module's output appearing empty when consumed by the root configuration, as the requested data simply isn't found at the specified location within the resource object. This is a common cause of unexpected empty outputs.
The IAM role used by Terraform does not have permission to read the bucket ARN.
After running 'terraform apply', the user sees that the 'aws_s3_bucket_object' is created successfully, but the bucket name is not as expected. What is the most likely reason?
The module variable 'bucket_name' is not consumed by the resource; the resource uses a hardcoded name.
The module output is incorrectly defined; it should use 'bucket' attribute instead of 'id'.
The module does not have an output for the bucket name, so the reference fails silently.
The output 'bucket_name' in the module is set to 'aws_s3_bucket.this.id', which is the bucket name, so the bucket name should be as expected.
The configuration appears correct; if the bucket name is not as expected, the issue might be elsewhere, but the output is correct.
You are a DevOps engineer at a company that manages infrastructure for multiple environments (dev, staging, prod) using Terraform. The team has created a reusable module for deploying an AWS ECS Fargate service. The module accepts variables for environment name, container image tag, and desired count. The module is stored in a private Git repository. The root configurations for each environment are stored in separate directories, each with its own backend configuration. Recently, a developer added a new feature to the module that requires a new variable 'enable_xray' (boolean, default false). After updating the module source to point to the new commit, the developer runs 'terraform init' and 'terraform plan' in the dev environment. The plan shows that the ECS service will be updated, but the output does not show any changes related to X-Ray. The developer expected that setting 'enable_xray = true' in the dev root module would enable X-Ray tracing. However, the plan shows no changes to the task definition. What is the most likely cause?
The module source was not updated correctly; it still points to the old commit.
The developer forgot to run 'terraform init' after changing the module source.
The variable 'enable_xray' is not declared in the module's variables.tf file.
The module does not reference the 'enable_xray' variable in any resource, so setting it has no effect.
For a variable to influence the infrastructure managed by Terraform, it must be actively referenced within the module's resource configurations, data sources, or outputs. In this scenario, while 'enable_xray' was declared and passed a value, no resource block or data source within the module's implementation actually uses 'var.enable_xray' to conditionally create, modify, or configure any infrastructure component. Consequently, changing the variable's value has no effect on the desired state of any managed object, leading 'terraform plan' to correctly report "no changes to infrastructure."
A team is using a module from the Terraform Registry. They want to ensure that changes to the module's source version are tested in a non-production environment before being applied to production. Which approach best supports this workflow?
Fork the module repository and manage the module internally as a private module.
Pin the module to an exact version (e.g., version = "1.2.3") and update it manually after testing in isolation.
Configure the module source to reference the latest commit from the default branch of the repository.
Use a version constraint like ~> 1.0 in the module configuration and test the module in a non-production workspace before promoting to production.
Using a pessimistic version constraint like `~> 1.0` allows for automatic updates to minor and patch versions (e.g., `1.1.x`, `1.2.x`) while preventing potentially breaking major version upgrades. This strategy, combined with thorough testing in a dedicated non-production workspace, ensures controlled adoption of module improvements and bug fixes before safely promoting changes to critical production environments. It effectively balances stability with the ability to receive necessary updates.
Refer to the exhibit. The configuration fails with an error indicating that the module does not support the 'enable_vpn_gateway' argument. What is the most likely cause?
The argument name is misspelled; it should be 'enable_vpn' instead.
The module version '3.18.0' does not include the 'enable_vpn_gateway' variable; it was added in a later version.
This option correctly identifies the root cause. When a module is explicitly pinned to a specific version, such as '3.18.0', Terraform strictly adheres to the variables and outputs defined within that exact module release. The `enable_vpn_gateway` variable was introduced in a subsequent version of the `terraform-aws-vpc` module, meaning it is not recognized or available in version '3.18.0', leading to an 'Unsupported Argument' or 'Undefined Variable' error during plan or apply.
The module does not support VPN gateways at all.
The module source is incorrectly specified; it should use a git URL instead of the registry path.
Want more Interact with Terraform modules practice?
Practice this domain12% of exam · 6 sample questions below
A team uses Terraform to manage infrastructure. After running 'terraform apply', a developer notices that a new security group rule was added, but then immediately removed. What is the most likely cause?
The security group rule was added manually and Terraform removed it to match the configuration.
Terraform's core principle is to manage infrastructure to match the desired state defined in its configuration files. When a security group rule is added manually outside of Terraform, it creates a "drift" between the actual infrastructure and Terraform's known desired state. During a subsequent `terraform apply` operation, Terraform detects this unmanaged rule and, in its effort to enforce the configured state, removes the rule to bring the infrastructure back into alignment with what is declared in the `.tf` files.
The state file was corrupted and Terraform performed a refresh.
The configuration was changed to remove the rule after the apply.
The developer accidentally ran 'terraform destroy' instead.
A DevOps engineer is troubleshooting a failed 'terraform apply'. The error message says: 'Error: Error applying IAM policy: The policy failed validation'. The IAM policy is defined using HCL in a JSON-encoded string. What is the most efficient way to debug this issue?
Run 'terraform plan' to see the detailed error.
Use 'terraform console' to test the policy string.
Use a JSON validator tool to check the policy string in the configuration.
A JSON validator tool is highly effective for identifying fundamental syntax errors within an IAM policy string embedded in Terraform configuration. These tools can quickly pinpoint issues like malformed JSON structure, incorrect escaping, missing commas, or unclosed brackets, which are common causes of policy validation failures. Catching these errors locally prevents terraform apply from failing due to basic JSON parsing issues, allowing the DevOps engineer to correct the policy before deployment attempts.
Upgrade to the latest Terraform version.
A team wants to ensure that all Terraform runs are recorded for audit purposes. Which practice should they implement?
Run 'terraform show' after every apply to capture state.
Add the state file to version control after each run.
Enable state locking in the backend configuration.
Configure a remote backend that supports state versioning.
Configuring a remote backend that supports state versioning is the recommended and most effective solution. Services like Amazon S3 with versioning or Azure Storage blobs automatically store a new, immutable version of the state file every time 'terraform apply' is executed. This creates a comprehensive, auditable history of all infrastructure changes, enabling easy rollback to previous states and ensuring all Terraform runs are reliably recorded for compliance and operational visibility.
Which TWO actions are part of the core Terraform workflow? (Choose two.)
terraform fmt
terraform plan
terraform plan is a fundamental command in the core Terraform workflow, serving as the crucial second step after initialization. This command generates an execution plan, detailing exactly what actions Terraform will perform to achieve the desired state defined in the configuration files. It allows users to review proposed changes—such as creating, updating, or destroying resources—before any actual modifications are made to the real infrastructure, ensuring predictability and preventing unintended consequences.
terraform validate
terraform apply
terraform apply is the critical final step in the core Terraform workflow, responsible for executing the actions proposed in a terraform plan to provision or modify infrastructure. This command prompts for confirmation (unless auto-approved) and then makes the necessary API calls to cloud providers or other services to create, update, or delete resources as defined in the configuration. It brings the real-world infrastructure into alignment with the desired state specified in the Terraform code.
terraform destroy
Which THREE of the following are valid reasons to use 'terraform refresh'? (Choose three.)
To update the state file when resources were deleted outside of Terraform.
terraform refresh reads the current state of real infrastructure and updates the Terraform state file to reflect any changes, including the absence of resources that were previously tracked but have since been deleted manually. This process ensures the state file accurately represents the infrastructure, marking deleted resources as "not found" and preparing them for removal from the state.
To detect drift between the state file and actual infrastructure.
terraform refresh compares the attributes of resources recorded in the Terraform state file with their actual current attributes in the cloud provider or on-premises environment. By updating the state file with these live attributes, it effectively identifies and records any configuration drift that has occurred since the last apply, making the discrepancies visible for subsequent plan operations.
To import existing infrastructure into Terraform management.
To update the state file after making manual changes to resources.
When manual modifications are made directly to infrastructure resources outside of Terraform (e.g., changing a security group rule via the AWS console), terraform refresh reads these updated attributes from the live infrastructure. It then writes these current values into the Terraform state file, ensuring that the state accurately reflects the post-manual-change configuration and preventing future terraform plan operations from proposing to revert these changes unnecessarily.
To update the Terraform configuration with current resource settings.
You are a DevOps engineer at a large e-commerce company. The infrastructure team uses Terraform to manage AWS resources across multiple accounts. Recently, they introduced a new module that creates an S3 bucket with a bucket policy. The module is used in several environments (dev, staging, prod). After merging a pull request that updates the bucket policy to grant cross-account access to a new partner account, the 'terraform apply' in the dev environment fails with: 'Error: Error putting S3 policy: AccessDenied: Access Denied'. The team is using a remote backend (S3) with DynamoDB locking. The CI/CD pipeline runs as an IAM role with permissions to manage infrastructure. The module uses 'aws_iam_policy_document' data source to construct the policy. The error occurs only in dev, not staging or prod. What is the most likely cause and the correct course of action?
Verify that DynamoDB state locking is not causing the error.
Run 'terraform validate' to check the policy document syntax.
Check the bucket policy for syntax errors by comparing with staging and prod.
Check the IAM permissions associated with the dev environment's role to ensure it has 's3:PutBucketPolicy' on the bucket.
The AccessDenied indicates the IAM role lacks permission to set the policy on that bucket.
Want more Use the core Terraform workflow practice?
Practice this domain12% of exam · 6 sample questions below
A team is using a remote backend in Terraform Cloud. After a failed apply, the state file is locked. The team lead wants to unlock the state immediately. What should be done?
Delete the state file from the backend and reinitialize
Run terraform force-unlock with the lock ID
The terraform force-unlock command with the lock ID manually releases the lock.
Manually edit the state file to remove the lock
Run terraform unlock
An organization uses Terraform with AWS S3 backend and DynamoDB for state locking. During a plan, you receive an error: 'Error acquiring the state lock'. The lock information in DynamoDB shows a lock from a previous session that crashed. What is the most appropriate next step?
Run terraform unlock
Run terraform force-unlock with the lock ID
This command releases the lock from the previous session.
Wait for the lock to expire automatically
Delete the lock item from DynamoDB table directly
A developer is working on a Terraform configuration that manages a single resource. They want to import an existing AWS EC2 instance into state. Which command should they use?
terraform apply
terraform refresh
terraform import
The `terraform import` command is the designated tool for bringing existing infrastructure resources, which were provisioned outside of Terraform's management, into the Terraform state file. It establishes a link between a specified remote resource and a corresponding resource block defined in the Terraform configuration. This crucial command enables developers to adopt pre-existing infrastructure and manage it subsequently with Terraform, integrating it into the desired state.
terraform state mv
After running terraform apply, you see the error: 'Error: Error loading state: state snapshot was created by Terraform v0.12.0, but this is Terraform v1.2.0'. What should you do to resolve this?
Run terraform state upgrade
Run terraform apply with no changes to upgrade the state format
When an older Terraform state file is detected by a newer version of the Terraform CLI, running `terraform apply` will automatically initiate an upgrade of the state format to the current version. Even if there are no configuration changes to apply, Terraform processes the existing state and writes it back in the updated format, resolving compatibility issues. This is the standard and recommended procedure for state file upgrades.
Delete the state file and reimport resources
Downgrade Terraform to v0.12.0
A user wants to remove a specific resource from Terraform state without destroying the actual infrastructure. Which command should they use?
terraform state rm resource
The `terraform state rm <address>` command is precisely designed to remove one or more resource instances from the Terraform state file. This operation updates the state to reflect that Terraform no longer manages the specified resource, but critically, it does not interact with the cloud provider or affect the actual infrastructure resource itself. The resource will continue to exist in the cloud, unmanaged by Terraform, making this the correct choice for decoupling a resource from state without destruction.
terraform taint resource
terraform state mv resource
terraform destroy -target=resource
A company uses Terraform to manage infrastructure across multiple AWS accounts. They want to use a single S3 bucket to store state files for all accounts, but ensure that state files are isolated per account. What is the best approach?
Use Terraform workspaces with a single state file
Use separate state files with unique S3 key prefixes per account
This approach correctly isolates Terraform state for each distinct AWS account. By configuring the S3 backend with unique `key` prefixes (e.g., `account-a/terraform.tfstate`, `account-b/terraform.tfstate`), each account's infrastructure state is stored in its own dedicated path within the S3 bucket. This prevents state file collisions, ensures independent management, and maintains clear separation of concerns across different environments or accounts.
Store all state in the same S3 key
Use a DynamoDB table with different lock IDs per account
Want more Implement and maintain state practice?
Practice this domain12% of exam · 6 sample questions below
A team wants to use Terraform to provision infrastructure across multiple cloud providers. Which configuration approach best supports this goal?
Define multiple provider blocks, one for each cloud provider.
Terraform configurations can declare multiple `provider` blocks to manage resources across different cloud platforms or services. Each `provider` block specifies the configuration for a particular infrastructure provider, such as `aws`, `azurerm`, or `google`. By defining distinct blocks, Terraform understands which provider to use for creating, updating, or deleting specific resources, enabling a single configuration to orchestrate infrastructure across a multi-cloud environment. This is the standard and intended method for multi-cloud deployments.
Use a single provider block that supports multiple clouds.
Terraform cannot manage multiple clouds in one configuration.
Create separate workspaces for each cloud provider.
A Terraform configuration uses a module from the Terraform Registry. After updating the module version in the configuration, the operator runs 'terraform plan' but does not see the changes expected from the new version. What is the most likely cause?
The operator did not run 'terraform get' to update modules.
The operator did not run 'terraform init' after changing the version.
When a module's version constraint is modified within the Terraform configuration, `terraform init` is the essential command to execute. This command re-evaluates all module requirements, downloads the newly specified module version into the `.terraform` directory, and updates the dependency lock file (`.terraform.lock.hcl`). Without running `init`, Terraform will continue to use the previously downloaded module version, leading to unexpected behavior or errors.
The operator did not run 'terraform refresh' to update state.
The module version constraint is stored in the state file and must be updated.
A developer wants to conditionally create a resource based on a variable that is a boolean. Which syntax should they use?
Use 'if var.create' inside the resource block
Use 'for_each = var.create ? [1] : []'
Use 'count = var.create'
Use 'count = var.create ? 1 : 0'
This is the correct and idiomatic pattern for conditionally creating a single resource in Terraform. The ternary operator `var.create ? 1 : 0` explicitly converts the boolean value of `var.create` into the required integer `0` or `1`. If `var.create` is `true`, `count` becomes `1`, ensuring the resource is created. If `var.create` is `false`, `count` becomes `0`, preventing the resource from being created or causing its destruction if it already exists.
An operator wants to pass output values from one Terraform configuration to another as input variables. Which approach is recommended?
Hardcode the output values in a variables file for the second configuration.
Store outputs in a shared file and use 'file()' function to read them.
Use a remote state data source to read the outputs from the first configuration's state.
Using a `terraform_remote_state` data source is the standard and recommended method for consuming outputs from a separate Terraform configuration. This data source securely reads the specified remote state file, allowing the second configuration to access the first's outputs directly and consistently. It establishes an implicit dependency, ensuring that the source configuration's state is available and up-to-date before the consuming configuration applies changes.
Use environment variables to pass the output values.
A Terraform configuration includes a resource block with a 'lifecycle' block that has 'create_before_destroy = true'. During an apply, the create step succeeds but the destroy step fails. What is the resulting state?
Only the new resource remains in state, old resource is destroyed.
The state is empty for that resource address.
Only the old resource remains in state.
Both the old and new resources are in state.
This option is correct. When a Terraform configuration is modified in a way that causes Terraform to perceive a new resource (e.g., changing a resource's logical name, or modifying `count`/`for_each` indices) while the original resource is not explicitly destroyed or its destruction fails, both resources will be tracked in the state file. The state reflects the current reality of the managed infrastructure, including any resources that were created but not yet removed.
A configuration uses variables defined in a 'variables.tf' file. The operator wants to override these variables for a specific run without modifying the file. Which method should they use?
Edit the state file directly.
Set environment variables with the same name as the variables.
Create a 'terraform.tfvars' file.
Use the '-var' flag with 'terraform plan' or 'terraform apply'.
The `-var` flag, used with commands like `terraform plan` or `terraform apply`, is the most direct and idiomatic way to provide or override variable values for a single Terraform execution. Values supplied via `-var` on the command line take the highest precedence, ensuring they are used for that specific run, and are not persisted for subsequent operations. This method is ideal for temporary adjustments, sensitive data, or testing different configurations without modifying files.
Want more Read, generate and modify configuration practice?
Practice this domainThe TF-004 exam has 57 questions and must be completed in 60 minutes. The passing score is 700/1000.
Scenario-based questions covering exam objectives with detailed answer explanations.
The exam covers 8 domains: Understand IaC concepts, Understand Terraform basics, Understand Terraform's purpose, Use Terraform outside the core workflow, Interact with Terraform modules, Use the core Terraform workflow, Implement and maintain state, Read, generate and modify configuration. Questions are weighted by domain — higher-weight domains appear more on your actual exam.
No. These are original exam-style practice questions written against the official HashiCorp TF-004 exam objectives. They are not copied from the real exam. Courseiva focuses on genuine understanding, not memorisation of braindumps.
Courseiva tracks your accuracy per domain and routes you toward weak areas automatically. Free, no account required.