Courseiva

HashiCorp Terraform Associate TF-004 (TF-004) — Questions 76150

428 questions total · 6pages · All types, answers revealed

Page 1

Page 2 of 6

Page 3
76
MCQeasy

Refer to the exhibit. Which command was most likely executed?

A.terraform apply
B.terraform plan
C.terraform get
D.terraform init
AnswerD

terraform init is the foundational command responsible for preparing a Terraform working directory for use. It performs several critical setup tasks, including discovering and downloading necessary provider plugins, configuring the backend for state storage, and recursively downloading all modules referenced in the configuration. The command's output explicitly includes messages like "Initializing modules," "Initializing provider plugins," and "Initializing the backend," directly matching the exhibit's likely "Initializing modules" output.

Why this answer

The exhibit shows Terraform downloading and installing provider plugins (e.g., hashicorp/aws) and initializing the backend configuration. This is the exact behavior of `terraform init`, which prepares the working directory for other commands by ensuring all required providers and modules are available.

Exam trap

The exam often tests the distinction between `terraform init` (which handles provider and backend setup) and `terraform get` (which only handles modules), leading candidates to confuse module downloading with provider initialization.

How to eliminate wrong answers

Option A is wrong because `terraform apply` executes the infrastructure changes defined in the configuration, not downloading providers or initializing backends. Option B is wrong because `terraform plan` creates an execution plan by comparing the current state with the configuration, but does not download providers or initialize backends. Option C is wrong because `terraform get` downloads and updates modules referenced in the configuration, but does not initialize backends or install provider plugins.

77
MCQmedium

An organization uses Terraform Cloud and wants to automate run triggers when a new version of a module is published in a private module registry. What is the recommended method?

A.Create a Git repository with versioned modules and use GitOps.
B.Configure a webhook in the private module registry to notify Terraform Cloud.
C.Schedule terraform plan to run periodically via cron.
D.Use the Terraform Cloud API to poll the registry for new versions.
AnswerB

Configuring a webhook in the private module registry allows for real-time, event-driven automation. When a new module version is published, the registry sends an HTTP POST request to a pre-configured endpoint in Terraform Cloud, notifying it of the change. This enables Terraform Cloud to immediately detect the new version and potentially trigger runs in workspaces that consume that module, facilitating seamless, automated updates without manual intervention or polling.

Why this answer

Terraform Cloud supports webhook notifications from private module registries. When a new module version is published, the registry can send an HTTP POST payload to a configured webhook URL in Terraform Cloud, which triggers a run in the associated workspace. This eliminates the need for polling or manual intervention, aligning with Terraform Cloud's event-driven automation model.

Exam trap

The trap is that candidates often confuse GitOps workflows (Option A) with Terraform Cloud's native webhook integration. Terraform Cloud uses webhooks from its own module registry (or Terraform Enterprise) to trigger runs when a new module version is published, not from general Git repository events.

How to eliminate wrong answers

Option A is wrong because Git repositories with versioned modules and GitOps workflows are not directly integrated with Terraform Cloud's run triggers; they require manual or CI/CD pipeline steps to initiate runs, not automatic triggers upon module publication. Option C is wrong because scheduling `terraform plan` via cron is inefficient, introduces latency, and does not provide real-time triggering when a new module version is published; it also wastes resources on unnecessary plan runs. Option D is wrong because polling the Terraform Cloud API for new module versions is not a recommended pattern; it adds complexity, API rate limits, and latency compared to the push-based webhook mechanism.

78
MCQhard

A company uses Terraform with a remote backend (AWS S3). They want to ensure that the state file is encrypted at rest. Which configuration approach guarantees this?

A.Configure the S3 backend with server-side encryption enabled (e.g., 'encrypt = true' and 'kms_key_id').
B.Enable encryption in the AWS provider block.
C.Use 'terraform state encrypt' command.
D.Use 'terraform init -encrypt-state' flag.
AnswerA

S3 backend encryption encrypts state at rest.

Why this answer

The S3 backend configuration block supports the `encrypt` and `kms_key_id` arguments, which enable server-side encryption (SSE-S3 or SSE-KMS) for the state file stored in the S3 bucket. This ensures that the state file is encrypted at rest, meeting the requirement without any additional steps or external commands.

Exam trap

