CCNA Read, generate and modify configuration Questions

68 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

Data sources allow reading outputs from remote state.

Why this answer

Option C is correct because 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

Outputs are meant to show values after apply.

Why this answer

Correct A: Output blocks display values to the user after apply. They do not set variables, create records, or store files by default.

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 can be used in metap arguments like count and for_each.

Why this answer

B is correct because data sources fetch external info. D is correct because they can be used with count/for_each. A is false (they read, not create), C is false (they are read during plan), E is false (they can be used in modules).

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

The map key is part of the resource address; changing it causes destroy+create.

Why this answer

Option D is correct: changing the map key results in destruction of the old subnet and creation of a new one because for_each uses keys as resource addresses. Option A is wrong because the key change is not an in-place update. Option B is wrong because it only shows deletion, not creation.

Option C is wrong because it suggests no changes.

5
Multi-Selecteasy

Which TWO of the following are valid ways to reference a value from a Terraform configuration?

Select 2 answers
A.var.environment
B.local.example.value
C.module.example.arn
D.provider.aws.region
E.aws_instance.example.id
AnswersA, E

Correct syntax for variable.

Why this answer

Option A is correct because `var.environment` is the standard syntax to reference an input variable defined in a Terraform configuration. Input variables are declared with a `variable` block and accessed using the `var.` prefix, making this a valid reference within any Terraform configuration file.

Exam trap

HashiCorp often tests the distinction between valid reference namespaces (var, local, module, data) and invalid ones (provider, resource attributes without proper syntax), trapping candidates who confuse provider configuration with data sources or resource references.

6
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

This is the proper Terraform command to release a lock.

Why this answer

Option D is correct because 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.

7
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

ignores changes to versioning attribute

Why this answer

Option C is correct because setting `ignore_changes` to the versioning block will ignore changes to versioning in the configuration, preserving the current setting. Option A is wrong because `create_before_destroy` is for ordering during recreation. Option B is wrong because `prevent_destroy` prevents deletion, not changes to attributes.

Option D is wrong because `replace_triggered_by` triggers replacement based on another resource.

8
MCQeasy

A startup uses Terraform to manage their cloud infrastructure. They have a single configuration file that defines an AWS EC2 instance. They want to add an Elastic IP (EIP) and associate it with the instance. The engineer modifies the configuration to add an `aws_eip` resource and references the instance ID. They run `terraform plan` and it shows that the EIP will be created. However, when they run `terraform apply`, they get an error: "Error: Error associating EIP: ... The instance ID 'i-1234567890abcdef0' does not exist." The instance was created successfully in a previous apply. What is the most likely cause?

A.The Terraform state file was lost or corrupted, so the instance is not in state.
B.The `aws_eip` resource is referencing the wrong instance attribute.
C.The instance type has changed causing a new instance to be created.
D.The instance was terminated manually outside Terraform.
AnswerA

state loss means Terraform doesn't know about the instance

Why this answer

Option B is correct because if the state was lost or corrupted, Terraform would think the instance needs to be created, but the error indicates the ID doesn't exist, which could happen if the state doesn't match reality. Option A is wrong because the instance exists. Option C is wrong because the configuration references the instance ID from the resource attribute.

Option D is wrong because the instance type is not changed.

9
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

overrides the default

Why this answer

Option A is correct because the default can be overridden by setting the variable in a `terraform.tfvars` file or via environment variable `TF_VAR_instance_type`. Option B is wrong because the default is read from the variable declaration. Option C is wrong because variable is set, not read from state.

Option D is wrong because the instance type is a variable, not a resource attribute change.

10
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

Valid: bool type with bool default.

Why this answer

A, B, D are valid. C is invalid because default is a string for number type. E is invalid because default is a string for list type.

11
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

AMI IDs are unique per region; the AMI may exist in another region.

Why this answer

Option B is correct because 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.

12
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

Terraform cannot track provisioner-side effects.

Why this answer

B and E require depends_on because Terraform cannot detect these dependencies. A, C, D typically create implicit dependencies.

13
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

The plan will show +3 resources (for indices 2,3,4) and ~0 changes for indices 0,1.

Why this answer

Option A is correct because increasing count adds three new resources while leaving existing ones unchanged. Option B is wrong because it incorrectly predicts deletion and recreation. Option C is wrong because it suggests in-place update, but count changes add/remove resources.

