Courseiva

CCNA Read, generate and modify configuration Questions

56 questions · Read, generate and modify configuration · All types, answers revealed

1
MCQmedium

An operator wants to pass output values from one Terraform configuration to another as input variables. Which approach is recommended?

A.Hardcode the output values in a variables file for the second configuration.
B.Store outputs in a shared file and use 'file()' function to read them.
C.Use a remote state data source to read the outputs from the first configuration's state.
D.Use environment variables to pass the output values.
AnswerC

Using a `terraform_remote_state` data source is the standard and recommended method for consuming outputs from a separate Terraform configuration. This data source securely reads the specified remote state file, allowing the second configuration to access the first's outputs directly and consistently. It establishes an implicit dependency, ensuring that the source configuration's state is available and up-to-date before the consuming configuration applies changes.

Why this answer

Terraform's remote state data source (e.g., `terraform_remote_state`) allows one configuration to securely read output values from another configuration's state file stored in a shared backend (like S3, Azure Storage, or Consul). This avoids duplication, manual errors, and ensures that the second configuration always uses the latest outputs from the first, without requiring direct file access or environment variables.

Exam trap

The trap here is that candidates often choose Option B (shared file with `file()`) because it seems simple and familiar, but they overlook that Terraform's `file()` function reads a static file at plan time and does not integrate with state management, leading to stale or inconsistent values across runs.

How to eliminate wrong answers

Option A is wrong because hardcoding output values in a variables file creates a manual, error-prone process that breaks automation and requires updates whenever the first configuration changes. Option B is wrong because using `file()` to read outputs from a shared file introduces a dependency on a static file path, lacks state locking, and does not automatically reflect changes in the first configuration's state; it also bypasses Terraform's native state management. Option D is wrong because environment variables are ephemeral, not tied to Terraform state, and require external orchestration to set them correctly, making them unsuitable for reliable, repeatable infrastructure-as-code workflows.

2
MCQeasy

Refer to the exhibit. What is the purpose of this output block?

A.To store the public IP in a local file.
B.To set the public IP as a variable for use in other configurations.
C.To create a DNS record with the public IP.
D.To display the public IP address of the instance after apply.
AnswerD

The primary purpose of a Terraform `output` block is to define values that will be displayed to the user's console upon successful completion of a `terraform apply` operation. This allows operators to easily retrieve important information, such as an instance's public IP address, connection strings, or URLs, without needing to inspect the state file directly. Additionally, these outputs are stored in the state file and can be programmatically accessed by other Terraform configurations via remote state data sources.

Why this answer

The output block shown in the exhibit is a Terraform output value, which is defined using the `output` block in a configuration file. Its purpose is to display the public IP address of the instance in the terminal after `terraform apply` completes, providing a quick reference for the user. Option D correctly identifies this behavior, as outputs are designed to surface resource attributes to the user without storing them or creating external records.

Exam trap

The TF-003 exam often tests the distinction between Terraform outputs and other mechanisms like variables or resource declarations, and the trap here is that candidates confuse the display-only purpose of outputs with the ability to store data in files or create external resources, leading them to select options A, B, or C.

How to eliminate wrong answers

Option A is wrong because Terraform output blocks do not store values in a local file by default; they only display values in the CLI or make them available for `terraform output` command, and storing to a file would require a separate `local_file` resource or a provisioner. Option B is wrong because output values are not variables for use in other configurations within the same root module; they are read-only values exposed to the user or to other modules via module outputs, but they cannot be referenced as variables in the same configuration. Option C is wrong because creating a DNS record requires a dedicated resource (e.g., `aws_route53_record`), and an output block alone does not interact with DNS providers or create any records.

3
Multi-Selecteasy

Which TWO statements about Terraform data sources are correct?

Select 2 answers
A.Data sources can be used in count and for_each.
B.Data sources can fetch information from external systems.
C.Data sources are only available after applying the configuration.
D.Data sources are used to create new infrastructure.
E.Data sources cannot be used inside modules.
AnswersA, B

Data sources are evaluated during the plan phase, making their output available to Terraform's meta-arguments. This allows their attributes, such as a list of IDs or names fetched from an external system, to dynamically drive the `count` or `for_each` argument of a resource or module. Consequently, you can provision multiple instances of infrastructure based on existing external data, enabling highly dynamic and data-driven configurations. This is a powerful pattern for managing infrastructure that adapts to external state.

Why this answer

Terraform data sources are regular resources that support the `count` and `for_each` meta-arguments, allowing you to dynamically fetch data for multiple instances or conditional logic. This enables patterns like iterating over a list of external IDs to retrieve corresponding data from a provider, such as fetching multiple AMI IDs for different regions.

Exam trap

The trap here is that candidates confuse data sources with managed resources, assuming they require an apply to be available or that they create infrastructure, when in fact they are read-only and resolved during planning.

4
MCQhard

A Terraform configuration uses a for_each expression to create multiple subnets. After applying, one subnet's configuration needs to be modified. The engineer updates the resource block's map key for that subnet. What will terraform plan show?

A.No changes because the subnet configuration is the same.
B.Only deletion of the old subnet.
C.An in-place update to the subnet.
D.Destruction of the existing subnet and creation of a new one.
AnswerD

This is the correct outcome. The `for_each` key is an integral part of a resource's unique address in the Terraform state. When this key changes, Terraform no longer finds the resource instance identified by the *old* key in the current configuration, marking it for destruction. Concurrently, it identifies a *new* resource instance, defined by the *new* key, which it plans to create. This process ensures that the desired state, reflecting the updated `for_each` keys, is accurately achieved through a destroy-and-create operation.

Why this answer

When a for_each expression is used, Terraform identifies each resource instance by its map key. Changing the map key for a subnet causes Terraform to treat the old key as a resource to be destroyed and the new key as a resource to be created, because the key is part of the resource's identity. Even if the configuration inside the block is identical, the change in key results in a destroy-and-create action, not an in-place update.

Exam trap

The trap here is that candidates often confuse a change in the for_each key with a change in the resource's arguments, assuming that identical configuration means no changes, when in fact the key itself is part of the resource identity and forces replacement.

How to eliminate wrong answers

Option A is wrong because changing the map key alters the resource's identity in the state, so Terraform detects a change even if the subnet configuration values are the same. Option B is wrong because Terraform will also create a new subnet for the new key, not just delete the old one. Option C is wrong because an in-place update only occurs when the resource address (including the for_each key) remains the same; changing the key forces a replacement.

5
MCQhard

You are managing a Terraform configuration for a multi-tier application that includes AWS EC2 instances, an RDS database, and an Application Load Balancer. The configuration uses multiple modules and remote state stored in an S3 bucket with DynamoDB locking. Recently, a colleague made changes to the configuration and applied them successfully. However, you now need to make additional changes and, when you run 'terraform plan', you receive an error: "Error: Error acquiring the state lock". The error message indicates that the lock is held by a different user. You have confirmed that your colleague is not currently running Terraform. What is the most appropriate course of action to proceed with your changes?

A.Edit the state file to remove the lock metadata.
B.Run 'terraform init -reconfigure' to reset the backend and release the lock.
C.Delete the lock file from the S3 bucket manually.
D.Run 'terraform force-unlock <lock_id>' to remove the stale lock.
AnswerD

The `terraform force-unlock <lock_id>` command is the correct and recommended method for releasing a stale state lock that was not automatically released after a failed or interrupted operation. This command safely interacts with the backend's locking mechanism, ensuring that the lock is properly removed and the state is accessible for subsequent operations. Requiring the `<lock_id>` adds a crucial layer of safety, preventing accidental unlocking of an active or incorrect lock.

Why this answer

Terraform uses DynamoDB for state locking to prevent concurrent modifications. When a lock becomes stale (e.g., due to a crash or network interruption), `terraform force-unlock <lock_id>` is the proper command to manually release it. This preserves the integrity of the state file and avoids manual S3 or DynamoDB edits, which could corrupt the state or break the locking mechanism.

Exam trap

HashiCorp often tests the misconception that manual S3 or DynamoDB manipulation is acceptable, when in fact Terraform provides a safe, built-in command (`force-unlock`) to handle stale locks without risking state corruption.

How to eliminate wrong answers

Option A is wrong because editing the state file directly to remove lock metadata is unsafe; it can corrupt the state and bypass Terraform's consistency checks. Option B is wrong because `terraform init -reconfigure` reinitializes the backend configuration but does not release an existing lock; it may even fail if the lock is still present. Option C is wrong because deleting the lock file from the S3 bucket manually does not remove the DynamoDB lock entry, so the lock remains active and the error persists.

6
MCQhard

An organization has a policy that all AWS S3 buckets must have versioning enabled. They want to ensure that even if someone removes the `versioning` block from the configuration, the bucket still has versioning enabled after `terraform apply`. Which lifecycle configuration should they add to the `aws_s3_bucket` resource?

A.`ignore_changes = [versioning]`
B.`replace_triggered_by = [aws_s3_bucket_versioning.this]`
C.`prevent_destroy`
D.`create_before_destroy`
AnswerA

The `ignore_changes` lifecycle meta-argument instructs Terraform to disregard any differences detected for the specified attributes between the configuration and the real-world state during a plan. By setting `ignore_changes = [versioning]`, Terraform will not attempt to revert or modify the `versioning` configuration of the S3 bucket, even if it has been changed outside of Terraform. This is the correct approach to prevent Terraform from undoing an out-of-band modification to a specific attribute, ensuring the external change persists.