The trap here is that candidates confuse provider-level encryption settings (which don't exist) with backend-level encryption, or assume a CLI flag like `-encrypt-state` exists, when in fact encryption must be explicitly declared in the backend configuration block.

How to eliminate wrong answers

Option B is wrong because the AWS provider block configures authentication and region settings, not storage-level encryption; it has no effect on S3 server-side encryption for the state file. Option C is wrong because there is no `terraform state encrypt` command in Terraform; state encryption is handled at the backend level, not via a CLI subcommand. Option D is wrong because `terraform init` does not support an `-encrypt-state` flag; encryption is configured in the backend block, not during initialization.

79
MCQmedium

Refer to the exhibit. Which change to the configuration would prevent this error in the future?

A.Hardcode a different AMI ID.
B.Set the AMI to null.
C.Add a lifecycle rule to ignore changes.
D.Use a data source to fetch the AMI dynamically.
AnswerD

Using a data source to fetch the AMI dynamically is the correct and most robust solution. A data source, such as `aws_ami`, queries the AWS API at `terraform plan` time, using filters (e.g., owner, name patterns, tags) to retrieve the most current and valid AMI ID that matches the specified criteria. This ensures that the EC2 instance is always provisioned with an existing and up-to-date image, effectively preventing `InvalidAMIID.NotFound` errors caused by stale or hardcoded values.

Why this answer

Using a data source to dynamically fetch the correct AMI avoids hardcoding invalid IDs and ensures the AMI exists in the region.

80
Multi-Selectmedium

Which TWO scenarios require the use of the depends_on argument?

Select 2 answers
A.When a resource uses the output of another resource in its arguments.
B.When a provisioner creates resources that other resources depend on.
C.When Terraform cannot automatically infer an implicit dependency.
D.When a resource uses the output of a data source in its arguments.
E.When a resource uses a module output as an input.
AnswersB, C

Provisioners execute arbitrary scripts or commands on a resource, often interacting with external systems or creating entities that Terraform itself does not manage directly. Because Terraform cannot introspect or track the side effects of these external operations, any subsequent Terraform-managed resource that relies on an outcome of a provisioner's execution will not have an automatically inferred dependency. In such cases, an explicit depends_on argument is essential to force the correct ordering, ensuring the provisioner completes its task before dependent resources are evaluated.

Why this answer

When a provisioner (such as a local-exec or remote-exec) creates resources outside of Terraform's state, Terraform cannot automatically detect the dependency. The depends_on argument explicitly tells Terraform to wait for that provisioner-created resource before proceeding. Option C is correct because depends_on is the mechanism to declare a dependency when Terraform's resource graph analysis cannot infer an implicit dependency from attribute references.

Exam trap

HashiCorp Terraform often tests the misconception that any cross-resource reference requires depends_on, when in fact Terraform automatically infers dependencies from direct attribute references, and depends_on is only needed for non-attribute-based or provisioner-created dependencies.

81
MCQeasy

Refer to the exhibit. A team deploys this configuration. They run 'terraform apply' once and the instance is created. Later, they modify the instance type and run 'terraform apply' again. They notice the provisioner does not run on the second apply. Why?

A.Provisioners run only when the resource is destroyed.
B.The provisioner should be 'remote-exec' to run on updates.
C.The command syntax is incorrect.
D.Provisioners run only when the resource is created, not on subsequent updates.
AnswerD

Provisioners are not re-run on updates unless triggers specify.

Why this answer

Provisioners in Terraform are designed to run only during resource creation, not during subsequent updates. When the instance type is modified and 'terraform apply' is run again, Terraform updates the existing resource in place without triggering the provisioner again. This behavior is intentional because provisioners are typically used for initial setup tasks like bootstrapping, not for ongoing configuration changes.

Exam trap

Terraform often tests the misconception that provisioners run on every 'terraform apply' regardless of the resource lifecycle, leading candidates to overlook the creation-only default behavior.

How to eliminate wrong answers

Option A is wrong because provisioners can run on creation, not only on destruction; they can also run on destroy if the 'on_failure' and 'when' attributes are set appropriately. Option B is wrong because the type of provisioner (local-exec vs remote-exec) does not affect whether it runs on updates; both types only run on creation by default. Option C is wrong because the command syntax is not the issue; the question explicitly states the instance is created successfully on the first apply, so the syntax is correct.

82
MCQmedium

Refer to the exhibit. A user runs 'terraform plan' and sees this output. However, when they run 'terraform apply', they get an error: 'Error creating EC2 instance: UnauthorizedOperation: You are not authorized to perform this operation.' The user's IAM permissions allow ec2:RunInstances. What is the most likely missing permission?

A.ec2:CreateNetworkInterface
B.iam:PassRole
C.ec2:TerminateInstances
D.ec2:DescribeInstances
AnswerA

When creating an EC2 instance, AWS automatically provisions a primary network interface (ENI) for it, even if not explicitly configured in Terraform. This ENI handles network connectivity, including IP addresses and security groups. The `UnauthorizedOperation` error during `terraform plan` for an EC2 instance creation often indicates that the IAM principal (user or role) executing Terraform lacks the necessary `ec2:CreateNetworkInterface` permission to perform this underlying AWS API call. Without this permission, the instance provisioning fails at a fundamental networking step.

Why this answer

Creating an EC2 instance often requires permissions for related resources like network interfaces, security groups, etc. The error 'UnauthorizedOperation' despite having ec2:RunInstances suggests missing permissions for other actions. Option A is correct because the instance might require a subnet and network interface, and without ec2:CreateNetworkInterface permission, the operation fails.

83
MCQhard

A team uses Terraform with remote state in Azure Storage. They have a CI/CD pipeline that runs terraform plan and apply. Recently, a team member ran terraform apply manually from their local machine and the process crashed due to a network interruption. Now, the pipeline's next run fails with an error: "Error: Error acquiring the state lock". The team is unsure who holds the lock. They need to proceed with the pipeline as soon as possible. What should they do?

A.Use terraform force-unlock with the lock ID to break the lock.
B.Wait for the lock to expire automatically.
C.Re-run terraform apply with -lock=false to skip locking.
D.Delete the .terraform folder and reinitialize.
AnswerA

When a Terraform operation fails midway, it can leave a state lock in place, preventing subsequent operations. The `terraform force-unlock` command is specifically designed to manually release such a "stuck" lock. It requires the lock ID, which can typically be found in the error message of the failed operation or by inspecting the backend. While effective, it must be used with extreme caution to avoid concurrent state modifications and potential corruption, ensuring no other operations are genuinely running.

Why this answer

The correct action is to use `terraform force-unlock` with the lock ID to break the stale lock. When a Terraform process crashes while holding a state lock (stored in Azure Blob Storage via the `azurerm` backend), the lock remains in place, blocking all subsequent operations. The `force-unlock` command is the designed mechanism to manually release such locks, and the lock ID can be obtained from the error message or by querying the Azure Storage blob's lease state.

Exam trap

HashiCorp often tests the misconception that `-lock=false` is a safe workaround for lock issues, but in reality it bypasses safety guarantees and can lead to state corruption, while `force-unlock` is the correct, intended recovery command.

How to eliminate wrong answers

Option B is wrong because Terraform state locks do not have a built-in expiration mechanism; they persist until explicitly released, so waiting will not resolve the issue. Option C is wrong because using `-lock=false` skips lock acquisition entirely, which risks concurrent state modifications and data corruption, and is not a safe or recommended practice for resolving a stuck lock. Option D is wrong because deleting the `.terraform` folder and reinitializing only clears local cached data and provider plugins; it does not affect the remote state lock held in Azure Storage, so the pipeline would still fail with the same lock error.

84
MCQmedium

A development team is using a declarative IaC tool. They make a change to the configuration file to add a new security group rule. When they apply the configuration, the tool automatically modifies the existing security group to add the rule. What is this behavior called?

A.Desired state reconciliation
B.Provisioning
C.Imperative execution
D.Resource drift
AnswerA

Declarative IaC tools continuously perform desired state reconciliation by comparing the current actual infrastructure state with the configuration defined as the desired state. This process automatically identifies any discrepancies and applies the necessary changes, such as creating, updating, or deleting resources, to bring the infrastructure into full alignment. This ensures that the deployed environment consistently matches the specified blueprint, automating infrastructure management and preventing configuration drift.

Why this answer

This behavior is called desired state reconciliation because declarative IaC tools like Terraform or AWS CloudFormation compare the current state of infrastructure against the desired state defined in the configuration file. When a new security group rule is added to the configuration, the tool automatically computes the necessary changes to reconcile the actual state with the desired state, creating, updating, or deleting resources as needed. This is a core principle of declarative IaC, where the user specifies the 'what' and the tool handles the 'how'.

Exam trap

The trap here is that candidates confuse the automatic correction of drift with the initial provisioning process, or they mistakenly think that any automated change is 'imperative execution' rather than recognizing the declarative reconciliation loop.

How to eliminate wrong answers

Option B is wrong because provisioning refers to the initial creation and setup of infrastructure resources, not the ongoing process of modifying existing resources to match a desired configuration. Option C is wrong because imperative execution involves explicitly scripting each step (e.g., using AWS CLI commands to add a rule), whereas the question describes a declarative tool that automatically determines the actions. Option D is wrong because resource drift is a condition where the actual state of infrastructure diverges from the desired state over time, not the automatic correction of that divergence through reconciliation.

85
MCQhard

A developer runs `terraform plan` and receives the error: "Error: Unsupported argument; An argument named 'enable_vpn_gateway' is not expected here." What is the most likely cause?

A.The source address is misspelled 'vpc' instead of 'vpc/aws'.
B.The source module is not pinned to a specific version, so it may have changed.
C.The module must be sourced from a different registry or repository.
D.The module version 5.0.0 does not support the 'enable_vpn_gateway' argument.
AnswerD

This option is correct because an error stating an argument like 'enable_vpn_gateway' is 'unexpected' or 'not expected' for a specific module version (e.g., 5.0.0) is a direct indication of an API change. Module developers often introduce breaking changes, such as removing, renaming, or altering input variables, especially in major version increments. This means the argument was likely supported in a previous version but has since been deprecated or removed in version 5.0.0, requiring the user to update their configuration to align with the module's current interface.

Why this answer

The error 'Unsupported argument' indicates that the module version currently in use does not define an input variable named 'enable_vpn_gateway'. In Terraform, each module version has a fixed set of input variables; if you attempt to pass an argument that is not declared in the module's variables.tf, Terraform will reject it. The most common reason for this is that the module version has been updated or changed, and the argument was removed or renamed in that version.

Exam trap

HashiCorp often tests the distinction between errors caused by module version changes versus errors caused by source configuration issues, trapping candidates who confuse a missing variable error with a source path or registry problem.

How to eliminate wrong answers

Option A is wrong because the error message specifically says 'An argument named 'enable_vpn_gateway' is not expected here', which is about an unexpected argument, not about a misspelled source address; a misspelled source would cause a 'source not found' or 'module not found' error. Option B is wrong because while not pinning a version can lead to unexpected changes, the error itself is about the current module's input schema, not about version drift; the error would occur even if the version is pinned to a version that lacks the argument. Option C is wrong because the source registry or repository does not affect which arguments are supported; the argument support is determined by the module's code, not its location.

86
MCQeasy

A team uses an S3 backend for Terraform state. During a `terraform apply`, another team member accidentally runs a plan that also modifies the same state. Which feature prevents state corruption in this scenario?

A.The `-lock=false` flag
B.Terraform Cloud remote operations
C.State locking via DynamoDB
D.State versioning in S3
AnswerC

State locking via DynamoDB is the correct and recommended mechanism for protecting Terraform state when using an S3 backend. Terraform utilizes a DynamoDB table to acquire and release a distributed lock before and after state modifications, ensuring that only one `terraform apply` or `terraform destroy` operation can proceed at a time. This prevents race conditions, safeguards state consistency, and avoids corruption in shared development or production environments.

Why this answer

State locking via DynamoDB prevents concurrent modifications to the state file, ensuring that only one operation can modify the state at a time. Option A (-lock=false) disables locking, which would allow concurrent modifications and risk corruption. Option B (Terraform Cloud remote operations) is not directly related to state locking in this S3 backend scenario.

Option D (state versioning) helps recover from corruption but does not prevent simultaneous writes.

87
MCQmedium

A developer creates a module in a subdirectory of their Terraform configuration and wants to reference it from the root module. The directory structure is: /terraform-project/modules/networking. Which source argument should they use in the module block?

A.source = "file:///terraform-project/modules/networking"
B.source = "/terraform-project/modules/networking"
C.source = "./modules/networking"
D.source = "hashicorp/networking/aws"
AnswerC

This source string correctly uses a relative path, starting with `./`, indicating that the module is located in a `modules/networking` subdirectory relative to the current Terraform configuration file. This is the standard and most portable method for referencing local modules within the same repository. Terraform resolves this path from the directory containing the calling module, ensuring consistency across different execution environments.

Why this answer

Terraform resolves local module paths relative to the root module's directory. The path `./modules/networking` correctly references the `networking` subdirectory within the `modules` folder, starting from the root of the Terraform configuration. This is the standard syntax for referencing a local module in a subdirectory.

Exam trap

HashiCorp often tests the distinction between local module paths (which must start with `./` or `../`) and registry module paths (which use a namespace/name/provider format), causing candidates to mistakenly choose an absolute path or a registry-style source for a local module.

How to eliminate wrong answers

Option A is wrong because `file://` is not a valid Terraform module source protocol; Terraform uses `./` or absolute paths for local modules, not file URIs. Option B is wrong because `/terraform-project/modules/networking` is an absolute filesystem path that would only work if the root module were at the filesystem root, which is not the case here; Terraform expects relative paths starting with `./` or `../` for local modules. Option D is wrong because `hashicorp/networking/aws` is a Terraform Registry source format, which would attempt to download a public module from the registry, not reference a local directory.

88
MCQmedium

A developer is reviewing a terraform plan output and sees that a resource of type "aws_instance" with name "web" will be updated. The developer expected no changes because the configuration hasn't been modified. The instance was manually resized in the AWS console by another team. The developer wants to reconcile the state without destroying the instance. What should they do?

A.Run terraform apply -refresh-only to update the state to match reality.
B.Run terraform state rm aws_instance.web and then terraform import.
C.Manually edit the state file to match the instance attributes.
D.Run terraform apply with -target=aws_instance.web to update only that resource.
AnswerA

When infrastructure resources have been modified outside of Terraform (a condition known as drift), `terraform apply -refresh-only` is the precise command to update Terraform's state file to reflect these real-world changes. This operation queries the cloud provider for the current attributes of all managed resources and updates the state file accordingly, without making any alterations to the actual infrastructure. It effectively synchronizes Terraform's understanding with reality, acknowledging external modifications and preventing Terraform from attempting to revert them in subsequent `apply` operations.

Why this answer

`terraform apply -refresh-only` updates the Terraform state to match the actual infrastructure without making any configuration changes. This command reads the current state of the `aws_instance.web` resource from AWS and writes it to the state file, reconciling the drift caused by the manual resize. It does not destroy or recreate the instance, preserving the existing resource.

Exam trap

HashiCorp often tests the distinction between `terraform apply -refresh-only` and `terraform apply` with `-target`, where candidates mistakenly think targeting a resource will only refresh it, but in reality `-target` still applies configuration changes and can cause updates or destruction.

How to eliminate wrong answers

Option B is wrong because `terraform state rm` followed by `terraform import` is unnecessarily destructive and complex; it removes the resource from state entirely, which could cause Terraform to plan a destroy on the next apply if the configuration still references it, and re-importing requires knowing the exact resource ID. Option C is wrong because manually editing the state file is error-prone, unsupported, and violates Terraform's principle of using the CLI to manage state; it can lead to corruption or inconsistencies. Option D is wrong because `terraform apply -target=aws_instance.web` would attempt to apply the configuration to that resource, which would likely trigger an update or destroy/recreate action based on the configuration, not just refresh the state; it does not reconcile drift without changes.

89
MCQeasy

An engineer modifies a Terraform configuration by increasing the instance_count for an AWS EC2 resource from 2 to 5. After running terraform plan, which change will be displayed?

A.One new resource will be created and two modified.
B.Two existing resources will be destroyed and five new created.
C.Three new resources will be created, two unchanged.
D.All five resources will be updated in-place.
AnswerC

When the `count` meta-argument for a resource block is increased (e.g., from 2 to 5), Terraform identifies the existing instances (indices 0 and 1) and marks them as unchanged, assuming no other attributes were modified. The plan then indicates the creation of the additional instances required to reach the new total count (indices 2, 3, and 4), resulting in three new resources being created.

Why this answer

Terraform's `instance_count` meta-argument uses a count-based resource management strategy. When the count increases from 2 to 5, Terraform treats the existing resources (index 0 and 1) as unchanged and plans to create three new resources (indices 2, 3, and 4). No in-place updates or destructions occur because the existing resources' configurations remain identical.

Exam trap

A common misconception is that increasing `instance_count` triggers an in-place update or partial modification of existing resources, when in fact Terraform treats each index as an independent resource and only creates new ones.

How to eliminate wrong answers

Option A is wrong because increasing `instance_count` does not modify existing resources; it only adds new ones, so no 'modified' resources appear. Option B is wrong because Terraform does not destroy existing resources when scaling up; it preserves them and creates additional instances. Option D is wrong because Terraform does not update all five resources in-place; the existing two resources remain unchanged, and only the three new ones are created.

90
MCQmedium

An organization uses Terraform to deploy resources on AWS. They have separate configuration files for development, staging, and production. To differentiate these environments, they plan to use the same root module with different variable values. Which Terraform feature best supports this use case?

A.Terraform modules
B.Remote state backends
C.Multiple provider configurations
D.Terraform workspaces
AnswerD

Workspaces allow multiple state files for the same configuration, ideal for environments.

Why this answer

Terraform workspaces allow you to manage multiple distinct state files within a single configuration directory, enabling you to use the same root module with different variable values for development, staging, and production environments. Each workspace maintains its own state data, so you can apply the same configuration to different environments by switching workspaces and providing environment-specific variable values.

Exam trap

The trap here is that candidates often confuse workspaces with modules or provider configurations, thinking that modules or multiple providers inherently provide environment isolation, when in fact workspaces are the specific Terraform feature designed to manage multiple environments with the same root module.

How to eliminate wrong answers

Option A is wrong because Terraform modules are reusable configuration packages that encapsulate resources, but they do not inherently differentiate environments or manage separate state files; they are used for code organization and reuse, not for environment isolation. Option B is wrong because remote state backends store state files remotely (e.g., S3, Azure Storage), but they do not provide a mechanism to separate environments within the same configuration; they are a storage mechanism, not an environment management feature. Option C is wrong because multiple provider configurations allow you to define different provider instances (e.g., different AWS regions or accounts), but they do not create separate state files or variable sets for the same root module; they are used for multi-region or multi-account deployments, not for environment differentiation within a single configuration.

91
MCQeasy

A company wants to adopt infrastructure as code (IaC) to manage their expanding cloud environment. Which problem does Terraform directly address?

A.Ensuring applications are highly available across regions
B.Automating software installation and patching on servers
C.Eliminating manual configuration drift across environments
D.Providing real-time monitoring and alerting for infrastructure
AnswerC

Terraform excels at eliminating manual configuration drift by enforcing a desired state model for infrastructure. It defines infrastructure declaratively in code, and during an `apply` operation, Terraform compares the current actual state of the infrastructure with this desired configuration. Any discrepancies, whether accidental manual changes or unapplied updates, are identified and can be automatically reconciled, ensuring environments remain consistent and aligned with their codified definition.

Why this answer

Terraform directly addresses the problem of manual configuration drift by enabling infrastructure as code (IaC), where the entire infrastructure state is defined in declarative configuration files. It uses a desired-state model: Terraform compares the current state of resources against the configuration and automatically reconciles any differences, ensuring environments remain consistent and drift is eliminated without manual intervention.

Exam trap

Candidates often confuse Terraform's purpose of infrastructure provisioning with configuration management tools like Ansible or Chef. Option B might be chosen because it deals with software installation, but Terraform is not a configuration management tool; it focuses on managing infrastructure resources declaratively.

How to eliminate wrong answers

Option A is wrong because Terraform is a provisioning tool, not a high-availability solution; ensuring applications are highly available across regions requires architectural patterns (e.g., multi-region deployment, load balancing, failover) and is outside Terraform's scope. Option B is wrong because automating software installation and patching on servers is the domain of configuration management tools like Ansible, Chef, or Puppet, not Terraform, which focuses on infrastructure provisioning and lifecycle management. Option D is wrong because real-time monitoring and alerting for infrastructure is handled by observability platforms such as Prometheus, CloudWatch, or Datadog, not by Terraform, which has no built-in monitoring or alerting capabilities.

92
MCQmedium

A team is writing Terraform configurations for a multi-region deployment. They want to use a module from the public Terraform Registry that provisions AWS VPCs. The module has been updated recently, but the team wants to ensure that all deployments use the same version of the module to avoid unexpected changes. Which configuration approach should they take to lock the module version?

A.Run 'terraform lock' on the module to record its version in the dependency lock file.
B.Use the 'version' argument in the module block to specify the exact version.
C.Reference the module source with a git URL and tag, such as 'git::https://github.com/...?ref=v1.0'.
D.Set the 'required_version' argument in the root module to match the module's version.
AnswerB

Using the 'version' argument within a module block is the standard and recommended method for specifying and pinning the exact version of a module, especially when sourcing from the Terraform Registry. This ensures that Terraform downloads and utilizes only the specified module version, providing crucial predictability and preventing unintended changes or breaking updates from newer module releases. This explicit version constraint is vital for maintaining configuration stability and reproducibility.

Why this answer

The 'version' argument in a module block is the standard Terraform mechanism for pinning a module from the Terraform Registry to a specific semantic version. This ensures that all deployments use the exact same module version, preventing unexpected changes from newer releases. The version constraint is evaluated against the registry's metadata and enforces the specified version during 'terraform init'.

Exam trap

HashiCorp often tests the distinction between module version pinning (using 'version' in the module block) and provider version pinning (using 'required_providers' and the lock file), leading candidates to confuse 'terraform lock' or 'required_version' as valid mechanisms for locking module versions.

How to eliminate wrong answers

Option A is wrong because 'terraform lock' is not a valid Terraform command; the dependency lock file (.terraform.lock.hcl) is automatically managed by 'terraform init' and records provider version hashes, not module versions. Option C is wrong because while using a git URL with a tag does pin a version, it bypasses the Terraform Registry's version resolution and is not the recommended approach for modules sourced from the registry; the question specifically asks about a module from the public Terraform Registry. Option D is wrong because 'required_version' in the root module sets a constraint on the Terraform CLI version, not on module versions.

93
MCQmedium

A developer creates a directory structure with a module located at './modules/networking'. The root configuration references it with source = './modules/networking'. What is the behavior when running terraform init from the root directory?

A.Terraform uses the module directly from the local filesystem.
B.Terraform requires a network connection to verify the module.
C.Terraform attempts to download the module from the public registry.
D.Terraform returns an error because the module path is not absolute.
AnswerA

When a module source is specified as a relative or absolute path, Terraform directly accesses the module's contents from the local filesystem. During `terraform init`, Terraform simply ensures the directory exists and contains valid configuration files, without any download operations. This direct access means the module is immediately available for use within the configuration, leveraging the local directory structure.

Why this answer

When a module source is a relative path like './modules/networking', Terraform interprets it as a local filesystem path. During `terraform init`, Terraform reads the module directly from the specified directory without any network access, downloading, or registry interaction. This is the standard behavior for local module references in Terraform.

Exam trap

HashiCorp often tests the misconception that Terraform always requires network access or absolute paths for modules, but the trap here is that local relative paths are fully supported and require no network, no registry, and no absolute path specification.

How to eliminate wrong answers

Option B is wrong because local module paths do not require any network connection; Terraform accesses the filesystem directly. Option C is wrong because Terraform only attempts to download from the public registry when the source is a registry address (e.g., 'hashicorp/consul/aws'), not a local path. Option D is wrong because Terraform accepts relative paths for local modules; absolute paths are not required, and relative paths are resolved from the root module's directory.

94
MCQhard

A team member runs terraform apply with the configuration shown in the exhibit. The apply succeeds, but the output of the local-exec provisioner shows an empty string for the public IP address. What is the most likely cause?

A.There is a dependency cycle between the aws_instance and null_resource causing Terraform to skip the provisioner.
B.The local-exec provisioner only runs during terraform destroy, not during apply.
C.The aws_instance resource does not have a public IP assigned because it is launched in a default VPC without auto-assign public IP, and no Elastic IP is attached.
D.The provisioner cannot access the aws_instance resource's attributes because it is defined in a separate resource block.
AnswerC

By default, EC2 instances launched into a default VPC do not automatically receive a public IP address unless the specific subnet's 'Auto-assign public IPv4 address' setting is enabled, or an Elastic IP (EIP) is explicitly associated with the instance. If neither of these conditions is met, the `aws_instance.public_ip` attribute will remain empty. This absence prevents the provisioner from establishing a connection using a public IP, leading to connection failures.

Why this answer

The `local-exec` provisioner runs on the machine executing Terraform, not on the AWS instance itself. If the instance is launched in a default VPC without `auto-assign public IP` enabled and no Elastic IP is attached, the `self.public_ip` attribute will be an empty string. The provisioner then outputs that empty string, as it simply reads the attribute value from the resource state.

Exam trap

HashiCorp often tests the misconception that `local-exec` runs on the remote instance or that `self.public_ip` is always populated, when in reality it depends on the network configuration and the provisioner's execution context.

How to eliminate wrong answers

Option A is wrong because a dependency cycle would cause Terraform to error out during planning, not silently skip the provisioner; the apply succeeded, so no cycle exists. Option B is wrong because `local-exec` provisioners run during `terraform apply` by default, not only during destroy; `destroy-time` provisioners require explicit `when = destroy`. Option D is wrong because provisioners can access attributes of any resource in the configuration, including `aws_instance`, as long as the resource is referenced (e.g., via `self` or a direct reference); the `null_resource` has a `depends_on` ensuring the instance exists.

95
MCQmedium

Refer to the exhibit. A Terraform configuration includes an `aws_instance.web` resource. The state shows the instance with a specific AMI and instance type. After running `terraform plan`, Terraform reports no changes. However, an engineer observes that the actual instance in AWS has a different AMI ID but the same instance type. What is the most likely cause?

A.The instance type was modified after the last apply, but AMI was not
B.The state file has not been refreshed since the manual AMI change; it still reflects the old AMI
C.The `terraform plan` command ignores drift by default
D.The AMI data source is returning a different value each time
AnswerB

Terraform compares state to config, not state to real world, unless refresh happens.

Why this answer

The state file is stale because it has not been refreshed since the AMI was manually changed outside of Terraform. When `terraform plan` runs, by default it first refreshes the state, but if the manual change occurred before the last refresh, the plan would have detected drift. However, if no refresh has occurred after the manual change, the plan compares the configuration with the old state, showing no changes.

The issue is that the state file still reflects the old AMI. Option B correctly identifies that the state has not been refreshed since the manual change.

96
MCQmedium

During a terraform apply, the state file becomes corrupted. What is the recommended recovery method?

A.Restore from backup
B.Re-run apply
C.Delete the state and re-import all resources
D.Use terraform state pull
AnswerA

When a Terraform state file becomes corrupted, the most reliable and recommended recovery strategy is to restore it from a recent, uncorrupted backup. Remote state backends, such as AWS S3 or Azure Blob Storage, automatically version and store previous states, making restoration straightforward. This approach ensures the state accurately reflects the infrastructure, preventing drift and potential resource destruction or recreation during subsequent `terraform apply` operations. It minimizes data loss and operational disruption, maintaining infrastructure integrity.

Why this answer

The recommended recovery method for a corrupted Terraform state file is to restore it from a known good backup. Terraform does not have built-in corruption repair mechanisms, so maintaining regular backups of the state file (e.g., using remote backends with versioning like S3 versioning or Terraform Cloud) is the standard operational practice. Restoring from backup ensures the state accurately reflects the real-world infrastructure without manual intervention.

Exam trap

The misconception tested in this question is that Terraform has a built-in repair command like `terraform state pull` or that re-running `terraform apply` can recover from corruption. In reality, the only reliable recovery method is restoring from a known good backup of the state file.

How to eliminate wrong answers

Option B is wrong because re-running `terraform apply` without a valid state file will fail or attempt to create duplicate resources, as Terraform cannot reconcile the existing infrastructure without a correct state. Option C is wrong because deleting the state and re-importing all resources is error-prone, time-consuming, and may lead to configuration drift or missed dependencies; it is not a recommended recovery method. Option D is wrong because `terraform state pull` retrieves the current state from a configured backend but does not fix corruption; if the state is already corrupted, pulling it only retrieves the corrupted data.

97
Multi-Selecteasy

Which TWO of the following commands can be used to read and inspect the current Terraform state? (Select TWO.)

Select 2 answers
A.terraform state show
B.terraform validate
C.terraform state list
D.terraform output
E.terraform plan
AnswersA, C

The terraform state show <ADDRESS> command is used to display the attributes of a single resource instance or module as recorded in the Terraform state file. It provides a detailed, human-readable output of the resource's current state, including its configuration and any computed values. This command is essential for inspecting the exact properties of a managed infrastructure component without interacting with the live cloud provider.

Why this answer

`terraform state show` is correct because it displays the attributes and metadata of a specific resource within the Terraform state file, allowing you to inspect the current state of that resource. `terraform state list` is correct because it lists all resources tracked in the state file, providing a high-level overview of what Terraform is managing. Both commands directly read and inspect the state without modifying it.

Exam trap

In Terraform, it's easy to confuse commands that inspect state versus those that read configuration or outputs. The trap here is that candidates may think `terraform output` or `terraform plan` are state inspection commands, but they serve different purposes: `output` shows output values, and `plan` creates a diff against state, not a direct state read.

98
MCQmedium

Refer to the exhibit. The user runs 'terraform plan' and sees that Terraform wants to create the instance. However, the instance already exists in the AWS account with the same configuration. What is the most likely reason?

A.The instance type has changed
B.The instance is not in the Terraform state
C.The AMI ID has changed
D.The provider version is different
AnswerB

Terraform's `plan` command operates by comparing the desired state defined in the configuration files with the actual state recorded in its state file and the real-world infrastructure. If an `aws_instance` resource is defined in the configuration but is entirely absent from the Terraform state file, Terraform will interpret this as a new resource that needs to be provisioned. Consequently, even if an identical instance physically exists in AWS, Terraform will propose to `create` it because it has no record of managing that existing resource.

Why this answer

Terraform determines whether to create, update, or destroy resources by comparing the desired configuration in the .tf files against the current state stored in the state file. If the instance already exists in AWS but is not recorded in the Terraform state, Terraform has no knowledge of it and will plan to create a new resource. This is the most likely reason because the instance is present in the account but absent from the state, causing Terraform to treat it as a new resource.

Exam trap

The Terraform exam often tests the misconception that Terraform automatically detects existing resources in the cloud provider, but in reality Terraform relies entirely on its state file to know what it manages, and any resource not in the state is treated as new regardless of its existence in the cloud.

How to eliminate wrong answers

Option A is wrong because if the instance type had changed, Terraform would detect a drift and plan to update (modify) the existing resource, not create a new one. Option C is wrong because a changed AMI ID would also result in a planned update or replacement (destroy and recreate), not a pure create action. Option D is wrong because a different provider version might cause compatibility warnings or errors, but it would not cause Terraform to ignore an existing resource in the state; the state file is version-independent for resource tracking.

99
MCQhard

An organization is evaluating IaC tools and wants to minimize configuration drift. Which characteristic of a declarative IaC approach is most effective in preventing drift?

A.Periodic state comparison and correction
B.Manual approval gates
C.Tagging resources
D.Using modules
AnswerA

Periodic state comparison and correction is the core mechanism by which declarative Infrastructure as Code tools like Terraform prevent configuration drift. Terraform maintains a desired state in its configuration files and a record of the actual infrastructure state in its state file. During a `terraform plan` operation, it compares these two states, identifying any discrepancies, and then `terraform apply` can be used to reconcile the actual infrastructure with the desired configuration, effectively correcting any drift.

Why this answer

A declarative IaC approach defines the desired end state of infrastructure, and tools like Terraform use periodic state comparison (e.g., `terraform plan` and `terraform apply`) to detect and correct any configuration drift. This automated reconciliation ensures the actual infrastructure matches the declared configuration, directly preventing drift without manual intervention.

Exam trap

HashiCorp often tests the misconception that drift prevention is achieved through code organization (modules) or operational controls (approvals), rather than the core declarative mechanism of automated state comparison and correction.

How to eliminate wrong answers

Option B is wrong because manual approval gates (e.g., in CI/CD pipelines) enforce process control but do not automatically detect or correct drift in the deployed infrastructure. Option C is wrong because tagging resources is a metadata labeling practice that aids in resource identification and cost allocation, not a mechanism for drift detection or correction. Option D is wrong because using modules promotes code reuse and consistency but does not inherently perform state comparison or auto-remediation against drift.

100
MCQeasy

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?

A.The `terraform apply` command
B.The `terraform validate` command
C.The `terraform plan` command
D.The `terraform state` command
AnswerC

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.

Why this answer

The `terraform plan` command creates an execution plan that shows what actions Terraform will take to achieve the desired state defined in the configuration. It compares the current state with the configuration and outputs a diff-like summary of resources to be created, modified, or destroyed, allowing the developer to review changes before applying them with `terraform apply`.

Exam trap

HashiCorp often tests the distinction between `terraform plan` as a read-only preview and `terraform apply` as the execution command, trapping candidates who confuse 'review' with 'apply' or think `terraform validate` performs a dry-run.

How to eliminate wrong answers

Option A is wrong because `terraform apply` executes the changes and does not provide a review-only preview; it applies the plan and prompts for confirmation unless auto-approved. Option B is wrong because `terraform validate` checks the syntax and internal consistency of the configuration files, not the planned changes against the real infrastructure state. Option D is wrong because `terraform state` is used to inspect or manipulate the Terraform state file (e.g., `terraform state list`, `terraform state show`), not to preview upcoming changes.

101
MCQeasy

A Terraform module defines an output 'instance_ips'. In the root module, how should this value be referenced?

A.var.instance_ips
B.local.instance_ips
C.resource.my_module.instance_ips
D.module.my_module.instance_ips
AnswerD

This is the correct and standard syntax for referencing an output value from a child module. When a module is declared and given a local name (e.g., `my_module`) in a `module` block, its defined output values become accessible using the `module.<MODULE_NAME>.<OUTPUT_NAME>` pattern. This allows the root module or other child modules to consume the computed results exposed by `my_module`, such as a list of instance IPs.

Why this answer

Outputs from a child module are accessed in the root module using the `module.<module_name>.<output_name>` syntax. The `module` keyword is a reserved reference that Terraform uses to expose all outputs defined within a module block, allowing the root configuration to consume values like `instance_ips` as `module.my_module.instance_ips`.

Exam trap

Terraform certification exams often test the distinction between `var.*`, `local.*`, `resource.*`, and `module.*` references, and the trap here is that candidates confuse module outputs with resource attributes, incorrectly using `resource.my_module.instance_ips` instead of the correct `module.my_module.instance_ips` syntax.

How to eliminate wrong answers

Option A is wrong because `var.instance_ips` would reference an input variable defined in the root module, not an output from a child module. Option B is wrong because `local.instance_ips` refers to a local value computed within the root module's configuration, not a module output. Option C is wrong because `resource.my_module.instance_ips` incorrectly uses the `resource` keyword; module outputs are not resources and cannot be referenced with a resource address syntax.

102
MCQhard

A company is adopting Terraform to manage its multi-cloud infrastructure on AWS and Azure. The infrastructure team has written several Terraform configurations stored in a Git repository. Each configuration is applied by different team members using their local machines. Recently, the team has been experiencing state file conflicts and inconsistencies, leading to infrastructure drift. The team currently stores the state file locally. They want to ensure that only one person can apply changes at a time and that the state file is always up-to-date. They also want to be able to collaborate effectively without overwriting each other's changes. Which approach should they implement?

A.Use Terraform Cloud to manage state and provide remote operations with locking.
B.Have only one team member run terraform apply from a dedicated machine.
C.Store the state file in a shared Git repository and use git pull/push to sync changes.
D.Use a remote backend such as Amazon S3 with DynamoDB for state locking.
AnswerA

Use Terraform Cloud to manage state and provide remote operations with locking is correct because Terraform Cloud offers managed remote state with built-in locking and remote operations, ensuring exclusive apply access, centralized state, and collaborative features.

Why this answer

Terraform Cloud provides a managed remote state backend with built-in state locking and remote operations. This ensures that only one person can apply changes at a time (via the locking mechanism), the state file is always up-to-date (stored centrally), and team members can collaborate without overwriting each other's changes. It directly addresses the team's need for exclusive apply access and consistent state.

Exam trap

HashiCorp often tests the distinction between remote state storage with locking (e.g., S3 with DynamoDB) and remote operations (e.g., Terraform Cloud). The trap is that candidates may see a 'remote backend' and assume it solves all collaboration issues, but Terraform Cloud provides additional benefits like remote execution and VCS integration that foster better collaboration. However, it's important to note that S3 with DynamoDB does provide state locking, which prevents concurrent applies.

How to eliminate wrong answers

Option B is wrong because it introduces a single point of failure and a bottleneck, and does not solve the underlying state locking issue—other team members could still run terraform plan or modify local state, leading to drift. Option C is wrong because storing the state file in a shared Git repository is not safe; Git does not provide state locking, and concurrent git pull/push operations can cause merge conflicts, corruption, or stale state. Option D is wrong because while Amazon S3 with DynamoDB provides state locking and remote storage, it does not offer remote operations (the apply still runs locally), so the team would still need to coordinate who runs apply, and the state file could become stale if multiple users run apply simultaneously without proper locking integration.

103
MCQeasy

A junior engineer cloned a Terraform repository from GitHub and ran terraform init inside the project directory. The command downloaded the required provider plugins successfully. Next, they ran terraform plan and received the following error: 'Error: No configuration files found in the current directory.' The engineer checked and confirmed that the main.tf file exists in the current directory. What is the most likely cause of this error?

A.The file is named main.tf.txt instead of main.tf
B.The terraform init command was not run with -upgrade flag
C.The main.tf file contains syntax errors
D.The terraform plan command requires the -out flag
AnswerA

Terraform's configuration loader specifically scans for files ending with the `.tf` extension within the working directory and its subdirectories. Files named with other extensions, such as `.tf.txt`, are completely ignored during the parsing phase, even if they contain valid HCL syntax. Consequently, if the primary configuration is misnamed, Terraform will report that no configuration files were found, as it simply doesn't recognize the file as part of its operational scope. This prevents accidental inclusion of non-Terraform files.

Why this answer

Terraform requires configuration files to have the `.tf` extension to be recognized. If the file is named `main.tf.txt` (e.g., due to Windows hiding known file extensions or accidental renaming), Terraform will not parse it as a configuration file, resulting in the 'No configuration files found' error even though the file exists in the directory. The `terraform init` command succeeded because it only downloads providers and modules, not requiring `.tf` files to be present.

Exam trap

HashiCorp often tests the subtle distinction between file existence and file recognition by Terraform, exploiting the common assumption that any file in the directory will be read, when in fact only files with the exact `.tf` extension are parsed.

How to eliminate wrong answers

Option B is wrong because the `-upgrade` flag is used to upgrade provider plugins to the latest version within the version constraint, not to make configuration files discoverable. Option C is wrong because syntax errors in `main.tf` would cause a different error during `terraform plan` (e.g., 'Error: Unsupported argument' or 'Error: Invalid expression'), not a 'No configuration files found' error. Option D is wrong because the `-out` flag is optional and only used to save the plan to a file; `terraform plan` runs successfully without it as long as configuration files are present.

104
Multi-Selecteasy

Which two commands are part of the standard Terraform workflow for provisioning infrastructure?

Select 2 answers
A.terraform init
B.terraform fmt
C.terraform apply
D.terraform import
E.terraform taint
AnswersA, C

The `terraform init` command is an indispensable first step in the standard Terraform workflow, executed whenever a new or existing configuration is started or updated. It performs crucial setup tasks, including downloading and installing the necessary provider plugins, initializing the configured backend for state management, and preparing any modules referenced in the configuration. Without successfully running `init`, Terraform cannot properly interact with the configuration files or the remote infrastructure providers.

Why this answer

`terraform init` is correct because it initializes a working directory containing Terraform configuration files, downloading the required providers and modules. `terraform apply` is correct because it executes the actions proposed in a Terraform plan to provision or change infrastructure resources. These two commands form the core of the standard workflow: initialize, plan, and apply.

Exam trap

HashiCorp often tests the distinction between provisioning commands and lifecycle or maintenance commands, so candidates may incorrectly select `terraform taint` or `terraform import` because they associate them with changing infrastructure, even though they do not directly provision new resources.

105
MCQmedium

A company wants to use Terraform to create Azure resources. They have written a configuration file but when they run `terraform init`, they get a warning about an 'incomplete lock file'. What should they do first?

A.Change the provider version in the configuration
B.Run `terraform apply` immediately
C.Run `terraform plan` to update the lock file
D.Delete the `.terraform.lock.hcl` and re-run `terraform init`
E.Run `terraform validate` to fix the warning
AnswerD

The `.terraform.lock.hcl` file serves to pin the exact versions and cryptographic checksums of providers used in a configuration, ensuring consistent and reproducible deployments. If this file becomes corrupted, outdated, or inconsistent with the actual provider requirements, deleting it forces `terraform init` to perform a fresh resolution of all provider dependencies. Subsequently re-running `terraform init` will then download the appropriate providers and generate a new, accurate `.terraform.lock.hcl` file based on the current configuration's `required_providers` block.

Why this answer

The warning about an 'incomplete lock file' indicates that the `.terraform.lock.hcl` file is corrupted, incomplete, or from an incompatible provider version. The correct first step is to delete the existing lock file and re-run `terraform init`, which will regenerate a fresh lock file based on the current configuration and provider requirements. This ensures dependency integrity before any planning or applying.

Exam trap

A common pitfall in Terraform is assuming that `terraform plan` or `terraform validate` can repair lock file issues, when in fact only `terraform init` (or manual deletion of `.terraform.lock.hcl`) will resolve dependency tracking problems.

How to eliminate wrong answers

Option A is wrong because changing the provider version in the configuration does not address a corrupted or incomplete lock file; it would only change which provider is referenced, not fix the lock file itself. Option B is wrong because running `terraform apply` without a valid lock file could lead to unexpected provider versions or dependency resolution failures, and Terraform will refuse to proceed with an incomplete lock file. Option C is wrong because `terraform plan` does not update the lock file; it reads the existing lock file and will fail or warn if the lock file is incomplete.

Option E is wrong because `terraform validate` checks configuration syntax and internal consistency, not the integrity of the dependency lock file.

106
Multi-Selecteasy

Which TWO statements best describe Terraform's purpose? (Choose two.)

Select 2 answers
A.It is a configuration management tool.
B.It is designed for single-cloud environments.
C.It uses a declarative language.
D.It requires a master node to manage agents.
E.It is an infrastructure provisioning tool.
AnswersC, E

Terraform utilizes HashiCorp Configuration Language (HCL), a declarative language, to define the desired end state of infrastructure. Users specify *what* resources should exist and their attributes, rather than *how* to achieve that state through a series of procedural steps. Terraform then intelligently determines the necessary actions to transition the current infrastructure to the declared desired state, ensuring idempotence and consistency across deployments.

Why this answer

Terraform uses a declarative language (HCL) where you define the desired end state of your infrastructure, and Terraform determines the necessary steps to achieve that state. This is a core differentiator from imperative tools, as it focuses on 'what' rather than 'how'.

Exam trap

Candidates often confuse infrastructure provisioning (Terraform) with configuration management (Puppet, Ansible, Chef). Terraform provisions the underlying infrastructure, while configuration management tools configure the software and settings on that infrastructure. This distinction is critical.

107
Multi-Selectmedium

Which TWO actions are part of the core Terraform workflow? (Select TWO.)

Select 2 answers
A.Create infrastructure manually via cloud console
B.Write Terraform configuration files
C.Review the execution plan
D.Commit changes to version control
E.Run unit tests on the configuration
AnswersB, C

Writing Terraform configuration files, typically in HashiCorp Configuration Language (HCL), is the initial and foundational step in the core workflow. These files declaratively define the desired state of infrastructure resources, specifying providers, resources, data sources, variables, and outputs. This configuration serves as the single source of truth for Terraform to understand what infrastructure to manage.

Why this answer

The core workflow consists of: Write (author config), Plan (review changes), Apply (execute). Options that match are 'Write configuration' and 'Review execution plan'.

108
MCQmedium

A team is using a private module registry from a third-party vendor. When running terraform init, they receive an error: 'Error downloading module: could not download module... server responded with 401 Unauthorized'. What is the most likely cause?

A.The module source URL is incorrect.
B.The registry credentials are missing or invalid.
C.The Terraform version is too old for the module.
D.The network firewall is blocking outbound connections.
AnswerB

An HTTP 401 Unauthorized response explicitly indicates that the request lacks valid authentication credentials for the target resource. When interacting with a private module registry, Terraform requires specific credentials, often an API token or username/password, configured via a `credentials.tfrc.json` file or environment variables. If these credentials are either missing from Terraform's configuration or are invalid/expired, the registry server will correctly deny access with a 401 status.

Why this answer

The 401 Unauthorized error indicates that the request to the private module registry was received but authentication failed. Private registries require valid credentials (such as an API token or username/password) to be configured, typically via a `.terraformrc` or `credentials` block in the CLI configuration. Without these, Terraform cannot authenticate and the download is rejected.

Exam trap

HashiCorp often tests the distinction between authentication errors (401) and authorization errors (403) or network connectivity errors, so candidates may incorrectly attribute a 401 to a wrong URL or firewall issue instead of missing or invalid credentials.

How to eliminate wrong answers

Option A is wrong because an incorrect module source URL would typically result in a 'not found' (404) or 'invalid source' error, not a 401 authentication error. Option C is wrong because an outdated Terraform version would cause compatibility warnings or syntax errors, not an HTTP 401 response from the registry. Option D is wrong because a network firewall blocking outbound connections would produce a timeout or connection refused error, not an HTTP 401 status code.

109
MCQhard

A company uses Terraform Cloud and wants to ensure that only approved modules from the private registry are used in configurations. How can they enforce this?

A.Restrict module sources in VCS
B.Configure workspace variables to limit module paths
C.Use Sentinel policies to check module sources
D.Use run tasks to scan for module types
AnswerC

Sentinel policies provide a robust, native policy-as-code framework within Terraform Cloud, designed to inspect the Terraform plan and enforce organizational governance rules before infrastructure changes are applied. By writing a Sentinel policy, an organization can directly access the `tfplan` data, specifically evaluating attributes like `tfplan.module_calls[*].source` to identify and validate all module sources being used. If an unauthorized module source is detected, the policy can be configured to soft-fail (warn) or hard-fail (block) the Terraform run, ensuring only approved modules are deployed.

Why this answer

Sentinel is HashiCorp's policy-as-code framework that can enforce governance rules on Terraform Cloud runs. By writing a Sentinel policy that inspects the `module` block's `source` attribute, you can restrict configurations to only use modules from the approved private registry, rejecting any run that references external or unapproved sources.

Exam trap

HashiCorp often tests the distinction between run tasks (external integrations) and Sentinel (native policy engine), leading candidates to incorrectly choose run tasks for in-plan policy enforcement when Sentinel is the correct answer.

How to eliminate wrong answers

Option A is wrong because restricting module sources in VCS (e.g., via branch protection or file patterns) does not prevent a user from committing a configuration that references an unapproved module source; VCS controls operate at the code storage layer, not at the Terraform plan/apply execution layer. Option B is wrong because workspace variables cannot limit module paths; variables are used to parameterize configurations, not to enforce source restrictions on module declarations. Option D is wrong because run tasks are external integrations that can perform arbitrary checks or actions (e.g., security scans), but they do not have native access to parse and enforce module source constraints within the Terraform plan; Sentinel policies are the designated mechanism for policy enforcement in Terraform Cloud.

110
MCQhard

What is the correct way to resolve this provider version conflict?

A.Ignore the module's required_providers and force install the root version.
B.Remove the required_providers block from the root module.
C.Change the root module's required version to ~> 2.70.
D.Manually edit the .terraform/modules/consul/main.tf to change the version.
AnswerC

This is the correct approach because it directly addresses the version conflict by aligning the constraints. If the module requires `~> 2.70` (meaning any patch version within 2.70, e.g., `2.70.0` up to `2.70.x` but less than `2.71.0`), then setting the root module's requirement to `~> 2.70` ensures both the root and the nested module can successfully use the same provider version. This modification makes both `required_providers` blocks compatible, allowing Terraform's dependency resolver to find a mutually acceptable version.

Why this answer

The root module's required_providers version constraint must be compatible with the version constraints declared in any child modules. The error indicates the root module requires a provider version that conflicts with the consul module's constraint (e.g., ~> 2.70). Changing the root constraint to ~> 2.70 aligns it with the child module, satisfying Terraform's version resolution logic during `terraform init`.

Exam trap

HashiCorp often tests the misconception that you can override or ignore a child module's provider version constraint, when in fact Terraform enforces compatibility across all modules and the correct fix is to align the root module's constraint with the child module's requirement.

How to eliminate wrong answers

Option A is wrong because ignoring a module's required_providers and forcing installation bypasses Terraform's dependency resolution, leading to unpredictable behavior or runtime errors. Option B is wrong because removing the required_providers block from the root module does not resolve the conflict; it removes the root's constraint but the child module's constraint still applies, and Terraform will still enforce the child's version requirement. Option D is wrong because manually editing the .terraform/modules/consul/main.tf is not a supported workflow; the .terraform directory is managed by Terraform and changes will be overwritten on the next `terraform init`, and it violates the principle of immutable module sources.

111
MCQeasy

A developer wants to create multiple instances of a module that provisions a single EC2 instance. They want to create 3 EC2 instances. Which approach is most efficient and concise?

A.Set the source argument to a list of three URLs.
B.Use the 'count' meta-argument in the module block.
C.Use the 'for_each' meta-argument with a list of numbers.
D.Copy the module block three times with different names.
AnswerB

The `count` meta-argument is specifically designed to create multiple identical instances of a resource or module block. By setting `count` to an integer value, such as `3`, Terraform will instantiate the module three times, creating separate, distinct instances. This method is highly efficient and concise for provisioning a fixed number of similar components, as it avoids repetition and leverages Terraform's built-in lifecycle management for each instance.

Why this answer

The `count` meta-argument in a module block allows you to create multiple instances of the entire module (including its EC2 instance) by specifying a number. This is the most efficient and concise approach when you need a fixed number of identical module instances, as it avoids code duplication and leverages Terraform's built-in iteration.

Exam trap

In the Terraform Associate exam, candidates are often tested on understanding that `count` is the most concise and efficient way to create a fixed number of identical module instances, while `for_each` is better for creating instances from a set of distinct keys or when you need to manage each instance independently with a unique identifier.

How to eliminate wrong answers

Option A is wrong because the `source` argument in a module block must be a single string pointing to the module's source location (e.g., a local path, registry, or Git URL); it cannot accept a list of URLs. Option C is wrong because while `for_each` can create multiple module instances, using it with a list of numbers is less concise than `count` when the goal is simply to create a specific number of identical instances; `for_each` is better suited for creating instances from a set of distinct keys or complex objects. Option D is wrong because copying the module block three times violates the DRY (Don't Repeat Yourself) principle, introduces maintenance overhead, and is neither efficient nor concise compared to using `count`.