Option D is wrong because it wrongly says only one new resource.

14
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

The 'version' argument in a module block pins the module to a specific version.

Why this answer

Option B is correct because 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.

15
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

shows details of a resource in state

Why this answer

Options B and C are correct. `terraform state list` lists resources, `terraform state show` shows details. Option A is wrong because `terraform plan` does not read state; it plans changes. Option D is wrong because `terraform output` shows outputs, not full state.

Option E is wrong because `terraform validate` validates syntax.

16
Multi-Selecthard

Which THREE of the following are valid ways to modify a Terraform configuration to rename a resource without destroying and recreating it? (Select THREE.)

Select 3 answers
A.Run `terraform state mv` to rename the resource in state, then update the config.
B.Add a `moved` block in the configuration to map the old address to the new.
C.Simply change the resource name in the configuration and run `terraform apply`.
D.Use a `removed` block to remove the old resource and `import` block to import the new.
E.Run `terraform state rm` then `terraform import` with the new address.
AnswersA, B, D

state mv renames in state without destroy.

Why this answer

Options A, B, and C are correct. Using `moved` block, `terraform state mv`, and then updating config manually, and using `removed` block with `import` are all valid. Option D is wrong because `terraform state rm` + `terraform import` is two steps but works, but the question asks for modification without destroy/recreate; however, removing and importing does not cause destroy, but it's not a single modification.

Option E is wrong because changing the resource name in config and running apply will destroy and recreate.

17
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

Correct pattern: count with ternary.

Why this answer

Option D is correct because 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.

18
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

Why this order

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

19
Multi-Selecthard

Which THREE statements about Terraform modules are correct?

Select 3 answers
A.Module sources can be local file paths.
B.Modules must always be in the root directory of the configuration.
C.A module can only use one provider.
D.Modules can be sourced from the Terraform Registry.
E.Modules can expose output values via 'output' blocks.
AnswersA, D, E

Local paths are valid module sources.

Why this answer

Option A is correct because Terraform modules can be sourced from local file paths using a relative or absolute path (e.g., `source = "./modules/network"`). This allows you to reuse configuration stored in subdirectories without needing a remote repository or registry. The `source` argument supports local paths as one of its valid source types, enabling modular development within a single project.

Exam trap

HashiCorp often tests the misconception that modules must reside in the root directory or that a module can only use one provider, leading candidates to incorrectly select option B or C.

20
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

Correctly references VPC module output.

Why this answer

Correct B: module outputs are accessed as module.module_name.output_name. A and C use incorrect syntax, D misses the VPC module definition.

21
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

This lifecycle argument creates a replacement resource before destroying the existing one.

Why this answer

Options A and C are correct. Option A: create_before_destroy causes a new resource to be created before destroying the old one. Option C: depends_on ensures explicit ordering.

Option B is wrong because count is for creating multiple resources, not ordering. Option D is wrong because for_each is for iteration, not ordering. Option E is wrong because lifecycle { prevent_destroy } prevents destruction but does not affect creation order.

22
MCQmedium

A team stores sensitive secrets in AWS Secrets Manager and wants to reference them in Terraform without exposing the values. Which approach is most secure and recommended?

A.Set the secret as an environment variable and reference it in the configuration.
B.Store the secret in a variables.tf file with a default value.
C.Use an aws_secretsmanager_secret_version data source and mark the variable as sensitive.
D.Define the secret in a locals block with a default.
AnswerC

Data sources retrieve secrets securely at runtime, and sensitive variables prevent display.

Why this answer

Option A is correct: using data sources to read secrets at plan/apply time and passing them via variables marked sensitive. Option B is wrong because hardcoding in variables.tf is insecure. Option C is wrong because using defaults in locals still exposes the value if output.

Option D is wrong because environment variables can leak in logs or shell history.

23
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

Allows using multiple providers in the same configuration.

Why this answer

Option A is correct because 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.

24
MCQeasy

A junior engineer is asked to review a Terraform configuration that defines a module from the Terraform Registry. Which file in the module’s root directory typically contains the description of the module’s inputs and outputs?

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

defines input variables

Why this answer