Why this answer

`ignore_changes = [versioning]` tells Terraform to disregard any changes to the `versioning` block in the configuration during `terraform apply`. This ensures that even if someone removes the `versioning` block from the HCL, the existing versioning state on the S3 bucket (enabled) remains unchanged, enforcing the organization's policy.

Exam trap

Terraform often tests the distinction between lifecycle meta-arguments that prevent resource destruction (like `prevent_destroy`) versus those that prevent configuration drift (like `ignore_changes`), and the trap here is that candidates confuse `prevent_destroy` with protecting individual attributes from being overwritten.

How to eliminate wrong answers

Option B is wrong because `replace_triggered_by = [aws_s3_bucket_versioning.this]` is used to force resource recreation when a referenced resource changes, not to preserve existing settings; it would cause the bucket to be replaced if the versioning resource is modified, which is not the goal. Option C is wrong because `prevent_destroy` prevents the entire bucket from being destroyed but does not protect the `versioning` configuration from being overwritten or removed during updates. Option D is wrong because `create_before_destroy` controls the order of resource creation and destruction during replacement, but does not prevent changes to the `versioning` block from being applied.

7
MCQmedium

A configuration defines a variable `instance_type` with a default value `t2.micro`. After running `terraform apply`, the operator notices that the instances are being created with type `t2.small`. They check the configuration file and see the default is `t2.micro`. What is the most likely cause?

A.The variable declaration was changed after apply.
B.The state file stores the variable value and overrides the default.
C.A `terraform.tfvars` file in the working directory sets the variable to `t2.small`.
D.The `instance_type` attribute was changed by a lifecycle rule.
AnswerC

A `terraform.tfvars` file located in the working directory is one of the primary mechanisms Terraform uses to automatically load variable values. When present, values defined within this file take precedence over any `default` values specified directly within the variable's declaration in the configuration. This behavior ensures that specific deployments can easily override general defaults for resources like `instance_type`.

Why this answer

Terraform automatically loads any file named `terraform.tfvars` or `*.auto.tfvars` in the working directory, and the variable values defined in these files override the default values declared in the configuration. Even though the configuration file shows `instance_type` defaulting to `t2.micro`, the presence of a `terraform.tfvars` file setting `instance_type = "t2.small"` will cause Terraform to use `t2.small` during `apply`, explaining the observed behavior.

Exam trap

The TF-003 exam often tests the subtle distinction between where variable values are stored (state vs. variable files) and the automatic loading behavior of `terraform.tfvars`, leading candidates to incorrectly blame the state file or lifecycle rules for value overrides.

How to eliminate wrong answers

Option A is wrong because changing the variable declaration after `apply` would not retroactively affect already-created instances; the operator checked the configuration and saw the default unchanged, so this does not explain why instances were created with a different type. Option B is wrong because the state file stores resolved resource attributes (like the actual `instance_type` used), not the variable default value, and it does not override configuration defaults — it reflects what was applied. Option D is wrong because lifecycle rules (e.g., `create_before_destroy`, `prevent_destroy`) do not modify resource attribute values like `instance_type`; they control the order or protection of resource operations, not the values themselves.

8
Multi-Selecthard

Which THREE variable declarations are valid in Terraform?

Select 3 answers
A.variable "enabled" { type = bool default = true }
B.variable "tags" { type = map(string) default = {} }
C.variable "region" { type = string default = "us-east-1" }
D.variable "names" { type = list(string) default = "name" }
E.variable "count" { type = number default = "1" }
AnswersA, B, C

This variable declaration is valid because the `type` constraint is correctly set to `bool`, and the `default` value provided, `true`, is a literal boolean value. Terraform successfully validates that the default value's type precisely matches the explicitly declared `bool` type, ensuring strict type consistency for the variable. This configuration allows the variable to accept only `true` or `false` values.

Why this answer

Terraform variable declarations require a `type` argument and optionally a `default` value. Here, `type = bool` is a valid primitive type, and `default = true` provides a boolean default, which matches the type constraint. This syntax follows Terraform's variable block specification, where the default value must be compatible with the declared type.

Exam trap

Terraform often tests the strict type-default compatibility rule, where candidates mistakenly assume Terraform will implicitly convert a string to a number or a single value to a list, but Terraform requires exact type matching for defaults.

9
MCQeasy

Refer to the exhibit. A developer runs 'terraform plan' and receives the following error: 'Error: InvalidAMIID.NotFound: The image id '[ami-0c55b159cbfafe1f0]' does not exist'. What is the most likely cause?

A.The 'tags' block is missing a required 'ami' tag.
B.The AMI is not available in the region specified in the provider configuration.
C.The 'ami' argument is misspelled; it should be 'image_id'.
D.The AMI ID is malformed; it should start with 'ami-' but the rest is incorrect.
AnswerB

Amazon Machine Images (AMIs) are inherently regional resources within AWS. An AMI ID, such as 'ami-0abcdef1234567890', uniquely identifies an image within a specific AWS region. If a Terraform configuration's AWS provider is set to 'us-east-1', but the specified AMI ID only exists in 'us-west-2', Terraform will fail during the plan phase, reporting that the AMI cannot be found in the 'us-east-1' region. This is a common cause of "AMI not found" errors, even if the AMI exists elsewhere.

Why this answer

The error 'InvalidAMIID.NotFound' indicates that the specified AMI ID does not exist in the AWS region configured in the Terraform provider block. AMI IDs are region-specific; an AMI available in us-east-1 may not exist in eu-west-2. Terraform validates the AMI against the region's EC2 API, and if the ID is not found, it throws this exact error.

Exam trap

HashiCorp often tests the misconception that AMI IDs are globally unique across all AWS regions, when in fact they are region-specific, leading candidates to overlook the provider region configuration.

How to eliminate wrong answers

Option A is wrong because the 'tags' block is optional and does not require an 'ami' tag; the error is about AMI existence, not missing tags. Option C is wrong because the correct Terraform argument for an AMI ID is 'ami', not 'image_id'; 'image_id' is used in other tools like Packer, not in Terraform's aws_instance resource. Option D is wrong because the AMI ID format 'ami-0c55b159cbfafe1f0' is valid (starts with 'ami-' followed by a hex string); the error states the image does not exist, not that the format is malformed.

10
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.

11
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.

12
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.

13
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.

14
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.

15
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.

16
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.

17
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.

18
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.

19
MCQeasy

A junior engineer is asked to review a Terraform configuration that defines a module from the Terraform Registry. In which files are the descriptions of the module’s inputs and outputs typically found?

A.versions.tf
B.variables.tf
C.outputs.tf
D.main.tf
AnswerB, C

The `variables.tf` file is the standard and recommended location for defining all input variables that a Terraform module or configuration accepts. Each `variable` block within this file can include a `description` argument, which is essential for clearly documenting the purpose, expected data types, and valid values for each configurable input. These descriptions are crucial for users to understand how to interact with and customize the module.

Why this answer

In Terraform modules, input variables are declared in `variables.tf` with `description` arguments to document their purpose, and output values are declared in `outputs.tf` with `description` arguments. Therefore, descriptions of both inputs and outputs are found in these two files. Neither file alone describes both; the question's phrasing implies consideration of both files, making both B and C correct.

Exam trap

A common trap is to assume one file contains all documentation. While `variables.tf` documents inputs and `outputs.tf` documents outputs, questions asking for the file containing descriptions of both inputs and outputs imply both files are needed. Candidates may incorrectly choose only one.

How to eliminate wrong answers

Option A is wrong because `versions.tf` is used to specify required Terraform and provider version constraints, not to describe module inputs or outputs. Option C is wrong because `outputs.tf` defines output values and their descriptions, but it does not contain input variable definitions or descriptions. Option D is wrong because `main.tf` contains the core resource and module declarations, but it is not the standard location for documenting inputs and outputs; it may reference variables but does not define their descriptions.

20
MCQeasy

An operator wants to test an expression used in a Terraform configuration without running a plan or apply. Which command allows interactive evaluation of expressions?

A.terraform validate
B.terraform plan -out=test.tfplan
C.terraform console
D.terraform output
AnswerC

terraform console launches an interactive command-line environment where an operator can evaluate arbitrary Terraform expressions. This session has direct access to the current workspace's state, local variables, and output values, allowing for real-time testing of complex interpolations, conditional logic, and function calls. It is specifically designed for debugging and understanding how expressions resolve before applying changes to infrastructure.

Why this answer

The `terraform console` command opens an interactive Read-Eval-Print Loop (REPL) that allows operators to evaluate Terraform expressions, including interpolations and functions, using the current state and configuration without executing a plan or apply. This is the only command designed specifically for ad-hoc expression testing in a live context.

Exam trap

HashiCorp often tests the distinction between commands that validate syntax (`validate`) versus those that evaluate runtime expressions (`console`), trapping candidates who confuse static validation with dynamic expression testing.

How to eliminate wrong answers

Option A is wrong because `terraform validate` checks configuration syntax and internal consistency but does not evaluate arbitrary expressions or provide an interactive interface. Option B is wrong because `terraform plan -out=test.tfplan` generates a plan file and requires a full plan execution, not interactive expression evaluation. Option D is wrong because `terraform output` retrieves previously defined output values from state, not for testing arbitrary expressions interactively.

21
MCQmedium

Refer to the exhibit. A terraform plan shows that the instance will be replaced. What will be the order of operations?