112
MCQmedium

A team is reviewing the Terraform configuration shown in the exhibit. Which statement best describes the relationship between the two resources?

A.The S3 bucket cannot be created until the EC2 instance is running.
B.The S3 bucket depends on the EC2 instance because it is defined after it.
C.The two resources have no dependencies and can be created in any order.
D.The EC2 instance depends on the S3 bucket because the instance uses the bucket name.
AnswerC

Terraform establishes dependencies either implicitly, when one resource's attribute is referenced by another, or explicitly, using the `depends_on` meta-argument. Given the absence of any such references or explicit declarations linking the EC2 instance and S3 bucket resources, Terraform correctly identifies them as entirely independent. This independence allows the Terraform graph to execute their creation in parallel or in any sequential order, as no ordering constraints exist.

Why this answer

Terraform resources are independent by default unless an explicit or implicit dependency is declared. In the exhibit, the S3 bucket and EC2 instance are defined without any `depends_on` argument or attribute reference (e.g., `aws_s3_bucket.example.arn` used in the EC2 instance configuration). Therefore, Terraform can create them in parallel or any order, as there is no directed acyclic graph (DAG) edge enforcing a creation sequence.

Exam trap

HashiCorp often tests the misconception that Terraform creates resources in the order they appear in the configuration file, but the actual dependency mechanism is based on explicit references and `depends_on`, not lexical order.