Option A is correct because the `variables.tf` file declares input variables, and `outputs.tf` declares outputs, but the question asks for description of inputs and outputs, which is often documented in `README.md` or the module's documentation. However, among these options, `variables.tf` and `outputs.tf` are the files that define them. But the question likely expects `variables.tf` as the primary file for inputs.

The correct answer is A: variables.tf. Option B is for outputs, option C is for resources, option D is for the provider.

25
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

console opens an interactive session to evaluate expressions against the current state.

Why this answer

Option D is correct: terraform console opens an interactive console to evaluate expressions. Option A is wrong because terraform plan does not evaluate arbitrary expressions. Option B is wrong because terraform validate only checks syntax.

Option C is wrong because terraform output shows output values, not arbitrary expressions.

26
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.
AnswerC

create_before_destroy ensures new is created before old is destroyed.

Why this answer

Correct B: The create_before_destroy lifecycle rule ensures the new instance is created before the old one is destroyed.

27
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

Prints output values from the state.

Why this answer

Correct D: terraform output displays output values. A shows state details, B manages state, C shows plan.

28
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 supports basic and complex variable types.

29
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

Option C is correct because `terraform import` is the proper way to bring existing resources into Terraform state. Option A is wrong because simply running apply would try to create a duplicate. Option B is wrong because manually editing the state file is error-prone and not recommended.

Option D is wrong because `terraform refresh` refreshes state, but does not import new resources.

30
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

Reconfiguring the backend pulls the latest state, ensuring the plan reflects current infrastructure.

Why this answer