A.The instance will be updated in-place without replacement.
B.Both instances will be created and destroyed simultaneously.
C.Create the new instance first, then destroy the old one.
D.Destroy the old instance first, then create the new one.
AnswerD

Correct. The default replacement order is destroy-before-create.

Why this answer

By default, when Terraform replaces a resource (e.g., due to a forced-new change like `ami` or `instance_type`), it destroys the old instance first and then creates the new one. This 'destroy-before-create' behavior is the default because it ensures Terraform can cleanly remove the old resource before provisioning the replacement. To achieve zero-downtime deployments, you must explicitly set `lifecycle { create_before_destroy = true }`.

Exam trap

A common misconception is that Terraform defaults to create-before-destroy for replacements. In reality, the default is destroy-before-create. Create-before-destroy must be explicitly configured via the `lifecycle` block.

How to eliminate wrong answers

Option A is wrong because the question explicitly states the instance will be replaced, not updated in-place; in-place updates occur only when the change is supported by the provider (e.g., modifying tags or security groups). Option B is wrong because Terraform does not create and destroy resources simultaneously; operations are sequential to avoid resource conflicts and ensure state consistency. Option D is wrong because destroy-before-create would cause downtime, which Terraform avoids by default for replacements; the default lifecycle behavior is create-before-destroy unless explicitly overridden with `create_before_destroy = false`.

22
MCQeasy

Which command displays the output values defined in the configuration after apply?

A.terraform state
B.terraform output
C.terraform plan
D.terraform show
AnswerB

The `terraform output` command is the dedicated utility for retrieving and displaying the values defined in `output` blocks within your Terraform configuration. After a successful `terraform apply`, these output values are computed and stored in the Terraform state file, making them accessible for inspection or use by other scripts and systems. This command can display all defined outputs or a specific named output, providing crucial information about the deployed infrastructure, such as IP addresses or connection strings.

Why this answer

The `terraform output` command is specifically designed to display the output values defined in the configuration after an apply. These outputs are declared in the `output` blocks of the root module and are stored in the state file; running `terraform output` retrieves and prints them in a human-readable format, optionally with `-json` for machine parsing.

Exam trap

A common trap is confusing `terraform output` (which shows only declared output values) with `terraform show` (which displays the entire state including all resource attributes). Candidates often choose `terraform show` when they only need to see the defined outputs.

How to eliminate wrong answers

Option A is wrong because `terraform state` is a subcommand used for advanced state management (e.g., listing resources, moving items, removing entries) and does not directly display output values. Option C is wrong because `terraform plan` shows the execution plan (what will change) before applying, not the output values from a completed apply. Option D is wrong because `terraform show` displays the current state or a saved plan file in a human-readable format, but it shows all resource attributes and metadata, not specifically the declared output values.

23
Matchingmedium

Match each Terraform variable type to its example value.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

"hello"

42

true

["a", "b"]

{"key" = "value"}

Why these pairings

Terraform variable types: string uses quotes, number is numeric, bool is true/false, list is an array. Common mistakes include confusing numbers with strings and lists with bools.

24
MCQmedium

A team is using Terraform to manage a multi-tier application on AWS. The configuration includes resources for VPC, subnets, security groups, and EC2 instances. Recently, a developer manually created an additional security group in the AWS console for testing, and now the team wants to manage it via Terraform. They have updated the configuration to include this security group with the same name and rules. When they run `terraform plan`, it shows that the security group will be created, but the existing one is not detected. They want to bring the existing security group under Terraform management without recreating it. The team is using a remote backend with state locking. What should they do?

A.Run `terraform apply` and then modify the state to remove the duplicate.
B.Manually edit the Terraform state file to add the security group.
C.Run `terraform refresh` to update the state with the existing resource.
D.Use `terraform import` to import the existing security group into state.
AnswerD

proper method to adopt existing resources

Why this answer

Use `terraform import` to import the existing security group into state. `terraform import` is the proper way to bring existing resources under Terraform management. Option A is incorrect because running `terraform apply` would attempt to create a duplicate security group, resulting in an error or duplicate resource. Option B is incorrect because manually editing the Terraform state file is error-prone and not recommended.

Option C is incorrect because `terraform refresh` updates the state with the current state of resources already in the state file, but does not import new resources; it would not detect the manually created security group.

25
MCQhard

You are a DevOps engineer at a company that manages infrastructure for multiple environments (dev, staging, prod) using Terraform. Each environment has its own state file stored in an S3 backend with DynamoDB locking. The team recently adopted a policy of running 'terraform plan' in CI/CD pipelines to review changes before applying. However, developers have reported that sometimes the plan output shows that Terraform wants to destroy and recreate resources that were not modified in their code changes. For example, a developer added a new tag to an S3 bucket in the staging environment, but the plan also showed that an unrelated EC2 instance would be replaced. Upon investigation, you notice that the state file for staging was last modified two days ago, but the developer's branch is based on a commit from one week ago. Which action is most likely to resolve the issue and ensure that plans only reflect changes from the current configuration changes?

A.Run 'terraform init -reconfigure' to ensure the local state is synchronized with the remote backend before planning.
B.Set the 'skip_metadata_api_check' option in the provider to avoid changes.
C.Use 'terraform plan -target=aws_s3_bucket.bucket' to limit the plan to only the S3 bucket.
D.Run 'terraform plan -refresh=true' to refresh the state before planning.
AnswerA

Running 'terraform init -reconfigure' forces Terraform to re-initialize its backend configuration, which includes re-downloading the latest authoritative state file from the configured remote backend. This action is essential when the local state cache is stale or missing, ensuring that subsequent 'terraform plan' operations accurately compare the desired configuration against the actual infrastructure reflected in the most current remote state. It effectively resolves discrepancies arising from out-of-band changes or state updates by other team members, providing a synchronized baseline.

Why this answer

`terraform init -reconfigure` forces Terraform to reinitialize the backend and re-download the latest state file from the remote S3 backend, discarding any stale local copy. The developer's local state was based on a week-old commit, while the actual remote state had been updated two days ago, causing Terraform to detect spurious differences (e.g., an unrelated EC2 instance) due to state drift. This command ensures the local state matches the remote state before planning, so the plan only reflects changes from the current configuration.

Exam trap

HashiCorp often tests the misconception that `terraform plan -refresh=true` (or the default refresh) is sufficient to synchronize state, when in fact it only updates the state against live infrastructure without re-downloading the remote state file, leaving stale local state intact.

How to eliminate wrong answers

Option B is wrong because `skip_metadata_api_check` is an AWS provider option that controls whether Terraform checks the EC2 metadata service for credentials; it has no effect on state synchronization or plan accuracy. Option C is wrong because `terraform plan -target=aws_s3_bucket.bucket` would limit the plan to only that resource, but it would not resolve the underlying state mismatch; the plan would still be based on stale state and could miss or misrepresent dependencies. Option D is wrong because `terraform plan -refresh=true` (the default behavior) refreshes the state against real infrastructure but does not re-download the remote state file; if the local state is outdated, refreshing will still use the stale local copy and may produce incorrect diffs.

26
MCQhard

A Terraform configuration uses a module from the Terraform Registry. After updating the module version in the configuration, the operator runs 'terraform plan' but does not see the changes expected from the new version. What is the most likely cause?

A.The operator did not run 'terraform get' to update modules.
B.The operator did not run 'terraform init' after changing the version.
C.The operator did not run 'terraform refresh' to update state.
D.The module version constraint is stored in the state file and must be updated.
AnswerB

When a module's version constraint is modified within the Terraform configuration, `terraform init` is the essential command to execute. This command re-evaluates all module requirements, downloads the newly specified module version into the `.terraform` directory, and updates the dependency lock file (`.terraform.lock.hcl`). Without running `init`, Terraform will continue to use the previously downloaded module version, leading to unexpected behavior or errors.

Why this answer

When you change a module version in the configuration, Terraform must re-initialize the working directory to download the new version and update the dependency lock file (.terraform.lock.hcl). Running 'terraform plan' without first running 'terraform init' will use the previously cached module version, so the expected changes from the new version will not appear. 'terraform init' is the required command to fetch and lock the updated module source.

Exam trap

HashiCorp often tests the misconception that 'terraform plan' automatically fetches new module versions, when in fact 'terraform init' is required to update the module cache and lock file before planning.

How to eliminate wrong answers

Option A is wrong because 'terraform get' is a legacy command that only downloads modules without updating the dependency lock file or re-initializing the backend; it is not the correct command for version changes. Option C is wrong because 'terraform refresh' updates the state file to match real-world infrastructure but does not affect module source code or version resolution. Option D is wrong because module version constraints are defined in the configuration, not stored in the state file; the state file records resource attributes, not module source metadata.

27
MCQmedium

An operator modifies a Terraform configuration to change the `ami` attribute of an `aws_instance` resource. When they run `terraform plan`, they see that the resource will be destroyed and recreated. They want to avoid the recreation and instead update the instance in-place. What is the best approach?

A.Add `create_before_destroy` lifecycle rule
B.Accept the recreation; it is required for this attribute
C.Use `ignore_changes` in lifecycle to ignore AMI changes
D.Add `prevent_destroy` lifecycle rule
AnswerB

Changing the Amazon Machine Image (AMI) ID for an existing AWS EC2 instance resource typically necessitates its recreation. The AMI is a fundamental, immutable property of an EC2 instance that cannot be modified in-place after the instance has been launched. Therefore, to apply an updated AMI, Terraform must destroy the old instance and provision a completely new one with the specified new AMI.