How to eliminate wrong answers

Option A is wrong because there is no `depends_on` or attribute reference from the S3 bucket to the EC2 instance, so Terraform does not require the EC2 instance to be running before creating the bucket. Option B is wrong because Terraform does not use definition order to determine dependencies; it builds a dependency graph based on explicit references and `depends_on` blocks, not the order in the configuration file. Option D is wrong because the EC2 instance does not reference the S3 bucket's name or any attribute (e.g., `aws_s3_bucket.example.bucket`), so no implicit dependency exists; the instance can be created independently of the bucket.

113
MCQmedium

A team has been managing their AWS infrastructure using a collection of Bash scripts that create resources in a specific order. They frequently encounter issues where resources are created out of order or not properly cleaned up. They want to adopt a more reliable approach that ensures consistent provisioning and teardown. Which action best aligns with Terraform's purpose?

A.Continue using the Bash scripts but add more error handling.
B.Use Terraform but only store state locally on the lead engineer's machine.
C.Convert the scripts into Terraform configuration files and use remote state.
D.Rewrite the scripts as Ansible playbooks for provisioning.
AnswerC

Converting to Terraform configuration files leverages a declarative approach, allowing the team to define the desired end state of their AWS infrastructure, rather than the steps to get there. Terraform automatically builds a dependency graph, ensuring resources are provisioned in the correct order and handling updates efficiently. Utilizing remote state, such as in an S3 bucket with DynamoDB locking, enables secure team collaboration, prevents concurrent modifications, and maintains a consistent, shared record of the infrastructure's actual state.