Option A is correct because `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.

31
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

'terraform init' downloads the specified module version.

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.

32
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

AMI changes always require recreation for EC2

Why this answer

Option C is correct because changing the AMI of an EC2 instance forces recreation; there is no in-place update. Option A is wrong because `create_before_destroy` still destroys the old. Option B is wrong because ignoring changes to AMI would prevent updates.

Option D is wrong because `prevent_destroy` would block the operation.

33
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

Downloads required providers and modules.

Why this answer

Correct A: terraform init initializes the directory. B gets modules but not providers, C and D require init first.

34
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

Correctly uses local value with indexing.

Why this answer

Correct C: local values are accessed with local.name. Option A and D miss the local prefix, B is syntactically incorrect.

35
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

Command-line flag overrides variables for that run.

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.

36
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

Converts the list to a set, valid for for_each.

Why this answer

Correct C: toset converts the list to a set, which is required by for_each. A is a list, B is a map but not necessary, D is a splat expression returning a list.

37
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

causes drift and a plan diff

Why this answer

Option D is correct because the current state might have been manually modified outside Terraform, causing a drift that appears as a plan diff. Option A is wrong because if state is up-to-date, no manual state edit occurred. Option B is wrong because a newer provider version could introduce changes but would be systematic.

Option C is wrong because stale state would show drift but the state is up-to-date.

38
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

New resource created; old resource not destroyed.

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.

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

40
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

Option B and C are correct because Terraform automatically loads terraform.tfvars and also supports .tfvars.json extension. Option A is incorrect because Terraform does not load .tf files recursively by default. Option D is incorrect because the -var-file flag does not accept comma-separated lists; you must use multiple flags.

Option E is incorrect because backend configuration does not have to be in the same file as provider configuration.

41
MCQmedium

A configuration creates multiple AWS instances using count. The developer wants to output the IDs of all instances. Which output block is valid? (Choose the best answer.)

A.output "ids" { value = aws_instance.web.*.id }
B.All of the above
C.output "ids" { value = aws_instance.web[*].id }
D.output "ids" { value = [for i in aws_instance.web : i.id] }
AnswerB

All are valid, including splat and for expressions.

Why this answer

Correct D: All three expressions are valid ways to output a list of IDs from a count resource.

42
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

count creates indexed resources

Why this answer

Option B is correct because `count` creates multiple instances and `count.index` can be used to derive unique names. Option A is wrong because `for_each` expects a map or set, not an index. Option C and D are wrong because they are not mechanisms for generating multiple resources.

43
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

Option B is correct because 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.

44
MCQmedium

An operator runs 'terraform plan' and sees that a resource will be replaced. They want to avoid destroying the resource, but still apply other changes. What should they do?

A.Use 'terraform apply -replace=resource_address' to replace only that resource.
B.Add a 'lifecycle' block with 'create_before_destroy = true'.
C.Set 'ignore_changes' to the attribute causing the replacement.
D.Add 'prevent_destroy = true' to the resource.
AnswerB

Creates new resource before destroying old one, reducing downtime.

Why this answer

Option B is correct because adding a `lifecycle` block with `create_before_destroy = true` instructs Terraform to create the new resource before destroying the old one, which avoids downtime but does not prevent the resource from being replaced. However, the question asks how to avoid destroying the resource entirely while still applying other changes. The correct approach is to use `ignore_changes` to exclude the attribute that triggers the replacement, so Terraform will not attempt to modify that attribute and thus will not schedule a destroy.

Option B is marked as correct in the provided answer key, but this is a common exam trap: `create_before_destroy` does not prevent destruction; it only reorders the lifecycle. The actual solution to avoid destruction is to use `ignore_changes` or `prevent_destroy` depending on the goal.

Exam trap

HashiCorp often tests the misconception that `create_before_destroy` prevents destruction, when in reality it only changes the order of operations; the trap here is that candidates confuse lifecycle ordering with lifecycle prevention, leading them to select B instead of the correct option C.

How to eliminate wrong answers

Option A is wrong because `terraform apply -replace=resource_address` explicitly forces Terraform to destroy and recreate that specific resource, which is the opposite of avoiding destruction. Option C is wrong because setting `ignore_changes` to the attribute causing the replacement tells Terraform to ignore future changes to that attribute, thereby preventing the replacement from being triggered; this is the correct technical solution to avoid destroying the resource while applying other changes. Option D is wrong because `prevent_destroy = true` prevents any destroy operation on the resource, which would block the replacement but also block any other changes that require modification of the resource (e.g., in-place updates that Terraform cannot perform), leading to an error during apply.

45
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 override a module variable, it must be passed as an argument within the module block (e.g., module "web" { instance_count = 3 }). A local value does not affect the module.

Why this answer

Option B is correct because the most common mistake is defining the variable as a local value rather than passing it as an argument to the module block. Option A is incorrect because the variable exists in the module (it has a default). Option C is incorrect because terraform init is not required for variable changes; terraform validate passed, so syntax is fine.

Option D is incorrect because module version does not affect variable overrides.

46
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

Validates syntax and internal consistency.

Why this answer

Correct D: terraform validate checks syntax and internal consistency. Option A formats code, B shows execution plan, C generates a graph of dependencies.

47
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

ensures consistent behavior

Why this answer

Options A and E are correct. Using remote state with locking prevents conflicts, and pinning provider versions ensures reproducibility. Option B is wrong because using `latest` is not reproducible.

Option C is wrong because hardcoding secrets is insecure. Option D is wrong because large monolithic configurations are harder to maintain.

48
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

Correctly references the module output.

Why this answer

Correct B: module outputs are referenced as module.module_name.output_name. A adds unnecessary '.outputs', C is incorrect syntax, D uses a variable not defined.

49
MCQhard

What is the most likely cause of this error?

A.The `output` block is referencing a non-existent attribute.
B.The `aws_eip` resource must use `self.instance` instead of `aws_instance.web.id`.
C.The `depends_on` meta-argument is missing from the aws_eip resource.
D.The `aws_instance.web` resource has a syntax error in the ami attribute.
AnswerC

Implicit dependency should work, but the error suggests Terraform is not resolving the dependency correctly. Adding explicit depends_on resolves it.

Why this answer

Option C is correct because the `aws_eip` resource depends on the `aws_instance.web` resource to ensure the instance is created before the Elastic IP is allocated. Without an explicit `depends_on` meta-argument, Terraform may attempt to create the EIP before the instance, causing an error if the instance ID is not yet available. The error message typically indicates that the `aws_eip` resource cannot resolve the `instance` argument because the instance resource has not been created yet.

Exam trap

HashiCorp often tests the misconception that `depends_on` is only needed when there is no implicit reference, but the trap here is that candidates may overlook that Terraform's automatic dependency detection can fail in certain edge cases, such as when the reference is inside a `count` or `for_each` expression, or when the resource is in a different module.

How to eliminate wrong answers

Option A is wrong because the `output` block referencing a non-existent attribute would produce a different error, such as 'Unsupported attribute', not a dependency-related error. Option B is wrong because `self.instance` is not a valid syntax in Terraform; the correct way to reference the instance ID is `aws_instance.web.id`, and using `self.instance` would cause a syntax error, not a dependency error. Option D is wrong because a syntax error in the `ami` attribute would cause a validation error during plan or apply, not a runtime error about missing dependencies.

50
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

Creates new resource before destroying old, ensuring zero downtime.

Why this answer

Correct B: create_before_destroy creates the new resource before destroying the old one. A prevents destruction, C ignores attribute changes, D handles explicit dependencies.

51
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

The -reconfigure flag disables backend migration and forces reinitialization from scratch.

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.

52
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

variable block with 'default' argument sets a default value for the variable.

Why this answer

Option C is correct: the variable block with a default argument sets a default. Option A is wrong because output blocks produce output values. Option B is wrong because locals are for local computed values.

Option D is wrong because terraform block is for provider and backend settings.

53
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

This outputs the resource's current attributes in JSON format, suitable for generating configuration.

Why this answer

Option B is correct because terraform state show displays the state of a single resource, and using -json provides machine-readable output ideal for generating configuration. Option A is wrong because terraform plan only shows changes, not full state. Option C is wrong because terraform output shows output values, not resource attributes.

Option D is wrong because terraform state pull outputs the entire state file, not a single resource in an easy-to-parse format.

54
Multi-Selecthard

An organization wants to reference outputs from a root module in another Terraform configuration. Which THREE methods are valid for reading those outputs?

Select 3 answers
A.Store outputs in a remote state backend and use terraform_remote_state with appropriate configuration.
B.Use provider data sources (e.g., aws_instance data source) to query existing infrastructure directly.
C.Use a module block with source = "./path/to/other-config" and reference its outputs.
D.Use a terraform_remote_state data source pointing to the remote backend of the other configuration.
E.Read the state file directly using terraform state pull and parse in HCL.
AnswersA, B, D

This is the standard way to share outputs across root modules.

Why this answer

Options B, C, and D are correct. Option B: terraform_remote_state data source reads outputs from another state. Option C: using data sources from a provider can read infrastructure directly.

Option D: outputs.tf in a remote state backend can be referenced via terraform_remote_state. Option A is wrong because relative paths only work within a single configuration. Option E is wrong because partial outputs cannot be extracted from state file directly via HCL.

55
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

Best practice: use provisioners only when necessary.

Why this answer

Option B is correct because 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.

56
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

Option B is correct because 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.

57
MCQhard

What will happen when this configuration is applied?

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 (~) signals an in-place update; changing instance type triggers a stop/start, which may involve a reboot.

Why this answer

Option C is correct because the tilde (~) indicates an in-place update. Changing the instance type on AWS requires a stop/start, which results in a reboot but not a full destroy and recreate. Option A is incorrect because the plan shows an update, not a destroy/recreate (which would show -/+).

Option B is incorrect because changing instance type typically requires a reboot, causing downtime. Option D is incorrect because the plan does not indicate any missing variables.

58
Multi-Selectmedium

A team runs terraform plan and sees changes that are unexpected. Which TWO actions should they take to investigate before applying?

Select 2 answers
A.Run terraform providers mirror to ensure provider versions are consistent.
B.Save the plan with terraform plan -out=plan.tfplan and then use terraform show plan.tfplan to examine details.
C.Delete the state and re-import all resources.
D.Manually edit the state file to match the configuration.
E.Revert the configuration to the previous commit and re-run plan.
AnswersA, B

Inconsistent provider versions can cause unexpected drift.

Why this answer

Options B and D are correct. Option B: terraform show with a saved plan file reveals detailed changes. Option D: terraform providers mirror can help verify provider versions are consistent.

Option A is wrong because reverting may lose intended changes. Option C is wrong because manual state editing is risky. Option E is wrong because deleting state would lose all management.

59
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

Correctly specifies the dependency as a list of resource addresses.

Why this answer

Correct D: depends_on requires a list of resource addresses. Option D is correct syntax. Others are incorrect.

60
MCQhard

A large organization uses Terraform to manage hundreds of AWS resources across multiple accounts. They have a central repository with modules for common patterns. A new engineer is tasked with adding a new feature that requires modifying the configuration of an existing S3 bucket to enable server-side encryption. The current configuration for the bucket is defined in a module that is used by many other teams. The engineer adds an `aws_s3_bucket_server_side_encryption_configuration` resource as recommended by the latest AWS provider. After running `terraform plan`, they see that the plan will create the new encryption resource but also shows an in-place update to the bucket itself. They check the bucket resource and see that it has a `server_side_encryption_configuration` argument that is deprecated. The engineer wants to ensure backward compatibility and avoid breaking other teams' configurations. What is the best course of action?

A.Use the deprecated `server_side_encryption_configuration` argument in the bucket resource to avoid adding a new resource.
B.Coordinate with the module maintainers to update the module, using the new encryption resource and removing the deprecated argument in a later release.
C.Proceed with the plan as is, since the in-place update is expected during migration.
D.Add a `lifecycle` block with `create_before_destroy` to the new encryption resource to prevent destruction.
AnswerB

ensures backward compatibility via module versioning

Why this answer

Option D is correct because using the new separate resource is the modern approach, and migrating from the old argument requires careful coordination. The best course is to implement the change using the new resource and update the module's version, communicating the change. Option A is wrong because using the deprecated argument is not recommended.

Option B is wrong because the plan already shows the correct approach; ignoring the plan might cause issues. Option C is wrong because forcing recreation might break other teams.

61
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

Option B is correct because `terraform output` displays the output values from the current state. Option A is wrong because `terraform show` shows the state or plan file but is not the quickest for just outputs. Option C is wrong because `terraform state list` lists resources.

Option D is wrong because `terraform plan` does not output values.

62
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

Some providers mark certain attributes as ForceNew; if name is ForceNew, any config change to the resource may trigger replacement.

Why this answer

Option C is correct: the 'name' attribute may be ForceNew, meaning any change forces replacement. Option A is wrong because create_before_destroy does not cause this. Option B is wrong because tags are not typically ForceNew.

Option D is wrong because underlying SDK may not trigger replacement for tags.

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

64
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

"to add" indicates creation

Why this answer

Option B is correct because the plan shows one resource will be created, none modified, none destroyed. Option A is wrong because it says add, not change. Option C is wrong because there is no change or destroy.

Option D is wrong because there is an add.

65
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

Option A is correct because variables are declared using the 'variable' block in .tf files. Option C is correct because Terraform automatically loads terraform.tfvars. Option B is incorrect because variables can have defaults and are not required to be assigned before plan.

Option D is incorrect because environment variables with TF_VAR_ prefix can override variable values. Option E is incorrect because default values are set in the variable block, not in .tfvars files.

66
MCQhard

A team has an existing S3 bucket created outside Terraform. They want to manage it with Terraform by importing its state. Which of the following is the correct sequence of commands to read the bucket's configuration and avoid drift?

A.Run terraform refresh, then terraform state pull to generate configuration.
B.Run terraform plan, note the resource address, then run terraform import.
C.Run terraform import, then terraform state show to generate configuration.
D.Write a minimal resource configuration, run terraform import, then terraform plan, then adjust configuration to match state.
AnswerD

This is the standard workflow: import into existing config, then use plan to detect differences and update config.

Why this answer

Option C is correct: first write a minimal resource block, then import, then run terraform plan to detect drift, then adjust config to match. Option A is wrong because terraform import requires a configuration to exist. Option B is wrong because terraform plan before import will show nothing.

Option D is wrong because terraform refresh alone does not create a state entry for unmanaged resources.

67
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

output retrieves outputs from the state without acquiring a lock.

Why this answer

Option B is correct because terraform output retrieves outputs from the state without any lock or plan. Option A is wrong because terraform plan acquires a lock and might show planned changes. Option C is wrong because terraform state pull downloads the entire state file, which is overkill and also acquires a lock.

Option D is wrong because terraform console does not directly show outputs.

68
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 does not automatically load arbitrary .tfvars files; using -var-file explicitly loads it.

Why this answer

The error indicates the variable file is not being loaded. The most common reason is that the -var-file flag was omitted. Option B fixes this by explicitly specifying the variable file.

Option A is incorrect because the variable is in the module, and root module can pass it via module block, but the variable is already defined in the module. Option C is incorrect because passing via module block is the correct way, but the error suggests the variable file is not being read at all. Option D is incorrect because the workspace is already set correctly.

Ready to test yourself?

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