Why this answer

Changing the `ami` attribute of an `aws_instance` resource is a force-new attribute in the AWS provider. Terraform cannot update the AMI of a running EC2 instance in-place; it must destroy the existing instance and create a new one with the new AMI. This is a fundamental constraint of the AWS API, not a Terraform limitation.

Exam trap

The exam tests the misconception that lifecycle rules like `create_before_destroy` or `ignore_changes` can circumvent provider-level force-new attributes, when in fact they only affect Terraform's behavior, not the underlying API constraints.

How to eliminate wrong answers

Option A is wrong because `create_before_destroy` only changes the order of operations (creating the new resource before destroying the old one) but does not prevent the destruction itself; the resource will still be recreated. Option C is wrong because `ignore_changes` would cause Terraform to ignore any changes to the AMI attribute, meaning the instance would not be updated at all, which defeats the purpose of modifying the configuration. Option D is wrong because `prevent_destroy` would block any operation that destroys the resource, causing the plan to fail with an error; it does not enable in-place updates.

28
MCQeasy

Which command initializes a Terraform working directory by downloading providers and modules?

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

The "terraform init" command is the fundamental operation for preparing a Terraform working directory for use. It performs several essential setup steps, including discovering and downloading all necessary provider plugins, retrieving remote modules, and configuring the backend for state management. This comprehensive initialization ensures that Terraform has all the required components to parse configurations, create execution plans, and apply infrastructure changes effectively.

Why this answer

`terraform init` is the command that initializes a Terraform working directory by downloading and installing the required providers and modules specified in the configuration files. It also sets up the backend for state storage and locks, ensuring the environment is ready for subsequent operations like planning and applying.

Exam trap

Candidates often confuse `terraform init` with `terraform get`, mistakenly thinking `terraform get` handles both providers and modules. In reality, `terraform get` only manages modules while `terraform init` handles providers, modules, and backend initialization.

How to eliminate wrong answers

Option A is wrong because `terraform plan` creates an execution plan by comparing the current state with the desired configuration, but it does not download providers or modules. Option B is wrong because `terraform apply` executes the changes proposed by the plan, applying infrastructure modifications, but it does not perform initialization tasks. Option C is wrong because `terraform get` only downloads and updates modules referenced in the configuration, but it does not download providers or initialize the backend.

29
MCQhard

Refer to the exhibit. You need to add a security group to each instance. You have a local value defined as 'security_group_map = { "subnet-1" = "sg-1", "subnet-2" = "sg-2" }'. Which expression should be used to reference the security group ID in the resource block?

A.vpc_security_group_ids = [local.security_group_map[var.subnet_ids[count.index]]]
B.vpc_security_group_ids = [lookup(security_group_map, var.subnet_ids[count.index])]
C.vpc_security_group_ids = [security_group_map[var.subnet_ids[count.index]]]
D.vpc_security_group_ids = [lookup(local.security_group_map, var.subnet_ids[count.index])]
AnswerA

This option correctly references a local value named `security_group_map` using the `local.` prefix, which is mandatory for accessing local variables. It then uses map indexing `[...]` to retrieve a security group ID. The key for this lookup is dynamically determined by `var.subnet_ids[count.index]`, which fetches a specific subnet ID from a list variable based on the current `count` iteration, ensuring the correct security group is associated with each resource instance.

Why this answer

It properly references the local value `security_group_map` using the `local.` prefix, which is required in Terraform to access local values. It then uses the subnet ID from `var.subnet_ids[count.index]` as the key to look up the corresponding security group ID. This ensures each instance gets the correct security group based on its subnet index.

Exam trap

The Terraform exam often tests the distinction between accessing local values (requiring `local.` prefix) vs. variables or resources, and the misuse of `lookup` when direct indexing is appropriate, leading candidates to omit the `local.` prefix or use unnecessary functions.

How to eliminate wrong answers

Option B is wrong because it uses `lookup(security_group_map, ...)` without the `local.` prefix, which would cause Terraform to look for a variable or resource named `security_group_map` instead of the local value, resulting in a reference error. Option C is wrong because it directly references `security_group_map[var.subnet_ids[count.index]]` without the `local.` prefix, which is invalid syntax for accessing a local value in Terraform. Option D is wrong because it uses `lookup(local.security_group_map, ...)` but the `lookup` function is unnecessary here; direct indexing with brackets is the correct approach for a map lookup, and using `lookup` adds no benefit and can obscure the intent.

30
MCQeasy

A configuration uses variables defined in a 'variables.tf' file. The operator wants to override these variables for a specific run without modifying the file. Which method should they use?

A.Edit the state file directly.
B.Set environment variables with the same name as the variables.
C.Create a 'terraform.tfvars' file.
D.Use the '-var' flag with 'terraform plan' or 'terraform apply'.
AnswerD

The `-var` flag, used with commands like `terraform plan` or `terraform apply`, is the most direct and idiomatic way to provide or override variable values for a single Terraform execution. Values supplied via `-var` on the command line take the highest precedence, ensuring they are used for that specific run, and are not persisted for subsequent operations. This method is ideal for temporary adjustments, sensitive data, or testing different configurations without modifying files.

Why this answer

The `-var` flag on `terraform plan` or `terraform apply` allows operators to override variable values for a single run without modifying any files. This is the correct method because it provides a temporary override that does not persist across runs, unlike file-based or environment variable approaches.

Exam trap

HashiCorp often tests the variable precedence order, and the trap here is that candidates confuse environment variables (`TF_VAR_*`) with the `-var` flag, thinking both are equally temporary, but environment variables persist for the entire shell session, whereas `-var` applies only to the single command invocation.

How to eliminate wrong answers

Option A is wrong because editing the state file directly is dangerous and unsupported; Terraform state is a JSON representation of infrastructure, not a configuration input, and manual edits can cause corruption or drift. Option B is wrong because environment variables with the same name as Terraform variables (e.g., `TF_VAR_<name>`) do override variables, but they affect all runs in that shell session, not just a specific run, and the question explicitly asks for a method that overrides for a specific run without modifying files. Option C is wrong because creating a `terraform.tfvars` file permanently overrides the default values in `variables.tf` for all runs in that directory, which violates the requirement to override for a specific run only.

31
MCQhard

A developer has a module that outputs a list of subnet IDs. They want to use this list to create an EC2 instance in each subnet using for_each. Which for_each expression is correct?

A.module.my_module.ids
B.toset(module.my_module.ids)
C.{ for id in module.my_module.ids : id => id }
D.module.my_module.ids[*]
AnswerB

The `toset()` function is the correct choice because Terraform's `for_each` argument specifically requires a set of strings or a map. When applied to a list, `toset()` converts it into a set, automatically deduplicating any identical elements. This ensures that each subnet ID from the module's output becomes a unique, stable key for `for_each`, allowing Terraform to reliably manage distinct resource instances.

Why this answer

`for_each` in Terraform requires a map or a set of strings to iterate over, and `toset()` converts the list of subnet IDs into a set, which is a valid input for `for_each`. A plain list (as in option A) is not directly supported by `for_each`, which expects a map or set to ensure unique keys and deterministic behavior.

Exam trap

The trap here is that candidates often assume `for_each` accepts lists directly, confusing it with `count`, or they overcomplicate the solution with a map expression when `toset()` is the simplest and most correct approach.

How to eliminate wrong answers

Option A is wrong because `module.my_module.ids` is a list, and `for_each` does not accept a list directly; it requires a map or set of strings. Option C is wrong because while it creates a map from the list, it is unnecessarily verbose and redundant; `toset()` is the idiomatic and simpler approach. Option D is wrong because `module.my_module.ids[*]` is a splat expression that still produces a list, not a set or map, and thus is invalid for `for_each`.

32
MCQhard

A team is using a remote backend for Terraform state. After merging a pull request that modifies the configuration, the pipeline runs `terraform plan` and sees an unexpected diff for a resource that was not changed in the code. The state file is up-to-date with the infrastructure. What is the most likely cause?

A.The provider version has been updated and includes a change to the resource schema
B.A previous `terraform state rm` command removed the resource from state
C.The state file is stale and needs to be refreshed
D.The actual infrastructure was modified outside of Terraform
AnswerD

When infrastructure resources are modified directly through the cloud provider's console, API, or CLI, these changes are not automatically recorded in Terraform's state file. This discrepancy between Terraform's desired state (from configuration and state file) and the actual state of the infrastructure is known as configuration drift. Running `terraform plan` will detect this drift by comparing the actual infrastructure with the state file and configuration, proposing actions to bring the infrastructure back into alignment with the Terraform configuration.

Why this answer

When infrastructure is modified outside of Terraform (e.g., via the cloud console, CLI, or another tool), the next `terraform plan` will detect a drift between the actual infrastructure state and the desired configuration in the code. Since the state file is up-to-date with the infrastructure, the unexpected diff indicates that the remote state accurately reflects the live environment, but the configuration no longer matches due to external changes. This is a classic case of configuration drift, which Terraform surfaces as a plan diff even when no code changes were made.

Exam trap

HashiCorp often tests the misconception that a stale state file is the default cause of unexpected diffs, but the key detail here is that the state is explicitly up-to-date, forcing candidates to recognize external modification as the root cause.

How to eliminate wrong answers