Why this answer

Terraform's purpose is to manage infrastructure declaratively, handling dependencies and state. Converting to Terraform configs and using the plan/apply workflow ensures consistent provisioning. Continuing with scripts or using Ansible for provisioning are less effective.

114
MCQhard

Which Terraform feature allows managing multiple separate sets of infrastructure from the same configuration?

A.Workspaces
B.Count
C.Providers
D.For_each
AnswerA

Workspaces in Terraform allow for managing multiple distinct instances of the same configuration. Each workspace maintains its own independent state file, enabling the deployment of identical infrastructure setups (e.g., `dev`, `staging`, `prod`) without modifying the core HCL code. This isolation prevents resource conflicts and ensures environment-specific configurations are applied correctly through variable overrides, making them ideal for environment separation.

Why this answer

Workspaces allow you to manage multiple distinct sets of infrastructure resources from the same Terraform configuration by maintaining separate state files. Each workspace isolates its own state data, enabling you to deploy, modify, or destroy infrastructure for different environments (e.g., dev, staging, prod) without interfering with each other. This is the native Terraform feature designed specifically for managing multiple separate instances of infrastructure from a single configuration.

Exam trap

A common pitfall is confusing meta-arguments like 'count' and 'for_each', which create multiple resource instances within a single state, with workspaces, which provide full state isolation for managing entirely separate environments (e.g., dev, staging, prod) from the same configuration.

How to eliminate wrong answers

Option B (count) is wrong because it is a meta-argument used to create multiple copies of a resource within a single configuration, not to manage separate sets of infrastructure; it operates within a single workspace and state file. Option C (Providers) is wrong because providers are plugins that interact with specific cloud APIs (e.g., AWS, Azure) and do not provide any mechanism for isolating or managing separate infrastructure instances; they define the resource types available, not workspace separation. Option D (for_each) is wrong because it is a meta-argument that creates multiple resource instances from a map or set of strings, similar to count, and does not offer state isolation or separate management of infrastructure sets; it works within a single workspace.

115
MCQhard

A user accidentally ran `terraform state rm` on a critical resource, removing it from state but not destroying the actual infrastructure. Later, they need to re-import the resource. Which sequence of commands correctly accomplishes this?

A.`terraform state push` with the original state file
B.`terraform plan` and then `terraform apply`
C.`terraform refresh` and then `terraform plan`
D.`terraform import` using the resource address and ID of the resource
AnswerD

terraform import is the correct and intended method for bringing existing infrastructure under Terraform management. When a resource is accidentally removed from the state file via terraform state rm, the remote resource still exists. By specifying the resource's address (e.g., aws_instance.web) from the configuration and its actual cloud provider ID (e.g., i-0abcdef1234567890), terraform import reads the resource's current configuration from the provider and adds it back into the Terraform state file, linking it to the specified configuration block without modifying the live resource.

Why this answer

After removal, the resource is unmanaged. `terraform import` re-associates it with state. Option D is the correct sequence.

116
MCQeasy

A developer wants to conditionally create a resource based on a variable that is a boolean. Which syntax should they use?

A.Use 'if var.create' inside the resource block
B.Use 'for_each = var.create ? [1] : []'
C.Use 'count = var.create'
D.Use 'count = var.create ? 1 : 0'
AnswerD

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.

Why this answer

In Terraform, the `count` meta-argument accepts a number, and the ternary expression `var.create ? 1 : 0` evaluates to 1 (true) to create one instance of the resource or 0 (false) to create none. This is the standard pattern for conditionally creating a single resource based on a boolean variable.

Exam trap

HashiCorp often tests the distinction between `count` and `for_each` for conditional creation, and the trap here is that candidates mistakenly think `count` can accept a boolean directly or that `for_each` with a single-element list is the correct approach for a simple boolean condition.

How to eliminate wrong answers

Option A is wrong because Terraform does not support an `if` keyword inside a resource block; conditional logic must be implemented using `count` or `for_each`. Option B is wrong because `for_each = var.create ? [1] : []` would work for conditionally creating resources but is unnecessarily complex for a single resource and is not the idiomatic syntax for a boolean variable; `count` is preferred for simple true/false conditions. Option C is wrong because `count = var.create` is invalid since `count` requires a number, not a boolean; Terraform will throw a type error unless the variable is explicitly converted to a number.

117
MCQhard

Refer to the exhibit. An engineer runs 'terraform plan' and receives an error: 'Error refreshing state: state data in S3 does not have the expected content.' The state file exists and is not corrupted. What is the most likely cause?

A.The state file is locked by another process.
B.The state file was written by a different backend configuration (e.g., different key or workspace).
C.The DynamoDB table does not exist.
D.The S3 bucket is in a different region.
AnswerB

Terraform state files include a "serial" attribute that increments with each successful `apply` operation, acting as a version number for the infrastructure state. When a state file is accessed or modified through a different backend configuration, such as a distinct S3 key, a separate workspace, or even a different backend type, Terraform might encounter a `serial` number that does not align with its expected sequence for the current working directory. This discrepancy triggers a "state serial mismatch" error, indicating that the current operation is attempting to interact with a state file that has an unexpected or inconsistent version history.

Why this answer

The error 'state data in S3 does not have the expected content' indicates a mismatch between the state file's content and what Terraform expects based on the current backend configuration. This typically occurs when the state file was written using a different backend key, workspace, or bucket path, causing Terraform to read a state that does not match the expected serial or lineage. The state file itself is not corrupted, but the backend configuration (e.g., different `key` or `workspace_key_prefix`) points to a different state object in S3.

Exam trap

Terraform often tests the distinction between state lock errors and state content mismatch errors, trapping candidates who confuse a missing DynamoDB table or a locked state with a backend configuration mismatch.

How to eliminate wrong answers

Option A is wrong because a locked state file would produce a different error, such as 'Error acquiring the state lock' or 'state file is locked', not a content mismatch error. Option C is wrong because a missing DynamoDB table would cause a lock-related error (e.g., 'failed to query lock table') or a permission error, not a state content mismatch. Option D is wrong because an S3 bucket in a different region would result in a 'bucket does not exist' or 'region mismatch' error, not a content mismatch, as Terraform uses the configured region to access the bucket.

118
MCQmedium

A company wants to ensure that Terraform configurations are consistent across teams. What practice should they adopt?

A.Write all code in a single file
B.Use modules from a registry
C.Use provisioners extensively
D.Avoid using variables
AnswerB

Using modules from a registry is the most effective method to ensure consistent Terraform configurations across an organization. Modules encapsulate a set of related infrastructure resources, allowing them to be defined once with standardized inputs and outputs, then reused across multiple projects or environments. This promotes consistency by enforcing predefined patterns, reducing configuration drift, and enabling centralized management and versioning of infrastructure components, directly addressing the need for reliable and repeatable deployments.

Why this answer

Using modules from a registry (Option B) is the correct practice because modules encapsulate reusable, version-controlled infrastructure configurations that enforce consistency across teams. By referencing a shared registry, teams can standardize on approved module versions, reducing drift and ensuring compliance with organizational policies. This approach aligns with Terraform's best practices for code reuse and collaboration.

Exam trap

A common mistake is assuming a single file ensures consistency, but modules from a registry provide version-controlled, shareable configurations that standardize infrastructure across teams.

How to eliminate wrong answers

Option A is wrong because writing all code in a single file violates the principle of separation of concerns, leading to monolithic, unmaintainable configurations that are difficult to version and review across teams. Option C is wrong because provisioners should be used sparingly as a last resort; extensive use introduces procedural logic that undermines Terraform's declarative model, making configurations brittle and non-idempotent. Option D is wrong because avoiding variables eliminates the ability to parameterize configurations, forcing hardcoded values that prevent reuse and consistency across different environments or teams.

119
MCQhard

A Terraform configuration includes a variable for a database password marked as sensitive. When a user runs 'terraform apply', the password appears as (sensitive) in the plan output. However, they want to pass this password to a provisioner as an environment variable. What should they do?

A.Use the variable directly; sensitive only affects CLI output.
B.Use the nonsensitive() function around the variable when assigning.
C.Store the password in a local value with sensitive = false.
D.Remove the sensitive flag from the variable.
AnswerB

The `nonsensitive()` function explicitly marks a sensitive value as non-sensitive for a specific expression or assignment, allowing it to be used in contexts where a sensitive value would otherwise be redacted or cause an error. Crucially, while `nonsensitive()` permits its use in a particular operation or argument, the original variable's value *remains marked sensitive within the Terraform state file*. This ensures the value is only exposed when explicitly intended for processing, maintaining its sensitive status for storage and subsequent operations.

Why this answer

The `nonsensitive()` function explicitly marks a sensitive value as safe to use in contexts where Terraform would otherwise block its usage, such as passing it to a provisioner's environment variable. Even though the variable is marked as sensitive, Terraform still prevents it from being used in certain contexts unless you explicitly override that protection with `nonsensitive()`. This ensures the password is available to the provisioner while still hiding it from CLI output.

Exam trap

The trap here is that candidates assume the sensitive flag only affects CLI output, leading them to choose Option A, but Terraform enforces sensitivity in all contexts unless `nonsensitive()` is used.

How to eliminate wrong answers

Option A is wrong because the sensitive flag does more than affect CLI output; it also prevents the value from being used in places like provisioner environment variables, where Terraform would raise an error. Option C is wrong because local values cannot override the sensitive flag; marking a local value with `sensitive = false` does not bypass the original variable's sensitive constraint. Option D is wrong because removing the sensitive flag would expose the password in all outputs and logs, which defeats the purpose of keeping it secure.

120
MCQeasy

After adding a new module sourced from a Git repository with a specific tag, terraform init reports that the module is being downloaded. What is the best practice to ensure the team uses the same version of this module consistently?

A.Use a version constraint in the module block, e.g., version = 1.0.0.
B.Specify the source as the branch name 'main'.
C.Use the 'latest' tag in the source URL.
D.Use a Git tag, like '?ref=v1.0.0', to pin the version.
AnswerD

Using a specific Git tag, such as `?ref=v1.0.0`, is the recommended and most robust method for pinning a module's version when sourcing directly from a Git repository. Git tags are immutable pointers to a specific commit in the repository's history, ensuring that the exact same module code is fetched every time Terraform runs. This immutability is crucial for achieving consistent and reproducible infrastructure deployments across all environments and team members, preventing unexpected changes and simplifying debugging.

Why this answer

Using a Git tag (e.g., `?ref=v1.0.0`) in the module source URL pins the module to a specific, immutable commit. This ensures that every team member downloads the exact same version of the module, regardless of future changes to the default branch. Terraform resolves the tag to a commit hash and caches it, providing deterministic and reproducible infrastructure.

Exam trap

In Terraform, candidates often confuse version constraints (for registry modules) with source URL parameters (for Git, Mercurial, or other VCS sources), leading them to incorrectly apply registry-style versioning to Git-sourced modules.

How to eliminate wrong answers

Option A is wrong because Terraform modules sourced from Git repositories do not support a `version` argument in the module block; version constraints are only valid for modules from the Terraform Registry. Option B is wrong because specifying a branch name (e.g., 'main') points to a moving target; the branch can receive new commits, causing different team members to get different module code over time. Option C is wrong because there is no 'latest' tag in Git; using 'latest' as a tag would require the repository to explicitly create and maintain such a tag, and it would still be mutable if updated.

121
MCQmedium

You are managing a Terraform configuration that deploys resources across multiple AWS accounts using provider aliases. The configuration uses a single backend (S3) to store the state file. Recently, you discovered that the state file has become very large (over 100 MB) and is causing slow operations and timeouts. The team wants to improve performance without losing the ability to manage all resources with a single `terraform apply`. You need to propose a solution. Which approach should you take?

A.Use state encryption to compress the state file
B.Switch the backend from S3 to Terraform Cloud to improve performance
C.Use Terraform workspaces to separate environments into different state files
D.Split the configuration into separate directories for each environment
AnswerB

Switching to Terraform Cloud provides a managed backend that can handle large state files efficiently with built-in state locking, remote execution, and caching. This allows you to continue using a single `terraform apply` to manage all resources.

Why this answer

Switching to Terraform Cloud can improve performance with large state files due to its optimized backend, remote state management, and built-in caching. It allows you to continue managing all resources with a single `terraform apply` command, as Terraform Cloud handles state operations efficiently. This approach does not require splitting the state file or using multiple workspaces, thus preserving the ability to apply all changes in one operation.

Exam trap

A common misconception is that Terraform workspaces allow a single `terraform apply` to manage all resources. In reality, each workspace requires its own apply, so workspaces do not satisfy the requirement of a single apply command.

How to eliminate wrong answers

Option A is wrong because state encryption (e.g., using AWS KMS) does not compress the state file; it only encrypts it at rest, so the file size remains unchanged and performance issues persist. Option B is wrong because switching to Terraform Cloud does not inherently reduce state file size; it may improve backend performance but the underlying large state file still causes slow operations. Option D is wrong because splitting the configuration into separate directories would require running `terraform apply` separately for each directory, breaking the requirement to manage all resources with a single `terraform apply`.

122
Drag & Dropmedium

Drag and drop the steps to handle sensitive data in Terraform outputs in the correct order.

Drag steps to the numbered slots on the right, or tap a step then tap a slot.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

Sensitive outputs are redacted in CLI; -json reveals raw value for secure handling.

123
Multi-Selecthard

Which THREE statements about module configuration are correct?

Select 3 answers
A.Module sources can be local paths or remote URLs.
B.Version constraints can be specified for any module source.
C.The outputs of a module are available after apply only.
D.A module block can contain multiple resources and child modules.
E.Module inputs can be optional if the module uses a default.
AnswersA, D, E

Terraform supports various source types including local, registry, Git, HTTP, etc.

Why this answer

Terraform module sources can be either local file paths (e.g., `./modules/network`) or remote URLs (e.g., `git::https://example.com/repo.git`, `registry.terraform.io/hashicorp/consul/aws`). The `source` argument supports multiple protocols including local, Git, HTTP, and the Terraform Registry, making it flexible for version control and distribution.

Exam trap

A common misconception is that version constraints can be applied to any module source, but they only work with registry modules that support semantic versioning.

124
Multi-Selecthard

Which THREE of the following are valid Terraform providers?

Select 4 answers
A.hashicorp/azurerm
B.kreuzwerker/docker
C.hashicorp/kubernetes
D.hashicorp/aws
E.hashicorp/cloudwatch
AnswersA, B, C, D

Correct. hashicorp/azurerm is the official Azure provider from HashiCorp.

Why this answer

All four options A, B, C, D are valid Terraform providers. Options A (hashicorp/azurerm), C (hashicorp/kubernetes), and D (hashicorp/aws) are official HashiCorp providers. Option B (kreuzwerker/docker) is a well-known community provider for Docker.

The question asks for 'valid' providers, which includes both official and community providers. Option E (hashicorp/cloudwatch) is not a valid standalone provider because CloudWatch is a service within AWS and is managed by the hashicorp/aws provider.

Exam trap

Candidates often assume that only official HashiCorp providers are valid, but community providers like kreuzwerker/docker are also valid unless the question specifies 'official'. Additionally, CloudWatch is not a standalone provider; it's part of the AWS provider.

125
MCQmedium

A team manages infrastructure with Terraform and uses a remote backend in an S3 bucket. After a recent state migration, a developer runs 'terraform plan' and gets an error: 'Error: Error loading state: NoSuchKey: The specified key does not exist.' The developer confirms that the state file exists in the bucket. What is the most likely cause?

A.The backend configuration in the Terraform code does not match the actual state file path.
B.Terraform state locking is enabled but the lock was not released.
C.The S3 bucket policy does not allow reading the state file.
D.S3 bucket versioning is enabled, and the state file is a non-current version.
AnswerA

This is the correct answer. A "NoSuchKey" error from an S3 backend explicitly indicates that Terraform attempted to retrieve a state file at a specific S3 key (path) but found no object there. This frequently occurs when the 'key' parameter in the 'backend "s3"' configuration, or the active Terraform workspace, does not precisely align with the actual location of the state file in the S3 bucket, causing Terraform to look for a non-existent object.

Why this answer

The error 'NoSuchKey: The specified key does not exist' indicates that Terraform is looking for the state file at a specific key (path) in the S3 bucket, but that key does not exist. Since the developer confirms the state file exists in the bucket, the most likely cause is a mismatch between the backend configuration in the Terraform code (e.g., the `key` argument) and the actual path where the state file is stored. This often happens after a state migration if the backend configuration was not updated to reflect the new location.

Exam trap

HashiCorp often tests the distinction between access denied errors (403) and missing key errors (404), so the trap here is that candidates might confuse a permission issue with a path mismatch, especially when the state file is confirmed to exist in the bucket.

How to eliminate wrong answers

Option B is wrong because state locking uses a separate lock file (e.g., a DynamoDB table entry) and does not affect the existence or retrieval of the state file itself; a released lock would not cause a 'NoSuchKey' error. Option C is wrong because if the S3 bucket policy denied read access, the error would typically be an access denied (403) error, not a 'NoSuchKey' (404) error. Option D is wrong because versioning does not change the current key; Terraform by default retrieves the latest version of the state file, and a non-current version would still be accessible via the same key with a version ID, but the error indicates the key itself is missing.

126
Multi-Selecthard

Which THREE of the following are valid reasons to use 'terraform refresh'? (Choose three.)

Select 3 answers
A.To update the state file when resources were deleted outside of Terraform.
B.To detect drift between the state file and actual infrastructure.
C.To import existing infrastructure into Terraform management.
D.To update the state file after making manual changes to resources.
E.To update the Terraform configuration with current resource settings.
AnswersA, B, D

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.

Why this answer

The `terraform refresh` command updates the state file to match real-world infrastructure. Option A is correct because if resources were deleted outside Terraform, refresh removes them from state. Option B is correct because refresh detects drift by comparing state with actual infrastructure.

Option D is correct because manual changes to resources are recorded in state after refresh. Option C is incorrect because importing infrastructure requires `terraform import`, not refresh. Option E is incorrect because refresh updates the state file, not the Terraform configuration.

Exam trap

HashiCorp often tests the distinction between `terraform refresh` (state update only) and `terraform import` (adding new resources to state), as well as the misconception that `terraform refresh` modifies configuration files.

127
MCQhard

An organization is evaluating Terraform for managing interconnected resources that must be created in a specific order. Why is Terraform's dependency graph handling a key aspect of its purpose?

A.It reduces the amount of code needed
B.It allows all resources to be created in parallel for speed
C.It ensures resources are provisioned in the correct order based on dependencies
D.It enables modularity and code reuse
AnswerC

The dependency graph is fundamental to Terraform's operational integrity, as it precisely maps out the relationships between all declared resources. By analyzing these explicit (e.g., `depends_on`) and implicit (e.g., attribute references) dependencies, Terraform constructs an execution plan that guarantees resources are provisioned, updated, or destroyed in the correct, logical sequence. This prevents provisioning failures, ensures state consistency, and maintains the desired infrastructure configuration.

Why this answer

Terraform builds a dependency graph from the resource configurations, analyzing explicit references (e.g., `aws_instance.web.vpc_id`) and implicit dependencies. This graph ensures that resources are created, updated, or destroyed in the correct order, preventing provisioning failures that would occur if, for example, a subnet were created before its parent VPC. This deterministic ordering is fundamental to Terraform's ability to manage complex, interconnected infrastructure reliably.

Exam trap

A common trap is the misconception that Terraform creates all resources in parallel for speed. While Terraform does parallelize independent resources, it strictly serializes dependent ones based on the dependency graph, so full parallelism is never the goal—correct ordering is.

How to eliminate wrong answers

Option A is wrong because Terraform's dependency graph does not reduce the amount of code; it manages execution order, while code reduction is achieved through features like modules, variables, and count/for_each. Option B is wrong because Terraform does not allow all resources to be created in parallel; it uses the dependency graph to identify resources with no dependencies and creates those in parallel, but dependent resources must wait, so full parallelism is impossible and would cause errors. Option D is wrong because modularity and code reuse are enabled by Terraform's module system and input/output variables, not by the dependency graph, which is solely concerned with ordering and parallelism.

128
MCQeasy

A team is new to Terraform and wants to manage their cloud infrastructure. They have written configuration files but have not yet run any commands. What is the correct sequence of initial steps to deploy their infrastructure?

A.Run terraform init, then terraform plan, then terraform apply
B.Run terraform plan, then terraform apply, then terraform init
C.Run terraform validate, then terraform plan, then terraform apply
D.Run terraform apply, then terraform plan, then terraform init
AnswerA

This sequence represents the standard and required workflow for managing infrastructure with Terraform. The `terraform init` command is essential for initializing the working directory, downloading necessary provider plugins and modules, and setting up the backend. Following this, `terraform plan` generates an execution plan, detailing all proposed infrastructure changes without making any modifications. Finally, `terraform apply` executes this plan, provisioning or modifying the infrastructure to match the desired state defined in the configuration.

Why this answer

The correct sequence is `terraform init`, `terraform plan`, then `terraform apply`. `terraform init` must be run first to initialize the working directory, download required provider plugins (e.g., AWS, Azure), and set up the backend state storage. Without initialization, subsequent commands like `plan` and `apply` will fail because Terraform cannot locate providers or configure the state backend. After initialization, `terraform plan` creates an execution plan showing what resources will be created, modified, or destroyed, and `terraform apply` executes that plan to deploy the infrastructure.

Exam trap

A common mistake is thinking that `terraform validate` or `terraform plan` can be run before `terraform init`, but in reality, `init` is mandatory first because it downloads providers and sets up the backend, without which no other command can execute.

How to eliminate wrong answers

Option B is wrong because `terraform plan` and `terraform apply` require an initialized working directory; running `plan` before `init` will fail with an error about missing providers or backend configuration. Option C is wrong because `terraform validate` is optional and checks syntax/correctness but is not a required initial step; the mandatory first step is always `terraform init` to download providers and set up state. Option D is wrong because `terraform apply` cannot run before `terraform init` (no providers or state) and `terraform plan` must precede `apply` to review changes; running `apply` without `plan` is possible but dangerous and not the correct initial sequence.

129
Multi-Selectmedium

Which TWO statements about Infrastructure as Code (IaC) are correct?

Select 2 answers
A.IaC is only applicable to cloud-based infrastructure.
B.IaC eliminates configuration drift entirely.
C.IaC enables automated provisioning and management of infrastructure.
D.IaC allows the same configuration to be applied multiple times with the same result.
E.IaC tools require manual execution of scripts.
AnswersC, D

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.

Why this answer

Infrastructure as Code (IaC) automates the provisioning and management of infrastructure through machine-readable definition files, enabling consistent and repeatable deployments without manual intervention. Tools like Terraform use a declarative approach to define resources, and the IaC engine handles creation, modification, and deletion based on the desired state. Option D is correct because IaC configurations are idempotent—applying the same configuration multiple times yields the same result.

This is achieved through state management and drift detection, ensuring that infrastructure remains in the specified state regardless of how many times the configuration is applied.

Exam trap

HashiCorp often tests the misconception that IaC eliminates drift entirely, when in reality it only detects and corrects drift through reconciliation, and candidates may also incorrectly assume IaC is cloud-only, missing its applicability to on-premises and hybrid environments.

130
MCQeasy

A user runs 'terraform plan' and the output includes a change that adds a new resource. However, the user expected the change to modify an existing resource. What is the most likely cause?

A.The provider version was updated.
B.A required attribute was added to the resource block.
C.The state file was manually deleted.
D.The resource name or type was changed in the configuration.
AnswerD

Terraform identifies resources by their unique address, which is composed of their type and local name (e.g., `aws_instance.web`). If either the resource type (e.g., changing `aws_instance` to `aws_ami`) or the local name (e.g., changing `web` to `app`) is altered in the configuration, Terraform considers this a completely different resource from what is recorded in the state file. It will then plan to destroy the old resource (if it exists in state) and create a brand new one with the updated address, resulting in a `(- destroy, + create)` action for that specific resource.

Why this answer

When a resource's name or type is changed in the configuration, Terraform interprets it as a request to destroy the old resource and create a new one, because Terraform maps each resource block to a state entry using its resource type and name (e.g., `aws_instance.web`). The plan output will show a `+` (create) for the new resource and a `-` (destroy) for the old one, rather than a `~` (update in-place). This matches the user's observation of a new resource being added instead of the expected modification.

Exam trap

HashiCorp often tests the misconception that Terraform identifies resources by their configuration block content (e.g., tags or names) rather than by the resource type and name in the block header, leading candidates to incorrectly attribute the behavior to provider updates or attribute changes.

How to eliminate wrong answers

Option A is wrong because updating a provider version may change default values or introduce new attributes, but it does not cause Terraform to treat an existing resource as a new resource; it would typically trigger in-place updates or require re-creation only if schema changes are incompatible. Option B is wrong because adding a required attribute to a resource block that already exists in state would cause a plan error (missing required argument) or force re-creation if the attribute cannot be updated in-place, but it would not silently add a new resource while leaving the old one unchanged. Option C is wrong because manually deleting the state file would cause Terraform to see no existing resources at all, so it would plan to create all resources from scratch, not just one new resource; the user would see many `+` entries, not a single addition.

131
Multi-Selectmedium

Which TWO statements are correct when refactoring a monolithic Terraform configuration into modules?

Select 2 answers
A.All modules must reside in a separate directory outside the root module.
B.A module should contain only one resource to keep it simple.
C.Module outputs are necessary to expose values to the root module.
D.Variables are optional in modules if hardcoded values are acceptable.
E.Modules help to organize and reuse infrastructure code.
AnswersC, E

Module outputs serve as the explicit interface for a child module to return specific values, such as resource IDs, IP addresses, or connection strings, back to its calling module or the root configuration. Without defining these outputs, any values computed or created within the module remain encapsulated and inaccessible to parent modules, preventing them from being used as inputs for other resources or modules in the overall infrastructure. This mechanism ensures controlled data flow and clear dependencies between different infrastructure components.

Why this answer

Module outputs are the mechanism by which a root module accesses values from child modules. Without outputs, any resource attributes created inside a module remain encapsulated and inaccessible to the calling configuration, making it impossible to use those values for interpolation or to pass them to other resources or modules.

Exam trap

A common misconception is that modules must be physically separated from the root module or that they must contain only one resource, when in fact modules are about logical grouping and can be nested locally.

132
MCQhard

Refer to the exhibit. A user applies this configuration. They then run 'terraform destroy' but the destroy fails with an error: 'Error deleting load balancer: DependencyViolation: The load balancer 'arn:aws:elasticloadbalancing:...' cannot be deleted because it is currently associated with another resource.' The user has not made any changes to the resources. What is the most likely cause?

A.The aws_lb_listener does not have explicit depends_on for the aws_lb_target_group.
B.The aws_lb_target_group is missing an explicit depends_on for the aws_lb_listener.
C.The aws_lb_target_group is missing an explicit depends_on for the aws_lb.
D.The aws_lb_listener is missing an explicit depends_on for the aws_lb.
AnswerD