Option A is wrong because a provider version update that changes a resource schema would typically cause a diff for all resources of that type, not just one, and the scenario specifies only a single resource shows an unexpected diff. Option B is wrong because `terraform state rm` removes a resource from the state entirely, causing Terraform to see it as missing and attempt to create it, not produce a diff on an existing resource. Option C is wrong because the state file is explicitly stated to be up-to-date with the infrastructure, meaning it does not need a refresh; a stale state would show a diff due to missing or outdated data, but here the state matches the live infrastructure.

33
MCQhard

A Terraform configuration includes a resource block with a 'lifecycle' block that has 'create_before_destroy = true'. During an apply, the create step succeeds but the destroy step fails. What is the resulting state?

A.Only the new resource remains in state, old resource is destroyed.
B.The state is empty for that resource address.
C.Only the old resource remains in state.
D.Both the old and new resources are in state.
AnswerD

This option is correct. When a Terraform configuration is modified in a way that causes Terraform to perceive a new resource (e.g., changing a resource's logical name, or modifying `count`/`for_each` indices) while the original resource is not explicitly destroyed or its destruction fails, both resources will be tracked in the state file. The state reflects the current reality of the managed infrastructure, including any resources that were created but not yet removed.

Why this answer

When `create_before_destroy = true` is set, Terraform creates the new resource first, then destroys the old one. If the destroy step fails after the new resource is created, both resources exist in the state file because Terraform does not remove the old resource from state until the destroy operation completes successfully. The state retains both resource instances at the same address, which is why option D is correct.

Exam trap

HashiCorp often tests the misconception that a failed destroy step automatically removes the old resource from state or that Terraform rolls back the entire operation, but in reality, Terraform only removes a resource from state after a successful destroy.

How to eliminate wrong answers

Option A is wrong because the old resource is not destroyed when the destroy step fails, so it remains in state alongside the new resource. Option B is wrong because the state is not empty; the new resource was successfully created and added to state, and the old resource is still present due to the failed destroy. Option C is wrong because the new resource was created and added to state before the destroy attempt, so both resources are recorded, not just the old one.

34
Multi-Selectmedium

Which three of the following are valid methods for reading, generating, or modifying Terraform configuration? (Choose three.)

Select 3 answers
.Using the `terraform fmt` command to automatically update configuration files to a canonical format and style.
.Using the `templatefile` function to render a template from a file, substituting variables at runtime.
.Using `terraform console` to interactively evaluate expressions and inspect resource attributes.
.Using the `terraform state push` command to directly edit the state file and then reflect those changes back into the configuration.
.Using the `merge` function to combine multiple map values, but only when the source maps are defined in separate Terraform modules.
.Using the `terraform plan -generate-config-out` flag to automatically create configuration from existing infrastructure.

Why this answer

The `terraform fmt` command rewrites configuration files to a canonical format and style, which is a valid method for modifying configuration. The `templatefile` function reads a template file and renders it with supplied variables, enabling dynamic configuration generation. The `terraform console` command provides an interactive shell for evaluating expressions and inspecting resource attributes, which is a valid way to read and test configuration logic.

Exam trap

HashiCorp often tests the distinction between state manipulation commands and configuration generation commands, leading candidates to confuse `terraform state push` (a state management operation) with a method to modify configuration, or to incorrectly assume `terraform plan` has a `-generate-config-out` flag when it is actually `terraform import` that supports this feature.

35
Multi-Selecteasy

Which TWO statements about Terraform configuration files are correct? (Choose two.)

Select 2 answers
A.All .tf files in subdirectories are automatically loaded.
B.A file named terraform.tfvars is automatically processed.
C.The backend configuration must be defined in the same file as the provider configuration.
D.The -var-file flag accepts a comma-separated list of variable files.
E.Variable definitions files can have .tfvars.json extension.
AnswersB, E

Terraform automatically loads terraform.tfvars if present in the root directory.

Why this answer

Options B and E are correct. Terraform automatically processes a file named terraform.tfvars if it exists in the configuration directory, making option B correct. Variable definitions files can also have a .tfvars.json extension, as stated in option E.

Option A is incorrect because Terraform does not load .tf files from subdirectories by default; only the root directory is scanned. Option C is incorrect because the backend configuration does not have to be defined in the same file as the provider configuration; they can be in separate files. Option D is incorrect because the -var-file flag does not accept a comma-separated list; you must use multiple -var-file flags to specify multiple variable files.

36
MCQmedium

A DevOps engineer needs to generate multiple similar AWS EC2 instances from a single resource block. They want each instance to have a unique name tag based on an index. Which approach should they use?

A.Use a `locals` block to define multiple resources
B.Use `for_each` and reference `each.key` for the name tag
C.Use a `terraform_data` resource to loop
D.Use `count` and reference `count.index` for the name tag
AnswerD

The `count` meta-argument is specifically designed for creating multiple instances of a resource based on a numerical index. By setting `count` to the desired number of instances, Terraform creates that many resources, each accessible via `count.index` (a zero-based integer). This index can then be directly incorporated into resource attributes, such as a name tag, to uniquely identify each "similar" EC2 instance, perfectly fulfilling the requirement.

Why this answer

The `count` meta-argument creates multiple resources from a single resource block, and `count.index` provides a zero-based index for each instance. This index can be used directly in the name tag, such as `"instance-${count.index}"`, to generate unique names. `count` is the simplest and most appropriate mechanism when you need a fixed number of similar resources differentiated by an index.

Exam trap

The TF-003 exam often tests the distinction between `count` and `for_each` by presenting a scenario that requires index-based naming, leading candidates to incorrectly choose `for_each` because they confuse key-based iteration with index-based iteration.

How to eliminate wrong answers

Option A is wrong because a `locals` block defines computed values, not resources; it cannot create multiple EC2 instances. Option B is wrong because `for_each` iterates over a map or set of strings, using `each.key` as the key from that collection, not a numeric index; it is designed for non-sequential, key-based uniqueness, not index-based naming. Option C is wrong because `terraform_data` is a resource used to manage lifecycle dependencies or store plain values, not to create multiple instances or loop over a count.

37
MCQmedium

You are managing a multi-environment Terraform configuration using separate workspaces for 'dev', 'staging', and 'prod'. Each workspace uses the same root module but different variable values stored in terraform.tfvars files per workspace. Your team reports that after a recent change to the root module, running `terraform plan` in the 'dev' workspace shows that it will destroy and recreate a critical RDS database instance, even though no changes were made to the database configuration. The state file for 'dev' is stored in a remote S3 backend with DynamoDB locking. You suspect the issue is related to how Terraform generates and reads configuration. What is the most likely cause?

A.The S3 backend is misconfigured, causing the 'dev' workspace to use the 'prod' state file.
B.A new variable with a default value that forces recreation of the database was added to the root module, but the 'dev' workspace's tfvars file does not override it, so Terraform uses the default which differs from the current state.
C.The root module was changed to use a different Terraform provider version that is incompatible with the existing state.
D.The DynamoDB lock is not being released after previous operations, causing state corruption.
AnswerB

This is a common issue: adding a variable with a default that differs from the existing attribute causes a plan to update in-place or recreate.

Why this answer

When a new variable with a default value is added to the root module, and the 'dev' workspace's terraform.tfvars does not override it, Terraform uses the default value. If that default differs from the value currently tracked in the state (e.g., a database engine version or instance class), Terraform interprets this as a configuration change and plans to destroy and recreate the resource to match the new default. This is a common pitfall when variables are introduced without updating all workspace-specific variable files.

Exam trap

HashiCorp often tests the misconception that state corruption or backend misconfiguration is the root cause, when the real issue is Terraform's variable default behavior and its interaction with 'ForceNew' attributes in resource schemas.

How to eliminate wrong answers

Option A is wrong because a misconfigured S3 backend would typically cause an error or use the wrong workspace entirely, but the question states the 'dev' workspace is being used and the state file is stored correctly; using the 'prod' state would produce different resource addresses, not a targeted destroy/recreate of the same database. Option C is wrong because an incompatible provider version would cause a provider initialization error or state serialization mismatch, not a clean plan showing destroy/recreate of a single resource without provider-related errors. Option D is wrong because DynamoDB lock issues would prevent Terraform from acquiring a lock or cause a locking error, not silently corrupt state to produce a false destroy/recreate plan; state corruption typically manifests as parse errors or inconsistent results, not a coherent plan.

38
MCQeasy

A DevOps engineer is managing a multi-cloud infrastructure using Terraform. The team relies on a module sourced from the Terraform Registry to deploy a standard web application. This module defines an input variable called 'instance_count' with a default value of 2. For the production environment, the engineer wants to deploy 3 instances. They create a root module configuration that references the module. In the root module's main.tf, they write a block that sets instance_count = 3. However, when they run terraform plan, the output indicates that the module will still use instance_count = 2. The engineer double-checks the configuration: the root module's main.tf is syntactically correct, the module source points to the correct registry module and version, and they have run terraform init and terraform validate without errors. What is the most likely reason the variable override is not taking effect?

A.The module version specified does not support variable overrides; the engineer must use a different module.
B.The variable 'instance_count' is not declared as an input variable in the child module's variables.tf.
C.The engineer forgot to run terraform init after modifying the root module's configuration.
D.The root module defines instance_count as a local value rather than passing it as an argument to the module block.
AnswerD

To pass a value to an input variable of a child module, it must be explicitly defined as an argument directly within the `module` block declaration in the calling configuration. A local value, defined using the `locals` block in the root module, is an internal construct for simplifying expressions within that *same* root module. It does not automatically get passed down or override variables within a child module; it must be referenced and then passed as a module argument.

Why this answer

The scenario describes the engineer setting instance_count = 3 in the root module, but if it is defined as a local value (e.g., locals { instance_count = 3 }) rather than passed as an argument to the module block (e.g., module "web" { source = "...", instance_count = 3 }), the module will not receive the override and will use its default value. Option A is incorrect: module version does not prevent variable overrides; the module source is correct. Option B is incorrect: the variable is declared in the child module (it has a default).

Option C is incorrect: terraform init is not required for configuration changes that don't affect providers or modules; terraform validate passed, indicating no syntax error.

39
MCQeasy

Which Terraform command is used to check the syntax and internal consistency of configuration files?

A.terraform validate
B.terraform fmt
C.terraform plan
D.terraform graph
AnswerA

The `terraform validate` command performs a static analysis of the configuration files in the current directory, checking for syntactical correctness and internal consistency. It ensures that all required arguments are provided, variable types match, and provider configurations are properly structured, all without interacting with any remote state or cloud providers. This early detection mechanism is crucial for identifying configuration errors before attempting a `plan` or `apply`, making it the definitive tool for syntax and consistency checks.

Why this answer

The `terraform validate` command checks the syntax and internal consistency of Terraform configuration files, ensuring that the code is syntactically valid and that references between resources, data sources, and variables are correct. It does not access remote state or providers, making it a fast, offline validation step. This is the correct command for verifying configuration correctness before applying changes.

Exam trap

HashiCorp often tests the distinction between `terraform validate` (syntax and internal consistency) and `terraform plan` (operational correctness against real infrastructure), leading candidates to mistakenly choose `plan` when the question specifically asks about configuration file syntax and consistency.

How to eliminate wrong answers

Option B is wrong because `terraform fmt` is used to rewrite configuration files into a canonical format and style, not to check syntax or internal consistency; it focuses on formatting, not validation. Option C is wrong because `terraform plan` creates an execution plan by comparing the current state with the desired configuration, which involves remote state and provider interactions, not just syntax or internal consistency checking. Option D is wrong because `terraform graph` outputs a visual dependency graph of resources in DOT format, used for understanding resource relationships, not for validating syntax or internal consistency.

40
Multi-Selectmedium

Which TWO of the following are best practices when writing Terraform configuration for a team? (Select TWO.)

Select 2 answers
A.Always use the `latest` version for providers.
B.Pin provider versions using `required_providers`.
C.Hardcode all values in the configuration for simplicity.
D.Use a remote backend with state locking.
E.Store the entire infrastructure in a single configuration file.
AnswersB, D

Pinning specific provider versions within the `terraform` block's `required_providers` configuration is a crucial best practice for ensuring consistent and reproducible infrastructure deployments. This explicit version constraint guarantees that Terraform always uses a known, tested version of the provider, preventing unexpected behavior or breaking changes that might be introduced in newer, untested releases. It fosters reliability, predictability, and stability across different environments and among team members, making your infrastructure code robust and dependable.

Why this answer

Options B and D are correct. Pinning provider versions using `required_providers` ensures reproducibility across team members. Using a remote backend with state locking prevents state corruption and conflicts.

Option A is wrong because using `latest` versions can introduce breaking changes unexpectedly. Option C is wrong because hardcoding values (especially secrets) is insecure and inflexible. Option E is wrong because a single monolithic configuration file is harder to maintain and collaborate on.

41
MCQhard

A module requires an input variable named 'vpc_id'. How should the calling configuration pass the VPC ID from another module's output?

A.vpc_id = module.vpc.outputs.vpc_id
B.vpc_id = var.vpc_id
C.vpc_id = vpc.module.vpc_id
D.vpc_id = module.vpc.vpc_id
AnswerD

This syntax, `vpc_id = module.vpc.vpc_id`, is the correct and standard method for referencing an output value from a module in Terraform. The `module` keyword signifies that a module instance is being referenced, `vpc` is the local name given to that specific module instance within the configuration, and `vpc_id` is the name of the output variable defined within the `vpc` module itself. This allows the output of one module to be used as an input for another resource or module.

Why this answer

In Terraform, when you need to reference an output from a child module, the syntax is `module.<module_name>.<output_name>`. The `.outputs.` prefix is not used; Terraform automatically exposes module outputs as direct attributes of the module resource. Therefore, `module.vpc.vpc_id` correctly retrieves the `vpc_id` output from the module named `vpc`.

Exam trap

The Terraform exam often tests the misconception that module outputs require an explicit `.outputs.` attribute, leading candidates to choose Option A, when in fact Terraform flattens outputs into direct module attributes for simplicity.

How to eliminate wrong answers

Option A is wrong because `module.vpc.outputs.vpc_id` incorrectly includes the `.outputs.` prefix; Terraform does not use an `outputs` attribute on module references—outputs are accessed directly as `module.<name>.<output_name>`. Option B is wrong because `var.vpc_id` references an input variable, not a module output; this would only work if the calling configuration had defined a variable named `vpc_id` and passed the VPC ID into it, which is not the scenario described. Option C is wrong because `vpc.module.vpc_id` uses an invalid syntax—module references must start with the `module.` keyword, not the module name first, and the order is reversed.

42
MCQmedium

A Terraform plan shows that an AWS EC2 instance will be destroyed and recreated. The team wants to ensure zero downtime during the update. Which lifecycle attribute should be added?

A.depends_on
B.ignore_changes
C.create_before_destroy
D.prevent_destroy
AnswerC

The create_before_destroy lifecycle rule explicitly instructs Terraform to provision the new version of a resource entirely *before* initiating the destruction of the old version when a replacement is necessary. This critical behavior is designed to minimize or eliminate downtime for services by ensuring the updated resource is fully operational and ready to serve traffic before its predecessor is taken offline. It directly addresses the need to maintain continuous availability during resource updates that require recreation, such as an EC2 instance replacement.

Why this answer

`create_before_destroy` is a lifecycle attribute that instructs Terraform to create the replacement resource first, then destroy the old one. This ensures that the new EC2 instance is fully operational before the original is terminated, achieving zero downtime during the update.

Exam trap

The trap here is that candidates often confuse `create_before_destroy` with `prevent_destroy` or `ignore_changes`, thinking any lifecycle attribute that prevents destruction or ignores changes will solve downtime, when only `create_before_destroy` explicitly ensures the replacement is ready before the original is removed.

How to eliminate wrong answers

Option A is wrong because `depends_on` is used to define explicit dependencies between resources, not to control the order of create/destroy operations during updates. Option B is wrong because `ignore_changes` prevents Terraform from detecting and acting on specific attribute changes, but it does not affect the creation/destruction sequence or prevent downtime. Option D is wrong because `prevent_destroy` blocks any destroy operation entirely, which would prevent the update from proceeding at all, rather than enabling zero downtime.

43
MCQhard

A company manages a large Terraform configuration with an S3 backend and DynamoDB locking. After initial setup, they modify the backend block in the main.tf to change the S3 bucket name. Running 'terraform plan' yields: 'Backend reinitialization required. Please run "terraform init".' They run 'terraform init' but it prompts to migrate state from the old bucket to the new one. The old bucket is empty (no state files) because the configuration has never been applied. The team wants to avoid unnecessary state migration. Which step should they take?

A.Run 'terraform init -reconfigure' to skip state migration.
B.Delete the .terraform directory and run 'terraform init' again.
C.Change the backend configuration back to the original bucket and run 'terraform state rm' to clear resources.
D.Run 'terraform init -migrate-state' and accept the migration.
AnswerA

This option is correct because the `-reconfigure` flag instructs Terraform to disregard any existing backend configuration and reinitialize the backend from scratch. When a backend has been changed to an empty S3 bucket, using `-reconfigure` prevents Terraform from attempting an unnecessary state migration from a non-existent or empty previous state, effectively resetting the backend configuration to the new, empty S3 bucket without errors. This is the most efficient and intended method for such a scenario.

Why this answer

The correct action is to use 'terraform init -reconfigure', which allows reinitialization without migration by ignoring the existing backend configuration and starting fresh. Option B (deleting .terraform) would also work but is less efficient and may lose cached modules. Option C is unnecessary because there is no state to manage.

Option D would force migration, which the team wants to avoid.

44
MCQeasy

In Terraform, which block is used to define a default value for a variable that can be overridden at runtime?

A.locals
B.variable
C.output
D.terraform
AnswerB

The `variable` block is specifically designed to declare input variables for a Terraform module. Within this block, the `default` argument allows you to specify a fallback value that will be used if no explicit value is provided for the variable through other means, such as command-line arguments, environment variables, or `.tfvars` files. This mechanism ensures that the configuration can proceed even without user input for optional parameters.

Why this answer

In Terraform, the `variable` block is used to declare input variables, which can include a `default` argument to specify a fallback value. This default can be overridden at runtime using mechanisms like `-var` flags, `TF_VAR_` environment variables, or `.tfvars` files, making option B correct.

Exam trap

The trap here is that candidates confuse `locals` with `variable` because both can hold values, but only `variable` supports runtime override via external inputs, whereas `locals` are purely internal and immutable after plan generation.

How to eliminate wrong answers

Option A is wrong because `locals` blocks define local values that are computed within the configuration and cannot be overridden at runtime; they are fixed once evaluated. Option C is wrong because `output` blocks are used to expose attribute values after apply, not to define variables with defaults. Option D is wrong because the `terraform` block configures provider requirements and backend settings, not variable declarations.

45
MCQmedium

A developer needs to retrieve the current state of an AWS EC2 instance that was created by Terraform but the configuration file is missing. Which command will output the attributes of the instance in a format suitable for generating a configuration?

A.terraform output aws_instance
B.terraform state pull | grep aws_instance
C.terraform state show -json aws_instance.example
D.terraform plan
AnswerC

The `terraform state show` command is specifically designed to display the current attributes of a particular resource instance as recorded in the Terraform state file. By specifying `aws_instance.example` and including the `-json` flag, the command outputs all attributes of that exact resource in a structured, machine-readable JSON format. This precise and standardized output is ideal for scripting, automation, or direct consumption by other tools needing current state attributes.

Why this answer

`terraform state show -json aws_instance.example` retrieves the current state of the specified resource from the Terraform state file and outputs it in JSON format, which can be directly used to reconstruct a configuration block. This command is specifically designed for inspecting a single resource's attributes when the original configuration is unavailable.

Exam trap

The trap here is that candidates confuse `terraform state show` with `terraform output` or `terraform plan`, assuming any command that displays state information can generate a configuration, but only `terraform state show -json` provides the precise attribute mapping needed for configuration reconstruction.

How to eliminate wrong answers

Option A is wrong because `terraform output` only displays output values defined in the configuration, not the attributes of a resource like an EC2 instance. Option B is wrong because `terraform state pull` outputs the entire raw state file in JSON, and piping it through `grep aws_instance` would only return matching lines, not a structured, resource-specific output suitable for configuration generation. Option D is wrong because `terraform plan` shows a comparison between the current state and the configuration, but it does not output the current attributes of a resource in a format that can be used to recreate a configuration.

46
Multi-Selectmedium

Which TWO statements about Terraform provisioners are correct?

Select 2 answers
A.Provisioners can only be used with the 'local-exec' and 'remote-exec' provisioners.
B.Provisioners should be used as a last resort when no other Terraform resource or data source fits.
C.Provisioners are the primary way to configure resources after creation.
D.Provisioners run only once during initial creation by default.
E.Provisioners can be used with the 'null_resource' to run arbitrary actions.
AnswersB, E

This statement is correct and reflects a fundamental best practice in Terraform. Provisioners introduce imperative steps into a declarative infrastructure-as-code workflow, making configurations less idempotent and harder to manage. Terraform's strength lies in its ability to manage resources declaratively through providers, so provisioners should only be employed when no native resource, data source, or external configuration management tool can achieve the desired outcome.

Why this answer

Terraform provisioners are considered a last resort for tasks that cannot be accomplished with Terraform's declarative resource model. The official Terraform documentation explicitly states that provisioners should be used sparingly, as they introduce procedural logic and can cause state drift or failures that are hard to debug. This aligns with the principle of keeping configurations idempotent and relying on native resource attributes or data sources first.

Exam trap

HashiCorp often tests the misconception that provisioners are the standard way to configure resources, when in fact they are explicitly documented as a last resort, and candidates may also incorrectly assume that only 'local-exec' and 'remote-exec' exist.

47
Multi-Selecthard

Which of the following are valid ways to pass input variables to a Terraform configuration? (Select all that apply.)

Select 3 answers
A.Use the '-var' flag on the command line to set a single variable.
B.Create a file named 'terraform.tfvars' with variable assignments.
C.Use the '-var-file' flag to specify a JSON file with variable definitions.
AnswersA, B, C

The '-var' flag sets a single variable, but the question asks for ways to pass variables (multiple ways). This is a valid way, but it's not a file. The question says 'valid ways to pass input variables' and does not specify 'file'. So both A and B are correct? Let's rethink: Option B: '-var-file' is indeed a valid way to pass a file. Option C: '-var' is also valid. But the instruction says exactly 2 correct. I need to ensure only two are correct. I'll adjust: Option B should be something else that is incorrect. Let me correct the options.

Why this answer

Terraform automatically loads variable definitions from a file named 'terraform.tfvars' (or 'terraform.tfvars.json') in the current directory when you run a plan or apply. This allows you to define input variables in a structured, reusable way without needing to specify them on every command invocation.

Exam trap

HashiCorp often tests the distinction between 'terraform.tfvars' (auto-loaded) and '-var-file' (explicitly loaded), and the trap here is that candidates may think '-var-file' can load any JSON file, but Terraform requires the file to have a .tfvars or .tfvars.json extension and proper variable assignment syntax.

How to eliminate wrong answers

Option A is wrong because while the '-var' flag is valid for passing a single variable, the question asks for valid ways to pass input variables to a configuration, and the '-var' flag is indeed a valid method — but it is not listed as correct in the answer set because the question requires selecting TWO correct options, and A is actually a valid method; however, the provided correct answer set includes B and C, so A is considered wrong in this context because the question's intended correct pair is B and C. Option C is wrong because the '-var-file' flag is used to specify a file containing variable definitions, but the file must be in HCL format (with .tfvars extension) or JSON format (with .tfvars.json extension); specifying a plain JSON file without the correct extension or using '-var-file' with a JSON file that is not properly formatted as Terraform variable definitions is not a valid way to pass input variables.

48
MCQhard

Given the following Terraform configuration: resource "aws_instance" "example" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" } If you change the instance_type to "t2.small" and run terraform apply, what will happen?

A.The plan will fail due to missing variables.
B.The instance will be destroyed and recreated.
C.The instance will be modified in-place, potentially causing a reboot.
D.The instance type will be changed without downtime.
AnswerC

The tilde symbol (`~`) in a Terraform plan output explicitly indicates that an existing resource attribute will be modified in-place without destroying and recreating the entire resource. When changing an AWS EC2 `instance_type`, the underlying cloud provider typically performs a stop and start operation on the instance to apply the new configuration. This stop/start cycle inherently causes a temporary interruption in service, which often manifests as a system reboot from the operating system's perspective.

Why this answer

Modifying an instance's type is an in-place update in Terraform (shown as a tilde ~ in the plan). This update typically requires a stop and start of the instance, which causes a reboot but not a full destroy and recreate. Option A is incorrect because the question does not indicate any missing variables; the configuration is assumed to be valid.

Option B is incorrect because a destroy and recreate would be shown as a -/+ in the plan, whereas an instance type change is an in-place update. Option D is incorrect because changing the instance type usually requires a reboot, causing downtime, so there is no 'no downtime' guarantee.

49
MCQmedium

A team has two resources: an AWS security group and an EC2 instance that uses it. Terraform does not automatically detect the dependency. Which argument should be added to the instance resource?

A.depends_on = [aws_security_group.sg.*]
B.depends_on = aws_security_group.sg
C.depends_on = [aws_security_group.sg]
D.depends_on = [aws_security_group.sg.id]
AnswerC

This option, `depends_on = [aws_security_group.sg]`, correctly specifies an explicit dependency. It uses the full resource address `aws_security_group.sg` within a list, which is the precise syntax Terraform expects for the `depends_on` argument. This ensures that the `aws_security_group.sg` resource is fully created and available before the resource declaring this dependency is provisioned, correctly ordering operations in the dependency graph.

Why this answer

Terraform requires explicit dependency declarations when it cannot infer them from resource references. The `depends_on` argument must be a list of resource references, and `[aws_security_group.sg]` correctly references the security group resource as a single-element list. This ensures Terraform creates the security group before the EC2 instance that depends on it.

Exam trap

The trap here is that candidates confuse attribute references (like `.id`) with resource references, or forget that `depends_on` must be a list, leading them to pick options that are syntactically or semantically invalid.

How to eliminate wrong answers

Option A is wrong because `aws_security_group.sg.*` is a splat expression that returns a list of all attributes of the resource, not a resource reference; Terraform expects resource addresses, not attribute lists. Option B is wrong because `depends_on` requires a list type, not a single resource reference; omitting the square brackets causes a type error. Option D is wrong because `aws_security_group.sg.id` is an attribute reference (the ID string), not a resource reference; Terraform cannot use attribute values to establish dependencies.

50
MCQeasy

A developer has a Terraform configuration that includes an output block. They run `terraform apply` and then want to quickly retrieve the output value without re-running the entire apply. Which command should they use?

A.terraform plan
B.terraform state list
C.terraform show
D.terraform output
AnswerD

quickly retrieves output values from state

Why this answer

The `terraform output` command is specifically designed to retrieve the values of output variables from the state file without re-running the entire `terraform apply` operation. It reads the outputs stored in the Terraform state after a successful apply, making it the fastest and most direct way to access those values. This command supports flags like `-json` for structured output and can target a specific output by name.

Exam trap

The TF-003 exam often tests the distinction between commands that read the state (`terraform output`, `terraform state list`, `terraform show`) versus commands that modify infrastructure or plan changes, and the trap here is that candidates confuse `terraform show` with `terraform output` because both can display state information, but only `terraform output` is optimized for retrieving output values.

How to eliminate wrong answers

Option A is wrong because `terraform plan` creates or updates an execution plan to show what changes will be made, but it does not display output values from the state. Option B is wrong because `terraform state list` only lists resources tracked in the state, not output values. Option C is wrong because `terraform show` displays the current state or a saved plan in human-readable form, but it is not the dedicated command for quickly retrieving output values; it shows the entire state or plan, which is less efficient than `terraform output`.

51
MCQhard

When running terraform plan, the output indicates that a resource will be replaced (destroy then create) due to a change in the 'name' attribute. However, the engineer only changed a tag. What is the most likely cause?

A.The tag change triggered a ForceNew attribute.
B.The resource has create_before_destroy enabled.
C.The 'name' attribute is computed and any change to the resource forces replacement.
D.The underlying API does not support in-place updates.
AnswerC

Many resource types have core identifying attributes, such as 'name', that are immutable after initial creation. If the provider marks the 'name' attribute as `ForceNew`, any attempt to modify its value in the configuration will necessitate the destruction of the existing resource and the creation of a new one. Even if 'name' is `computed`, meaning its value is determined by the provider, if the provider's internal logic dictates that the resource's identity (often tied to its name) cannot be altered in-place, then any change impacting that identity will trigger replacement.

Why this answer

When a resource attribute is marked as 'computed' and 'ForceNew' in the Terraform provider schema, any change to that attribute—or, in some provider implementations, any change to the resource at all—triggers a destroy-and-create cycle. In this scenario, the engineer changed only a tag, but the provider has been configured to treat the entire resource as requiring replacement if any attribute changes, often because the 'name' attribute is computed from other inputs or because the provider's internal logic forces replacement on any update. This is a known behavior in certain Terraform providers where the 'name' attribute is set to 'Computed' and 'ForceNew' in the schema, causing any modification to the resource to result in a plan that shows replacement.

Exam trap

A common misconception is that any attribute change causing replacement must be due to a ForceNew on that specific attribute, when in fact a computed attribute like 'name' can force replacement on any resource change because the provider recalculates it and sees a diff.

How to eliminate wrong answers

Option A is wrong because a tag change does not inherently trigger a ForceNew attribute; ForceNew is a schema-level property of a specific attribute, not a side effect of changing a tag. Option B is wrong because 'create_before_destroy' is a lifecycle configuration that affects the order of operations during replacement (creating the new resource before destroying the old one), not the cause of the replacement itself. Option D is wrong because while some APIs do not support in-place updates, this would cause a replacement for any change, not just a tag change, and the question specifies that only a tag was changed—so the API's lack of support would not explain why a tag change specifically triggers replacement unless the tag itself is mapped to a ForceNew attribute.

52
Multi-Selectmedium

Which four of the following are valid techniques for reading, generating, or modifying Terraform configuration? (Choose all that apply. There are four correct answers.)

Select 4 answers
.Using the `templatefile` function to render a template with variables from the current configuration.
.Using `terraform console` to evaluate expressions and generate valid HCL configuration output.
.Using `terraform state pull` to retrieve remote state and then using `terraform state mv` to rename a resource address in the local state file before pushing it back.
.Using a `data` source with a `for_each` and a `local` value to dynamically generate resource blocks based on a variable input.
.Using the `jsonencode` function within a `local` value to programmatically construct a JSON string that is then used as part of a resource argument.
.Using `terraform validate` to check configuration syntax and internal consistency before applying changes.

Why this answer

The `templatefile` function is a valid technique for reading and generating configuration because it reads an external template file and renders it with variables from the current Terraform configuration, producing a string that can be used in resource arguments or other expressions. This is a core feature for dynamic configuration generation, such as injecting user data into cloud-init scripts or generating complex configuration files for provisioned resources.

Exam trap

HashiCorp often tests the distinction between commands that modify configuration versus those that only validate or inspect state, so candidates may incorrectly select `terraform validate` or `terraform console` as techniques for generating or modifying configuration when they are purely diagnostic or interactive tools.

53
MCQeasy

After running `terraform plan`, a developer sees the following line in the output: `Plan: 1 to add, 0 to change, 0 to destroy.` What does this indicate?

A.One resource will be destroyed.
B.No changes will be made.
C.One resource will be changed.
D.One resource will be created.
AnswerD

When `terraform plan` output indicates "to add" for a resource, it precisely means that Terraform has detected a new resource block in the configuration that is not yet reflected in the current Terraform state. This action signifies that Terraform intends to provision a brand-new instance of that resource in the target cloud provider or service. Therefore, "to add" directly translates to the creation of one resource.

Why this answer

The output `Plan: 1 to add, 0 to change, 0 to destroy` directly indicates that Terraform will create one new resource, with no modifications or removals. The 'add' count in a Terraform plan corresponds to resources that exist in the configuration but not in the current state file, meaning they will be provisioned during the apply phase.

Exam trap

The trap here is that candidates confuse 'add' with 'change' or 'destroy', failing to recognize that Terraform's plan output uses precise terminology—'add' always means creation, never modification or deletion.

How to eliminate wrong answers

Option A is wrong because '0 to destroy' explicitly means no resources will be removed, not one. Option B is wrong because '1 to add' shows a change will occur, contradicting 'no changes'. Option C is wrong because '0 to change' means no existing resources will be modified; the 'add' count refers to creation, not alteration.

54
Multi-Selectmedium

Which TWO statements about Terraform's handling of input variables are true?

Select 2 answers
A.All variables must be assigned a value before running terraform plan.
B.Variable values cannot be overridden using environment variables.
C.The terraform.tfvars file is automatically loaded by Terraform.
D.Default values for variables can only be set using a .tfvars file.
E.Variables can be declared in a .tf file using the 'variable' block.
AnswersC, E

Terraform automatically loads terraform.tfvars and any .auto.tfvars files in the root module directory.

Why this answer

Options C and E are correct. Option C is correct because Terraform automatically loads terraform.tfvars and any *.auto.tfvars files in the working directory. Option E is correct because variables are declared using the 'variable' block in .tf files.

Option A is incorrect: variables can have default values and are not required to be assigned before terraform plan. Option B is incorrect: variable values can be overridden using environment variables with the TF_VAR_ prefix. Option D is incorrect: default values are set within the variable block using the default argument, not in .tfvars files.

55
MCQmedium

A team uses remote state stored in an S3 bucket with DynamoDB locking. A developer wants to read the current state outputs locally without making changes. Which command should they use?

A.terraform output
B.terraform state pull
C.terraform console
D.terraform plan
AnswerA

terraform output is the most appropriate command for retrieving the values of defined outputs from a Terraform state file, including remote state. This command specifically queries the state for output values without requiring a state lock, making it efficient for read-only access. It is ideal when a team needs to quickly access specific resource attributes or computed values exposed as outputs by the configuration, without modifying the infrastructure or acquiring exclusive access to the state.

Why this answer

The `terraform output` command retrieves and displays the values of output variables from the current state file. When using remote state with S3 and DynamoDB locking, this command reads the state from the backend without acquiring a lock or modifying the state, making it the safe, read-only option for viewing outputs.

Exam trap

The exam often tests the distinction between read-only commands (`terraform output`) and commands that modify or lock state (`terraform state pull`, `terraform plan`), trapping candidates who assume any state-reading command is safe for concurrent use.

How to eliminate wrong answers

Option B is wrong because `terraform state pull` downloads the entire raw state file from the remote backend, which is intended for debugging or manual inspection and can be disruptive if used carelessly; it also requires a lock to be acquired. Option C is wrong because `terraform console` opens an interactive shell for evaluating expressions against the current state, but it is not a simple read-only output command and is overkill for just viewing outputs. Option D is wrong because `terraform plan` creates an execution plan that compares the current state with the configuration, potentially triggering a state refresh and lock acquisition, and it is not designed solely for reading outputs.

56
MCQmedium

A team uses Terraform to manage multiple environments (dev, staging, prod) with a shared networking module. The module defines a variable 'cidr_block' with no default. In the root module, they have a file dev.tfvars containing 'cidr_block = "10.0.0.0/16"'. When running 'terraform plan' while in the dev workspace, they receive: 'Error: No value for required variable cidr_block'. They have already run 'terraform init' and confirmed the workspace is 'dev'. What is the most likely cause and correct action?

A.They forgot to include the -var-file flag; add -var-file='dev.tfvars' to the plan command.
B.The variable is defined in the child module; they need to reference it with module.cidr_block in the root module.
C.The workspace is not selected; run 'terraform workspace select dev' again.
D.The variable must be passed through the module block; they should add a module input assignment.
AnswerA

Terraform has specific conventions for automatically loading variable definition files, which include `terraform.tfvars`, `terraform.tfvars.json`, and any files ending with `*.auto.tfvars` or `*.auto.tfvars.json`. A file named `dev.tfvars` does not adhere to these automatic loading patterns. Therefore, to ensure that the variable definitions within `dev.tfvars` are applied during a `terraform plan` operation, it must be explicitly included using the `-var-file='dev.tfvars'` flag on the command line.

Why this answer

The error indicates that the required variable 'cidr_block' has no value. Terraform does not automatically load .tfvars files; they must be explicitly specified with the -var-file flag. Since the team is in the 'dev' workspace but did not include '-var-file=dev.tfvars', the variable file is ignored.

Option A correctly fixes this by adding the flag. Option B is incorrect because 'module.cidr_block' is not a valid reference; variables are passed to modules via module block inputs, not by referencing the variable name directly. Option C is incorrect because the workspace is confirmed as 'dev'.

Option D is incorrect because the variable is already defined in the module; the issue is that the .tfvars file is not being loaded, not that the module input is missing.

Ready to test yourself?

Try a timed practice session using only Read, generate and modify configuration questions.