The aws_lb_listener is indeed missing an explicit depends_on for the aws_lb. AWS API rules mandate that listeners must be deleted before their associated load balancer can be destroyed. Without an explicit depends_on on the listener for the load balancer, Terraform might attempt to destroy the load balancer first, leading to a DependencyViolation error from AWS. This explicit dependency ensures the correct destruction order, preventing the error.

Why this answer

The destroy fails because Terraform attempts to delete the load balancer before the listener that is associated with it. The listener has an implicit dependency on the load balancer via the `load_balancer_arn` attribute, but Terraform may not always recognize this implicit dependency, especially if the reference is indirect. Therefore, an explicit `depends_on` from the listener to the load balancer is required to ensure the listener is destroyed first, releasing the association and allowing the load balancer to be deleted.

Option D correctly identifies this missing dependency on the listener.

Exam trap

The error 'DependencyViolation' indicates that the load balancer cannot be deleted because it is still associated with a listener. Although the listener references the load balancer via `load_balancer_arn`, Terraform may not always infer this implicit dependency, especially if the reference comes from a module output or variable. Adding an explicit `depends_on` from the listener to the load balancer ensures the listener is destroyed first, releasing the association.

133
MCQhard

A team wants to reuse a VPC module across multiple environments. They need to pass outputs from one module as inputs to another. Which configuration is correct?

A.module "vpc" { source = "./vpc" } module "app" { source = "./app" subnet_id = module.vpc.outputs.subnet_id }
B.module "vpc" { source = "./vpc" } module "app" { source = "./app" subnet_id = vpc.output.subnet_id }
C.module "vpc" { source = "./vpc" } module "app" { source = "./app" subnet_id = module.vpc.subnet_id }
D.module "app" { source = "./app" subnet_id = module.vpc.subnet_id }
AnswerC

This option correctly demonstrates the standard and recommended way to reference an output value from a Terraform module. The syntax `module.vpc.subnet_id` directly accesses the `subnet_id` output defined within the `vpc` module. This allows the `app` module to receive the necessary resource ID, establishing an explicit dependency and enabling resource sharing between different module instances.

Why this answer

In Terraform, module outputs are accessed using the syntax `module.<module_name>.<output_name>`, not `module.<module_name>.outputs.<output_name>` or `vpc.output.<output_name>`. The `outputs` attribute is not a valid path; Terraform automatically exposes all declared outputs of a module as attributes of the module object. Therefore, `module.vpc.subnet_id` correctly references the `subnet_id` output from the `vpc` module.

Exam trap

The trap here is that candidates confuse Terraform's module output syntax with the `outputs` block used in root modules or with AWS CloudFormation's `Fn::GetAtt`, leading them to add an extra `.outputs` or omit the `module.` prefix.

How to eliminate wrong answers

Option A is wrong because it uses `module.vpc.outputs.subnet_id`, which incorrectly assumes a nested `outputs` attribute; Terraform does not expose outputs under an `outputs` key. Option B is wrong because it uses `vpc.output.subnet_id`, which is not a valid reference syntax — module outputs must be accessed via the `module` prefix, not a bare module name. Option D is wrong because it references `module.vpc.subnet_id` without first declaring the `vpc` module in the same configuration, so the reference would fail with an 'undefined module' error.

134
Multi-Selecteasy

A DevOps engineer wants to modify the Terraform configuration to control resource lifecycle behavior. Which TWO meta-arguments can be used to influence the order of creation and destruction?

Select 2 answers
A.create_before_destroy
B.depends_on
C.for_each
D.prevent_destroy
E.count
AnswersA, B

The `create_before_destroy` lifecycle argument is essential for minimizing downtime during resource updates that require replacement rather than in-place modification. When set to `true`, Terraform will provision the new version of the resource, update any dependent resources to point to the new instance, and only then destroy the old resource. This ensures continuous availability and prevents service interruptions during a resource's lifecycle replacement.

Why this answer

`create_before_destroy` is a meta-argument used within a `lifecycle` block to instruct Terraform to create a replacement resource before destroying the existing one, directly influencing the order of creation and destruction during updates. Option B is correct because `depends_on` explicitly sets dependencies between resources, ensuring that Terraform creates or destroys resources in a specific order based on those declared dependencies.

Exam trap

Candidates often confuse meta-arguments that control lifecycle behavior (like `create_before_destroy` and `prevent_destroy`) with those that control resource count or iteration (like `count` and `for_each`). Specifically, `prevent_destroy` does not influence creation/destruction order; it only blocks destruction.

135
Multi-Selecteasy

Which TWO of the following are valid strategies to migrate Terraform state from a local backend to a remote backend?

Select 2 answers
A.Use terraform import for each resource
B.Manually copy the local state file to the remote backend storage
C.Change backend configuration and run terraform init -reconfigure
D.Use terraform init with the -migrate-state flag
E.Use the terraform state push command
AnswersB, D

Manually copying the local state file (`terraform.tfstate`) to the remote backend storage location is a valid, albeit less automated, strategy. This approach requires direct interaction with the remote storage system (e.g., uploading to an S3 bucket or Azure Blob Storage). After the manual copy, you must then run `terraform init` (without the `-migrate-state` flag, as the state is already present) to configure Terraform to recognize and use the state file now residing in the remote backend.

Why this answer

The valid strategies for migrating state from local to remote backend are: manually copying the state file to the remote location (B) or using `terraform init -migrate-state` (D). Option C is incorrect because `terraform init -reconfigure` only reconfigures the backend without migrating the existing state.

136
MCQmedium

A company has a Terraform module that creates an AWS VPC with subnets. They want to reuse this module across multiple AWS accounts. What is the best practice for referencing the module from different root configurations?

A.Store the module in a shared S3 bucket and reference it with the module source.
B.Use a module registry and specify a version constraint.
C.Use a data source to fetch the module's output from another state.
D.Copy the module code into each root configuration's directory.
AnswerB

A module registry, such as the public Terraform Registry or a private registry in Terraform Cloud/Enterprise, provides a centralized, discoverable, and version-controlled repository for sharing modules. Specifying a version constraint (e.g., `~> 1.0.0`) ensures that consumers utilize a compatible module version, enabling controlled updates and preventing unintended breaking changes. This approach significantly promotes reusability, consistency, and efficient collaboration across an organization's Terraform configurations.

Why this answer

Using a module registry with a version constraint is the best practice for reusing Terraform modules across multiple AWS accounts. It provides a centralized, version-controlled source that can be referenced by any root configuration via a simple source address (e.g., `registry.terraform.io/org/module/aws`), ensuring consistency and enabling safe upgrades through semantic versioning. This approach avoids duplicating code and leverages Terraform's built-in dependency resolution and caching mechanisms.

Exam trap

Candidates may think that using a remote source like S3 or Git is just as good as the HashiCorp Terraform Registry. However, the registry provides built-in version resolution, centralized management, and is the recommended best practice for sharing modules across multiple root configurations and accounts.

How to eliminate wrong answers

Option A is wrong because storing a module in an S3 bucket and referencing it with `source = "s3::https://bucket/path"` works for sharing, but it lacks built-in versioning and dependency resolution; you must manually manage versions via object keys or separate buckets, making it less robust than a registry. Option C is wrong because using a `data` source to fetch a module's output from another state file (e.g., `terraform_remote_state`) reads outputs from an existing deployment, not the module code itself, so it cannot be used to reuse the module definition across root configurations. Option D is wrong because copying the module code into each root configuration's directory violates DRY principles, creates maintenance overhead, and makes it difficult to propagate updates or enforce consistent versions across accounts.

137
MCQeasy

A small startup uses Terraform to manage infrastructure on AWS. They store the state file directly in a Git repository (gitignored but accidentally committed) and have no remote backend. The team has two engineers: Alice and Bob. They both run Terraform from their local machines. Recently, they experienced state conflicts where Alice's apply would succeed but subsequently Bob's apply would fail due to state drift. They want a simple solution without adding too much complexity. What should they do?

A.Add the state file to .gitignore and stop versioning it.
B.Configure an S3 backend with DynamoDB locking and have both engineers use the remote state.
C.Continue with the current setup but ask Alice and Bob to coordinate via Slack before running apply.
D.Switch to Terraform Cloud with remote execution for automated locking.
AnswerB

Configuring an S3 backend centralizes the Terraform state file, establishing a single, authoritative source of truth accessible to all team members, which is crucial for collaborative infrastructure management. Integrating DynamoDB for state locking ensures that only one `terraform apply` operation can modify the state at any given time, effectively preventing concurrent changes from causing state corruption or overwriting each other's work. This combination is the industry standard for maintaining state consistency and preventing race conditions in shared environments.

Why this answer

Configuring an S3 backend with DynamoDB locking provides a remote state file that both engineers can access, along with state locking to prevent concurrent modifications. This directly solves the state conflicts without adding excessive complexity. Option A (adding .gitignore) does not address the conflict issue since the state is still local and not shared.

Option C (coordination via Slack) is unreliable and does not prevent race conditions. Option D (Terraform Cloud) is a valid solution but adds more complexity than the simple S3+DynamoDB setup, which is the recommended approach for small teams.

138
MCQhard

You are a DevOps engineer for a company that uses Terraform to manage infrastructure across multiple AWS accounts (production, staging, development). Each account has its own Terraform configuration and remote state stored in an S3 bucket with DynamoDB locking. Recently, the production deployment pipeline failed with the error: 'Error: Error loading state: AccessDenied: Access Denied'. The pipeline runs under an IAM role that has been working for months. The S3 bucket policy and IAM role permissions have not been changed. However, the team did recently enable S3 bucket versioning and added a lifecycle policy to transition objects to Glacier after 30 days. The state file was last modified 35 days ago. What is the most likely cause of the error?

A.The DynamoDB lock table has a stale lock from a previous deployment that is blocking read access.
B.The IAM role's permissions were inadvertently revoked due to a recent AWS policy change.
C.The S3 bucket policy now denies access to objects older than 30 days due to a new condition key.
D.The state file was transitioned to Amazon S3 Glacier by the lifecycle policy, and Terraform cannot read it without restoration.
AnswerD

When an S3 object, such as a Terraform state file, is transitioned to the Amazon S3 Glacier or Glacier Deep Archive storage class by a lifecycle policy, it is no longer immediately accessible via standard S3 GetObject requests. Attempting to retrieve an object in Glacier without first initiating a restoration job will result in an AccessDenied error from S3. Terraform requires immediate, direct read access to its state file, making restoration a necessary prerequisite for any operations if the state is archived in Glacier.

Why this answer

D is correct because the S3 lifecycle policy transitions objects to the Glacier storage class after 30 days. The state file was last modified 35 days ago, so it has been moved to Glacier. Terraform cannot read objects in the Glacier storage class directly; it requires a restoration (e.g., using `aws s3api restore-object`) before the state can be accessed, resulting in the 'AccessDenied' error.

Exam trap

HashiCorp often tests the distinction between 'AccessDenied' errors caused by storage class transitions (e.g., Glacier) versus permission-based denials, and the trap here is that candidates may assume the error is due to a policy change or stale lock, ignoring the lifecycle policy's effect on object accessibility.

How to eliminate wrong answers

Option A is wrong because a stale DynamoDB lock would cause a 'lock acquisition' error (e.g., 'Error acquiring the state lock'), not an 'AccessDenied' error when loading state. Option B is wrong because the scenario explicitly states that the IAM role permissions and S3 bucket policy have not been changed, so a policy revocation is not the cause. Option C is wrong because S3 bucket policies do not automatically deny access based solely on object age unless a specific condition key (e.g., `s3:ObjectAgeInDays`) is explicitly added to the policy, and the scenario says the policy was not changed.

139
MCQmedium

A team uses Terraform to manage AWS resources. After a manual change to an S3 bucket policy through the AWS console, Terraform's next plan shows that it will revert the policy to the configuration. This is an example of which concept?

A.Configuration drift and correction
B.Immutable infrastructure
C.Resource tagging
D.Imperative provisioning
AnswerA

When a team manually alters an AWS resource managed by Terraform, it creates "configuration drift" where the actual infrastructure deviates from the defined desired state in the Terraform configuration. Terraform detects this discrepancy during a `terraform plan` operation by comparing the current state file with the live infrastructure and the configuration files. The proposed plan to revert the manual change back to the configuration's desired state exemplifies the "correction" mechanism, ensuring infrastructure consistency.

Why this answer

This scenario describes configuration drift, where a manual change to an S3 bucket policy via the AWS console creates a difference between the actual state of the resource and the desired state defined in Terraform code. Terraform's next plan detects this drift and will revert the policy to match the configuration, demonstrating its correction mechanism. This is a core principle of declarative IaC tools like Terraform, which enforce the desired state and automatically remediate any out-of-band changes.

Exam trap

Terraform certification exams often test the distinction between configuration drift correction and immutable infrastructure. Candidates may mistakenly think any automated change implies immutability, but drift correction modifies existing resources rather than replacing them.

How to eliminate wrong answers

Option B is wrong because immutable infrastructure refers to replacing resources entirely rather than modifying them in place, whereas Terraform here is reverting a policy change on an existing S3 bucket, not replacing the bucket. Option C is wrong because resource tagging is a metadata practice for organizing and labeling resources, not a mechanism for detecting or correcting state mismatches. Option D is wrong because imperative provisioning involves step-by-step commands to achieve a desired state, while Terraform uses a declarative approach where the configuration defines the end state and the tool handles the steps to reach it.

140
MCQeasy

A developer is new to infrastructure as code and wants to deploy a simple web server on AWS using a tool that allows them to define the infrastructure in a reusable and version-controlled manner. They are considering using the AWS Management Console, AWS CLI, or Terraform. Which course of action aligns best with Terraform's purpose?

A.Use Terraform to define the web server in a .tf file and run terraform apply.
B.Use the AWS Management Console to manually create the web server.
C.Write a shell script using the AWS CLI to provision resources.
D.Use Terraform but only with local state and no version control.
AnswerA

Terraform's declarative configuration, defined in a .tf file, specifies the desired end state of the web server infrastructure. Running terraform apply then intelligently provisions or modifies resources to match this state, ensuring idempotency and providing a consistent, version-controlled blueprint for the environment. This approach automates infrastructure provisioning and updates reliably.

Why this answer

Terraform is designed for infrastructure as code, allowing declarative configuration, version control, and automation. The console is manual, CLI is imperative and not idempotent. Terraform's purpose is to provision infrastructure as code.

141
MCQhard

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?

A.Run 'terraform plan' to see the detailed error.
B.Use 'terraform console' to test the policy string.
C.Use a JSON validator tool to check the policy string in the configuration.
D.Upgrade to the latest Terraform version.
AnswerC

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.

Why this answer

The error 'The policy failed validation' indicates that the JSON-encoded IAM policy string in the Terraform configuration is malformed or violates AWS IAM policy syntax. Using a JSON validator tool (e.g., `jq`, online validator, or `aws iam simulate-custom-policy`) directly checks the string's structure and compliance with AWS IAM policy schema, which is the most efficient first step before re-running Terraform. This isolates the issue from Terraform's execution logic and avoids unnecessary plan/apply cycles.

Exam trap

HashiCorp often tests the misconception that `terraform plan` catches all errors, but plan only validates Terraform configuration syntax and state drift, not the semantic correctness of embedded JSON strings that are passed to external APIs.

How to eliminate wrong answers

Option A is wrong because `terraform plan` does not validate the syntax of a JSON-encoded IAM policy string; it only compares the desired state with the current state and would not catch validation errors that occur during apply. Option B is wrong because `terraform console` is used to evaluate expressions and test interpolation, not to validate JSON policy strings or AWS IAM policy syntax. Option D is wrong because upgrading Terraform version does not fix a malformed JSON policy string; the error is a content validation issue, not a software bug.

142
MCQhard

An organization uses Terraform Cloud with VCS-driven runs. They have two workspaces: network and application. They want a new run in the application workspace to automatically trigger whenever the network workspace completes a successful plan. What should they configure?

A.Run triggers in the application workspace pointing to the network workspace.
B.A webhook from Terraform Cloud to an external CI system.
C.Use 'terraform apply' with '-target' to simulate dependency.
D.Run triggers in the network workspace pointing to the application workspace.
AnswerA

Run triggers are configured in the *downstream* workspace to monitor an *upstream* workspace. Therefore, for the application workspace to depend on the network workspace, the application workspace (downstream) must have a run trigger configured to watch the network workspace (upstream). When the network workspace successfully completes a `terraform apply`, it will automatically queue a run in the application workspace, ensuring proper dependency ordering and resource availability in a VCS-driven Terraform Cloud environment.

Why this answer

Run triggers in Terraform Cloud allow one workspace to automatically queue a run in another workspace after a successful plan. By configuring a run trigger in the application workspace that points to the network workspace, any successful plan in the network workspace will automatically initiate a new run in the application workspace, satisfying the requirement without external tools or manual steps.

Exam trap

The trap here is that candidates often confuse the direction of run triggers, thinking they should be configured on the upstream workspace (network) pointing to the downstream (application), when in fact they must be set on the downstream workspace (application) pointing to the upstream (network).

How to eliminate wrong answers

Option B is wrong because a webhook to an external CI system introduces unnecessary complexity and external dependencies; Terraform Cloud’s native run triggers provide the same functionality directly. Option C is wrong because 'terraform apply -target' is used to apply only specific resources within a single workspace, not to trigger cross-workspace runs, and it does not automate dependency-based triggering. Option D is wrong because run triggers are configured in the downstream workspace (the one that needs to be triggered), not in the upstream workspace; pointing from network to application would not cause the application workspace to run when network completes.

143
MCQhard

A DevOps team accidentally deleted their Terraform state file. The actual infrastructure (EC2 instances, security groups, etc.) is still running and unchanged. They have the Terraform configuration files that were used to create the infrastructure. They want to re-establish management of the existing infrastructure without recreating it. Which course of action aligns with Terraform's purpose?

A.Delete all existing infrastructure and run terraform apply to recreate it.
B.Manually edit the configuration to match the existing resources exactly, then run terraform apply.
C.Run terraform plan to generate a new state file automatically.
D.Use terraform import for each resource to bring them into the state file.
AnswerD

Using terraform import for each resource is the correct and most robust method to recover from a lost state file without disrupting existing infrastructure. This command allows you to link an existing cloud resource, identified by its provider-specific ID, to a corresponding resource block defined in your Terraform configuration. By systematically importing each managed resource, Terraform rebuilds its state file, establishing a new authoritative record of the infrastructure it controls.

Why this answer

Terraform's purpose includes managing existing infrastructure through import. Using terraform import allows you to bring resources into state without recreation. Deleting and recreating is disruptive, and modifying config without state is risky.

144
MCQmedium

Refer to the exhibit. After applying the plan, the state serial number is 2. What was the serial number before the apply?

A.0
B.1
C.3
D.2
AnswerB

The Terraform state serial consistently increments by exactly one (1) for every successful modification to the state file, regardless of the number of resources added, changed, or destroyed within that single `terraform apply` operation. This behavior ensures a clear, sequential version history of the infrastructure's configuration as managed by Terraform. Therefore, after applying a plan that modifies the state, the serial will increase by 1.

Why this answer

The serial number increments by 1 each time state is modified. Initially the state had serial 1 (or 0 if fresh). After the apply adding one resource, serial becomes 2, so previous serial was 1.

145
MCQhard

An organization uses Terraform workspaces to manage multiple environments (dev, staging, prod). They notice that terraform plan in the prod workspace unexpectedly shows changes to a resource that should be identical across workspaces. The resource uses a backend that stores state in an S3 bucket. What is the most likely cause?

A.The prod workspace was created by copying the dev workspace state.
B.The S3 bucket does not support versioning.
C.The terraform.workspace variable is used in the resource configuration.
D.The provider version differs between workspaces.
AnswerC

The `terraform.workspace` variable provides the name of the currently selected workspace, allowing for dynamic configuration based on the execution context. By incorporating this variable into resource arguments, such as `name = "my-resource-${terraform.workspace}"` or conditional logic using `count` or `for_each`, the same configuration can provision distinct resources or resource attributes across different workspaces. This direct manipulation of resource definitions based on the workspace name is the most common and intended mechanism for generating varying `terraform plan` outputs from a single set of configuration files.

Why this answer

If the `terraform.workspace` variable is used directly in a resource configuration (e.g., in a name, tag, or identifier), the resource definition will differ between workspaces. Since the prod workspace has a different workspace name than dev, the plan will show changes to resources that are otherwise identical, as Terraform detects the difference in the interpolated value.

Exam trap

A common misconception in Terraform is that workspace differences are solely due to state management issues (like copying state or versioning) rather than configuration logic. The trap here is assuming that identical resource definitions across workspaces are automatically enforced without checking for workspace-aware variables like 'terraform.workspace' in the configuration.

How to eliminate wrong answers

Option A is wrong because copying state from dev to prod would not cause unexpected plan changes for resources that should be identical; it would simply replicate the same state, and any differences would stem from configuration, not state copying. Option B is wrong because S3 bucket versioning affects state file history and rollback capabilities, not the content of the plan or the detection of configuration differences across workspaces. Option D is wrong because provider versions are defined in the Terraform configuration (e.g., required_providers block) and are consistent across all workspaces in the same directory; differing provider versions would require separate configurations or manual overrides, not workspace isolation.

146
MCQeasy

A team wants to use Terraform to provision infrastructure across multiple cloud providers. Which configuration approach best supports this goal?

A.Define multiple provider blocks, one for each cloud provider.
B.Use a single provider block that supports multiple clouds.
C.Terraform cannot manage multiple clouds in one configuration.
D.Create separate workspaces for each cloud provider.
AnswerA

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.

Why this answer

Terraform uses multiple provider blocks to manage resources from different cloud providers within a single configuration. Each provider block configures a separate provider (e.g., aws, azurerm, google) with its own authentication and region settings, allowing Terraform to provision and manage infrastructure across AWS, Azure, GCP, and others in the same state file and execution plan.

Exam trap

HashiCorp often tests the misconception that Terraform can only manage a single cloud or that a single provider block can be reused across clouds, when in fact multiple provider blocks are required and fully supported for multi-cloud configurations.

How to eliminate wrong answers

Option B is wrong because no single Terraform provider block supports multiple clouds; each provider is specific to a single platform (e.g., hashicorp/aws, hashicorp/azurerm) and cannot be shared across different cloud providers. Option C is wrong because Terraform explicitly supports multi-cloud configurations by defining multiple provider blocks, as demonstrated in official documentation and real-world use cases. Option D is wrong because workspaces are used to manage multiple instances of the same configuration (e.g., dev, staging, prod) and do not isolate or separate providers; using separate workspaces for each cloud provider would not enable multi-cloud management within a single configuration.

147
MCQmedium

Refer to the exhibit. A user attempts to run terraform apply with this configuration. What error will occur?

A.Conflicting access control settings
B.Missing required provider configuration
C.Duplicate resource name "mybucket"
D.Invalid bucket name pattern
AnswerC

Terraform requires that all resources within a given module have a unique combination of resource type and local name. In the provided configuration, there are two separate `aws_s3_bucket` resources both declared with the local name `mybucket`. This duplication creates an ambiguous reference and violates Terraform's naming conventions, leading to a validation error during the plan or apply phase because Terraform cannot uniquely identify or manage these distinct resources.

Why this answer

Terraform requires every resource block to have a unique address within the same module. If two `aws_s3_bucket` resources both use the same logical name `mybucket`, Terraform will reject the configuration with a `Duplicate resource name` error during the `plan` or `apply` phase. This is a fundamental rule of Terraform's configuration language, enforced at parse time before any provider interaction occurs.

Exam trap

A common pitfall is confusing Terraform's core language validation (which catches duplicate resource names) with provider-level validation (which catches invalid bucket names or missing configurations). This question tests the distinction between a local naming error and a provider or API error.

How to eliminate wrong answers

Option A is wrong because access control settings (like bucket policies or ACLs) are configured within the resource arguments, not at the resource naming level, and Terraform does not raise a 'conflicting access control' error from duplicate resource names. Option B is wrong because a missing provider configuration would cause a different error, such as 'No provider configuration found' or 'Provider not configured', not a duplicate name error. Option D is wrong because bucket name pattern validation (e.g., DNS-compliant naming) is performed by the AWS provider or API, not by Terraform's core parser, and would produce an error like 'Invalid bucket name' rather than a duplicate resource error.

148
MCQeasy

A developer is new to Terraform and wants to understand the purpose of the terraform init command. Which statement correctly describes its primary function?

A.It initializes the local environment by downloading the required provider plugins and modules.
B.It checks the syntax of all configuration files.
C.It compares the state file with real infrastructure.
D.It creates the initial configuration for a new Terraform project.
AnswerA

The `terraform init` command is foundational, executed first in a new or cloned Terraform project to prepare the local environment. It scans the configuration files (e.g., `.tf` files) to identify all declared `required_providers` and any `module` blocks. Subsequently, it downloads the specified provider plugins from the Terraform Registry or configured mirrors, and fetches remote modules, storing them in the `.terraform` directory. This process ensures all necessary components are available for subsequent commands like `terraform plan` or `terraform apply`.

Why this answer

`terraform init` is the first command to run in any Terraform project. Its primary function is to initialize the working directory by downloading and installing the required provider plugins (e.g., from the Terraform Registry) and modules specified in the configuration. It also sets up the backend for state storage and locks, ensuring the local environment is ready for subsequent commands like `plan` and `apply`.

Exam trap

A common trap in Terraform certification is confusing `terraform init` with `terraform validate` or `terraform plan`. Candidates may think `init` checks syntax or creates the project, but it strictly downloads providers/modules and initializes the backend.

How to eliminate wrong answers

Option B is wrong because syntax checking of configuration files is performed by `terraform validate`, not `init`. Option C is wrong because comparing the state file with real infrastructure is the job of `terraform plan`, which detects drift. Option D is wrong because `terraform init` does not create initial configuration; it initializes an existing configuration directory.

Creating a new project typically involves writing `.tf` files manually or using `terraform scaffold` or a template.

149
MCQhard

Refer to the exhibit. An engineer receives this error when running terraform apply. What is the most likely cause?

A.The policy JSON is missing a required field like "Sid".
B.The Action element should be an array, not a string.
C.The Resource ARN is incorrect because it lacks a region.
D.The policy exceeds the maximum size limit.
AnswerB

AWS IAM policy syntax strictly mandates that the `Action` element must be an array of strings, even when only a single action is specified. If the `Action` element is provided as a plain string (e.g., `"s3:GetObject"`) instead of being encapsulated within an array (e.g., `["s3:GetObject"]`), the IAM policy parser will encounter a type mismatch error. This fundamental syntax requirement is a common source of errors and prevents the policy from being correctly interpreted and applied.

Why this answer

The error indicates a malformed policy JSON. In IAM policy syntax, the `Action` element must be an array of strings, even if only one action is specified. The provided policy has `"Action": "ec2:DescribeInstances"` (a string), which is invalid; it should be `"Action": ["ec2:DescribeInstances"]`.

This is the most likely cause of the error.

150
Multi-Selecteasy

Which TWO of the following are valid ways to use Terraform outside the core workflow? (Choose two.)

Select 2 answers
A.Using Terraform to manage application secrets lifecycle.
B.Using Terraform outputs as inputs for other tools like Ansible.
C.Using Terraform to install software on existing servers.
D.Using Terraform as a CI/CD pipeline tool.
E.Using Terraform state to generate infrastructure diagrams.
AnswersB, E

Terraform outputs provide a structured and machine-readable mechanism to expose specific values derived from the managed infrastructure, such as newly provisioned IP addresses, DNS names, or resource IDs. These exposed values are easily consumed by other automation tools, including configuration management systems like Ansible, custom scripts, or subsequent stages in a CI/CD pipeline, enabling seamless integration and data flow between different components of an automation stack.

Why this answer

Terraform outputs can be consumed by other tools like Ansible via the `terraform output` command or by referencing the state file, enabling integration in multi-tool workflows. Option E is correct because the Terraform state file (`.tfstate`) contains all resource attributes and dependencies, which can be parsed programmatically or with tools like `terraform graph` to generate infrastructure diagrams, extending Terraform's use beyond provisioning.

Exam trap

HashiCorp often tests the distinction between provisioning (Terraform) and configuration management (Ansible, Chef), so candidates mistakenly think Terraform can install software or manage secrets, when it is strictly for infrastructure lifecycle and state-driven outputs.

Page 1

Page 2 of 6

Page 3

All pages