CertSafari

    Free HashiCorp Terraform Authoring and Operations Professional Sample Questions

    35 free sample questions from our bank of 322+, covering every exam domain, with answers and detailed explanations. Updated August 2026.

    Domain 1: Manage resource lifecycle

    Subdomain 1.1: Initialize a configuration using terraform init and its options

    1.What is the primary purpose of the `-from-module` option when executing the `terraform init` command?

    1. A.It initializes only a specific child module within the current configuration, ignoring the root module.
    2. B.It copies the contents of the specified source module into the target empty working directory before initialization.
    3. C.It downloads the specified module and outputs its variables and outputs to the console for inspection.
    4. D.It bypasses the root module and executes a plan directly against the specified child module.
    Show answer & explanation

    Correct answer: BIt copies the contents of the specified source module into the target empty working directory before initialization.

    • A. Incorrect. The `-from-module` option does not perform partial initialization of a child module within an existing configuration. Instead, it is used to populate an empty directory with a module to serve as the new root configuration.
    • B. Correct. The `-from-module=SOURCE` option tells Terraform to copy the contents of the specified source module into the current (usually empty) working directory before proceeding with the initialization. This effectively promotes the module to be the root module of the current project.
    • C. Incorrect. This option copies the actual source code and files of the module into the target directory; it does not simply download the module for inspection or display its variables and outputs in the console.
    • D. Incorrect. The `-from-module` flag is part of the initialization phase, not the execution phase. It does not bypass the root module to run plans or applies; it creates the root module structure from a source module.

    Subdomain 1.2: Generate an execution plan using terraform plan and its options

    2.A large Terraform configuration manages thousands of resources. During the refresh phase of `terraform plan`, the AWS provider frequently hits API rate limits, causing the plan to fail. Without modifying the provider configuration block, how can you mitigate this issue from the CLI?

    1. A.Run `terraform plan -parallelism=5` to reduce the number of concurrent operations.
    2. B.Run `terraform plan -rate-limit=5` to throttle the API requests.
    3. C.Run `terraform plan -refresh-rate=5` to slow down the state refresh phase.
    4. D.Run `terraform plan -max-api-calls=5` to limit the provider's request rate.
    Show answer & explanation

    Correct answer: ARun `terraform plan -parallelism=5` to reduce the number of concurrent operations.

    • A. Correct. The `-parallelism=n` flag (which defaults to 10) controls the number of concurrent operations Terraform performs as it walks the dependency graph. Reducing this value decreases the number of simultaneous API requests made to the cloud provider, effectively throttling the load and helping to avoid API rate limits.
    • B. Incorrect. There is no `-rate-limit` flag in the Terraform CLI. Throttling is handled via `-parallelism` or within specific provider configurations.
    • C. Incorrect. There is no `-refresh-rate` flag in the Terraform CLI. The concurrency of the refresh phase is governed by the global `-parallelism` setting.
    • D. Incorrect. The Terraform CLI does not expose a `-max-api-calls` flag. API request management is controlled through concurrency settings or provider-specific retry logic.

    Subdomain 1.4: Destroy resources using terraform destroy and its options

    3.A junior engineer runs `terraform destroy -auto-approve` on a production workspace to decommission an old environment. The command fails immediately, citing that a specific `aws_db_instance` cannot be destroyed. What is the most likely Terraform-specific reason for this failure, and how must it be resolved?

    1. A.The state file is locked by another user; the engineer must use the -force flag to override the lock.
    2. B.The resource has lifecycle { prevent_destroy = true } configured; the configuration must be updated to remove this block or set it to false before destroying.
    3. C.The provider has deletion_protection enabled by default; the engineer must pass -ignore-provider-protections to the destroy command.
    4. D.The resource was created manually and imported; imported resources cannot be destroyed via terraform destroy.
    Show answer & explanation

    Correct answer: BThe resource has lifecycle { prevent_destroy = true } configured; the configuration must be updated to remove this block or set it to false before destroying.

    • A. State locking errors are global and prevent any Terraform operation from beginning. They produce a specific lock error message and are resolved using `terraform force-unlock` after verification, not with a `-force` flag on the destroy command.
    • B. The `prevent_destroy` meta-argument is a Terraform-specific safety feature. If this is set to true within the `lifecycle` block, Terraform will immediately error during the planning phase of a destroy operation. To resolve this, the engineer must modify the configuration to remove the argument or set it to false, then run the destroy command again.
    • C. While AWS RDS instances have a `deletion_protection` attribute, this is a cloud-provider setting managed through the resource arguments. Terraform does not provide a CLI flag such as `-ignore-provider-protections` to bypass this; the protection must be disabled in the configuration and applied first.
    • D. Imported resources are tracked in the state file and managed exactly like resources created by Terraform. Being an imported resource does not inherently prevent it from being destroyed via the CLI.

    Subdomain 1.4: Destroy resources using terraform destroy and its options

    4.You want to review exactly what will be destroyed before actually destroying it, and you want to save this execution plan to a file named `tfdestroy.plan` so it can be reviewed by a senior engineer and applied later. Which command generates this specific plan?

    1. A.terraform plan -destroy -out=tfdestroy.plan
    2. B.terraform destroy -plan=tfdestroy.plan
    3. C.terraform plan -out=tfdestroy.plan -target=destroy
    4. D.terraform destroy -out=tfdestroy.plan
    Show answer & explanation

    Correct answer: Aterraform plan -destroy -out=tfdestroy.plan

    • A. This command correctly uses the `terraform plan` command with the `-destroy` flag to create a plan specifically for resource destruction. The `-out` flag captures this plan in a file, which can then be inspected or applied later using `terraform apply tfdestroy.plan`.
    • B. This command is invalid because `terraform destroy` does not support a `-plan` argument. To generate and save a plan file for review, you must use the `terraform plan` command.
    • C. This command is incorrect because the `-target` flag requires a specific resource address (e.g., `aws_instance.example`), not an action keyword like 'destroy'. Additionally, without the `-destroy` flag, Terraform will generate a standard plan to reach the desired state defined in your configuration files, rather than planning to destroy all managed infrastructure.
    • D. This command is incorrect because `terraform destroy` is used to execute a destruction directly (with an interactive prompt) and does not support the `-out` flag. The `-out` flag is unique to the `terraform plan` command.

    Subdomain 1.3: Apply configuration changes using terraform apply and its options

    5.Your automated deployment pipeline frequently fails during the `terraform apply` stage with an "Error acquiring the state lock" message. Investigation reveals that the preceding `terraform plan` step takes a few extra seconds to release the lock on the remote backend. How can you resolve this issue without disabling state locking?

    1. A.Run `terraform apply -lock-timeout=30s` to instruct Terraform to wait up to 30 seconds for the lock to become available.
    2. B.Run `terraform apply -retry-lock=30s` to force Terraform to retry the lock acquisition every second for 30 seconds.
    3. C.Run `terraform apply -wait=30s` to pause the execution of the apply command before attempting to acquire the lock.
    4. D.Run `terraform apply -lock-delay=30s` to add a buffer time before the apply phase begins.
    Show answer & explanation

    Correct answer: ARun `terraform apply -lock-timeout=30s` to instruct Terraform to wait up to 30 seconds for the lock to become available.

    • A. Correct. The `-lock-timeout` flag is a standard option for Terraform commands (such as plan and apply) that interact with state. It tells Terraform to retry acquiring the state lock for the specified duration (e.g., 30s) before returning an error. This is the recommended way to handle transient lock contention in automation pipelines.
    • B. Incorrect. `-retry-lock` is not a valid Terraform CLI flag. The functionality to retry lock acquisition is specifically provided by the `-lock-timeout` flag.
    • C. Incorrect. Terraform does not have a `-wait` flag for the apply command to pause execution. Lock management is handled through the locking mechanism and its timeout parameter.
    • D. Incorrect. There is no `-lock-delay` flag for Terraform CLI commands. While some backends (like Consul) might have internal lock delay settings for sessions, the global command-line interface uses `-lock-timeout` to manage lock wait times.

    Subdomain 1.5: Manage resource state, including importing resources and reconciling resource drift

    6.An API outage caused Terraform to crash while destroying an Azure resource group. The resource group was successfully deleted in Azure, but Terraform's state still shows it as existing. Subsequent `terraform plan` runs fail because the resource cannot be found by the provider. How should you resolve this state inconsistency?

    1. A.Run `terraform apply -refresh-only`.
    2. B.Run `terraform state rm azurerm_resource_group.example`.
    3. C.Run `terraform untaint azurerm_resource_group.example`.
    4. D.Run `terraform import azurerm_resource_group.example <id>`.
    Show answer & explanation

    Correct answer: BRun `terraform state rm azurerm_resource_group.example`.

    • A. While `terraform apply -refresh-only` attempts to sync state with real-world infrastructure, it can often fail or behave unexpectedly if the provider returns a terminal error (like a 404) for a resource it expects to exist. If the plan phase is failing because the resource is missing, a refresh may not reliably resolve the state inconsistency.
    • B. Correct. `terraform state rm` is the standard tool for surgically removing a resource from the Terraform state without attempting to modify or query the real-world infrastructure. This is the appropriate action when a resource has been deleted out-of-band or during a failed run, allowing Terraform to stop tracking the non-existent resource.
    • C. Tainting is used to mark a resource for recreation during the next apply. `terraform untaint` clears that status. Neither command addresses a scenario where the resource is entirely missing from the provider but still exists in the state file.
    • D. Terraform import is used to bring existing infrastructure under Terraform management. Because the resource group has already been deleted in Azure, there is no resource to import, and this command would fail.

    Subdomain 1.5: Manage resource state, including importing resources and reconciling resource drift

    7.Which command is used to update the provider source address for resources in a Terraform state file when a provider has been renamed or moved to a new namespace in the Terraform Registry?

    1. A.terraform providers mirror
    2. B.terraform state replace-provider
    3. C.terraform init -upgrade
    4. D.terraform state push -force
    Show answer & explanation

    Correct answer: Bterraform state replace-provider

    • A. The terraform providers mirror command is used to download and store provider plugins in a local directory mirror, typically for use in air-gapped environments or for caching. It does not update or rewrite provider source addresses within the Terraform state file.
    • B. The terraform state replace-provider command is specifically designed to update provider source addresses for resources already recorded in the state file. This is the required action when a provider is renamed or moved to a new namespace (e.g., moving from a default namespace to a specific organization namespace) to ensure existing resources map to the correct provider source.
    • C. The terraform init -upgrade command is used to initialize a configuration and upgrade provider plugins to the latest versions allowed by the version constraints. While it manages local plugin installation, it does not modify the provider source metadata stored in the state file for existing resources.
    • D. The terraform state push command is used to manually upload a local state file to a remote backend. The -force flag allows overwriting the remote state if the serials do not match, but the command does not perform internal transformations like remapping provider addresses.

    Domain 2: Develop & troubleshoot dynamic configuration

    Subdomain 2.6: Analyze best practices for managing sensitive data, such as using Vault for secrets management.

    8.You are deploying an AWS EC2 instance via Terraform. The application on the instance requires a highly sensitive API key to start up. Currently, the API key is passed into the `user_data` script via a Terraform template. Security flags this as a critical vulnerability because the `user_data` is visible in plaintext via the AWS API and metadata service. What is the best practice to resolve this?

    1. A.Base64 encode the API key in the `user_data` script to obfuscate it from the AWS console.
    2. B.Mark the `user_data` attribute as `sensitive = true` in the Terraform configuration to encrypt it in AWS.
    3. C.Remove the API key from `user_data` and configure a Vault Agent on the EC2 instance to fetch the secret at runtime using an AWS IAM auth role.
    4. D.Store the API key in a Terraform Cloud sensitive variable and use a `remote-exec` provisioner to inject it after the instance boots.
    Show answer & explanation

    Correct answer: CRemove the API key from `user_data` and configure a Vault Agent on the EC2 instance to fetch the secret at runtime using an AWS IAM auth role.

    • A. Base64 encoding is an encoding scheme, not encryption. It provides no confidentiality because any user or process with access to the AWS console, API, or Instance Metadata Service (IMDS) can easily decode the string back to its original plaintext form.
    • B. Marking an attribute as `sensitive = true` in Terraform only affects the CLI output and logs by redacting the value. It has no effect on how the data is handled or stored by the cloud provider (AWS). The `user_data` will still be transmitted to AWS and stored in a way that is retrievable via the metadata service in plaintext.
    • C. This is the industry-standard best practice for managing secrets on compute instances. By using the Vault AWS IAM auth method, the EC2 instance uses its internal machine identity to authenticate with Vault. The Vault Agent then retrieves the secret directly into the instance's memory or a protected file at runtime, ensuring the secret never touches the provider's metadata service or Terraform state in plaintext.
    • D. While Terraform Cloud sensitive variables protect values within the Terraform platform, using a `remote-exec` provisioner is considered a legacy and less secure pattern. Provisioners can leak sensitive data into execution logs, require open network paths (like SSH or WinRM), and are less resilient than identity-based secret retrieval via a dedicated secrets manager.

    Subdomain 2.3: Compute and interpolate data using HCL functions

    9.You have a map where the keys are availability zones and the values are lists of instance IDs deployed in those zones: `{"us-east-1a" = ["i-123", "i-456"], "us-east-1b" = ["i-789"]}`. You need to transform this into a map where the keys are the instance IDs and the values are lists containing their corresponding availability zone: `{"i-123" = ["us-east-1a"], "i-456" = ["us-east-1a"], "i-789" = ["us-east-1b"]}`. Which function accomplishes this?

    1. A.transpose
    2. B.matchkeys
    3. C.zipmap
    4. D.setproduct
    Show answer & explanation

    Correct answer: Atranspose

    • A. Correct. The transpose function takes a map of lists of strings and swaps the keys and values to produce a new map of lists of strings. In this scenario, the instance IDs (original values) become the new keys, and the availability zones (original keys) become the new list values.
    • B. Incorrect. The matchkeys function filters a list of values by checking if the corresponding index in a second list (keys) matches a third list (search values). It returns a filtered list, not a transformed map.
    • C. Incorrect. The zipmap function constructs a map from two separate lists (one for keys and one for values). It does not perform the inversion or transformation of an existing map's internal list elements.
    • D. Incorrect. The setproduct function computes the Cartesian product of two or more sets, returning a list of tuples representing all possible combinations. It is unrelated to map key-value inversion.

    Subdomain 2.2: Query providers using data sources

    10.You need to retrieve a list of subnets for a specific AWS VPC, but you only know the VPC's Name tag. You write the following configuration: ```hcl data "aws_vpc" "main" { tags = { Name = "prod-vpc" } } data "aws_subnets" "main" { filter { name = "vpc-id" values = [data.aws_vpc.main.id] } } ``` How does Terraform handle the execution order of these data sources?

    1. A.Terraform executes them in the exact order they appear in the configuration file.
    2. B.Terraform requires an explicit `depends_on = [data.aws_vpc.main]` in the `aws_subnets` data source to determine the order.
    3. C.Terraform automatically infers the dependency and reads `aws_vpc` before `aws_subnets`.
    4. D.Terraform executes both concurrently and resolves the interpolation after both API calls return.
    Show answer & explanation

    Correct answer: CTerraform automatically infers the dependency and reads `aws_vpc` before `aws_subnets`.

    • A. Terraform does not rely on the order of blocks in the configuration file to determine execution order. Instead, it builds a dependency graph based on references and metadata. File order is irrelevant when interpolations create dependencies.
    • B. While Terraform supports the `depends_on` argument for data sources to handle edge cases, it is not required here. An implicit dependency is created because `aws_subnets` references `data.aws_vpc.main.id`. Terraform automatically identifies this relationship and sequences the operations without manual configuration.
    • C. Correct. Terraform automatically infers the dependency because the `aws_subnets` data source uses an attribute from the `aws_vpc` data source (`data.aws_vpc.main.id`). This creates an implicit dependency in the resource graph, ensuring the VPC data is retrieved before the subnet query is initiated.
    • D. Terraform will not execute these data sources concurrently because the output of `aws_vpc` is a required input for `aws_subnets`. The dependency graph enforces sequential execution for dependent reads to ensure that the required values are available for the subsequent provider API call.

    Subdomain 2.5: Configure input variables and outputs, including complex types

    11.Which of the following is the correct syntax for a variable validation condition that checks if an input variable `ami_id` matches a specific pattern using regular expressions?

    1. A.condition = startswith(var.ami_id, "ami-") && length(var.ami_id) == 17
    2. B.condition = match("^ami-[a-zA-Z0-9]{17}$", var.ami_id)
    3. C.condition = can(regex("^ami-[a-zA-Z0-9]{17}$", var.ami_id))
    4. D.validate = regex("^ami-[a-zA-Z0-9]{17}$", var.ami_id)
    Show answer & explanation

    Correct answer: Ccondition = can(regex("^ami-[a-zA-Z0-9]{17}$", var.ami_id))

    • A. This expression uses basic string functions but is insufficient. It does not ensure the remaining characters are alphanumeric. Furthermore, for a standard AWS AMI ID, the length check of 17 would be incorrect as it would need to include the 'ami-' prefix length (totaling 21 characters).
    • B. Terraform does not provide a built-in `match` function for variable validation. Validation conditions require an expression that returns a boolean value, and the idiomatic way to perform regex matching is via the `regex` or `regexall` functions.
    • C. This is the correct idiomatic approach in Terraform. The `regex` function attempts to match the pattern and throws an error if it fails. The `can` function evaluates the expression and returns `true` if it succeeds without error and `false` if it fails, providing the boolean result required by the `condition` attribute.
    • D. The attribute name inside a `validation` block must be `condition`, not `validate`. Additionally, `regex` alone returns a string or list of matches (or an error), which cannot be directly used as a boolean condition.

    Subdomain 2.5: Configure input variables and outputs, including complex types

    12.Which of the following conditions correctly validates that every 'port' attribute within a list of objects named 'services' falls within the inclusive range of 1024 to 65535?

    1. A.condition = anytrue([for obj in var.services : obj.port >= 1024 && obj.port <= 65535])
    2. B.condition = contains(var.services[*].port, range(1024, 65535))
    3. C.condition = alltrue([for obj in var.services : obj.port >= 1024 && obj.port <= 65535])
    4. D.condition = var.services[*].port >= 1024 && var.services[*].port <= 65535
    Show answer & explanation

    Correct answer: Ccondition = alltrue([for obj in var.services : obj.port >= 1024 && obj.port <= 65535])

    • A. Incorrect. The anytrue function returns true if at least one element in the list evaluates to true. In the context of variable validation, this is inappropriate because it would allow the input to be accepted even if some service ports were invalid, as long as at least one port was within the required range.
    • B. Incorrect. The contains(list, value) function checks whether a specific value is an element of a list. Using range() as the second argument results in a type mismatch for this logic, as range() produces a list of integers. Furthermore, range() is end-exclusive, meaning range(1024, 65535) would not include the port 65535.
    • C. Correct. This is the idiomatic way to perform element-wise validation on a list of objects in Terraform. The 'for' expression iterates through the services to create a list of boolean values, and alltrue ensures that every single item in that list meets the criteria.
    • D. Incorrect. The splat operator (var.services[*].port) returns a list of values. Terraform does not support direct element-wise comparison between a list and a scalar (or another list) using standard comparison operators like >= or <=. This expression will result in a syntax or type error.

    Subdomain 2.1: Use language features to validate configuration

    13.You are writing a module that provisions an S3 bucket and returns its ARN as an output. You want to ensure that the output is only returned if the bucket has versioning enabled. If versioning is not enabled, Terraform should produce an error. Which of the following configurations can achieve this?(Select 2)

    1. A.Add a precondition block directly inside the output block checking the bucket's versioning status.
    2. B.Add a postcondition block directly inside the output block checking the bucket's versioning status.
    3. C.Add a postcondition block inside the aws_s3_bucket resource's lifecycle block checking self.versioning[0].enabled.
    4. D.Add a validation block directly inside the output block.
    5. E.Add a check block directly inside the output block.
    Show answer & explanation

    Correct answers: A, CAdd a precondition block directly inside the output block checking the bucket's versioning status.; Add a postcondition block inside the aws_s3_bucket resource's lifecycle block checking self.versioning[0].enabled.

    • A. Correct. Terraform 1.2.0 and later support `precondition` blocks within `output` blocks. These blocks allow you to validate the computed output before it is finalized and passed to other modules. If the condition is false, Terraform will produce an error message.
    • B. Incorrect. Unlike resources, `output` blocks do not support `postcondition` blocks. Since an output is the final result of a module evaluation, there is no subsequent action to protect, so only `precondition` is available for gating the value.
    • C. Correct. Resource `lifecycle` blocks support `postcondition` blocks (introduced in v1.2.0). Adding a postcondition to the `aws_s3_bucket` resource allows Terraform to inspect the actual state of the resource after creation. If the versioning status does not match the expectation, Terraform will return an error and mark the resource as failed, which effectively prevents the module from successfully returning outputs.
    • D. Incorrect. The `validation` block meta-argument is specific to `variable` blocks and is used to validate input values. It cannot be used within `output` blocks.
    • E. Incorrect. `check` blocks (introduced in Terraform 1.5) are top-level blocks used for continuous validation and health checks. They are not nested within `output` blocks.

    Subdomain 2.1: Use language features to validate configuration

    14.In Terraform 1.2 and later, custom condition checks (`precondition` and `postcondition` blocks) can be used within the `lifecycle` blocks of which of the following Terraform elements?(Select 2)

    1. A.variable
    2. B.resource
    3. C.provider
    4. D.data
    5. E.module
    Show answer & explanation

    Correct answers: B, Dresource; data

    • A. Variable blocks use a nested `validation` block for input validation. They do not support the `lifecycle` meta-argument or `precondition`/`postcondition` blocks.
    • B. Resource blocks fully support the `lifecycle` meta-argument, which can include both `precondition` and `postcondition` blocks. Preconditions are checked before an operation (like creation or update), while postconditions are checked after.
    • C. Provider blocks are used to configure the interaction with a specific platform's API and do not support the `lifecycle` meta-argument.
    • D. Data blocks (data sources) support the `lifecycle` meta-argument starting in Terraform 1.2. Specifically, they support `postcondition` blocks to validate that the fetched data meets specific requirements before continuing with the plan or apply.
    • E. Module blocks do not support the `lifecycle` meta-argument. While you can use `depends_on`, `count`, or `for_each` with modules, custom condition checks are handled via `precondition` in `output` blocks or within the resources inside the module itself.

    Subdomain 2.4: Use meta-arguments in configuration

    15.You have two modules in your root configuration: `module "network"` and `module "compute"`. You add the meta-argument `depends_on = [module.network]` to the `module "compute"` block. What is the operational impact of this configuration during a `terraform apply`?

    1. A.Terraform will process the modules concurrently but wait to output the final state until both are complete.
    2. B.All resources inside `module.compute` will be forced to wait until every single resource in `module.network` is fully created or updated.
    3. C.Terraform will throw a syntax error because the `depends_on` meta-argument cannot be used with `module` blocks.
    4. D.Only the resources in `module.compute` that explicitly reference outputs from `module.network` will wait for the network module to finish.
    Show answer & explanation

    Correct answer: BAll resources inside `module.compute` will be forced to wait until every single resource in `module.network` is fully created or updated.

    • A. Incorrect. This describes a delayed output rather than a processing sequence. In reality, the `depends_on` meta-argument explicitly defines an order of operations, preventing Terraform from starting any resource processing in the dependent module until the target module is finished.
    • B. Correct. Using `depends_on` at the module level creates an explicit dependency. This ensures that all resources inside the dependent module (`module.compute`) will wait until every resource in the targeted module (`module.network`) has been fully created or updated before the dependent resources begin their lifecycle.
    • C. Incorrect. Since Terraform version 0.13, the `depends_on` meta-argument is fully supported on module blocks. It is a valid construct used to express cross-module ordering requirements that may not be captured via implicit data references.
    • D. Incorrect. This describes the behavior of implicit dependencies (referencing outputs). Using `depends_on` on the module block creates a broad dependency that affects every resource within that module, regardless of whether a specific resource references an output from the other module.

    Domain 3: Develop collaborative Terraform workflows

    Subdomain 3.3: Use the Terraform workflow in automation

    16.Your team is implementing a strict GitOps workflow. Reviewers must see the exact infrastructure changes that will be applied before approving a Pull Request. Once merged, the pipeline must apply those exact changes, guaranteeing no drift occurs between the PR approval and the merge. Which two practices must be implemented in the CI/CD pipeline to achieve this?(Select 2)

    1. A.The PR pipeline must run `terraform plan -out=tfplan` and upload the `tfplan` file as an artifact.
    2. B.The merge pipeline must run `terraform apply -auto-approve` without referencing a plan file.
    3. C.The merge pipeline must download the `tfplan` artifact and run `terraform apply tfplan`.
    4. D.The PR pipeline must run `terraform apply -target=plan` to lock the state.
    5. E.The merge pipeline must run `terraform plan -detailed-exitcode` before applying.
    Show answer & explanation

    Correct answers: A, CThe PR pipeline must run `terraform plan -out=tfplan` and upload the `tfplan` file as an artifact.; The merge pipeline must download the `tfplan` artifact and run `terraform apply tfplan`.

    • A. Correct. Running `terraform plan -out=tfplan` generates a binary plan file that captures the exact state of the configuration and infrastructure at that moment. Uploading this as an artifact ensures that reviewers see the precise changes that will be applied and that the same plan can be used later.
    • B. Incorrect. Running `terraform apply` without referencing a plan file forces Terraform to generate a new plan at execution time. This new plan may include changes that were not present or reviewed during the PR stage if the infrastructure or state changed in the interim.
    • C. Correct. By downloading the plan artifact and running `terraform apply tfplan`, the pipeline executes the exact actions reviewed and approved in the PR. This prevents 'drift' between the time of approval and the time of merge, as Terraform will only perform the actions contained within the binary plan file.
    • D. Incorrect. The `-target` flag is used for resource targeting and does not accept 'plan' as a valid argument in this context. Additionally, applying changes during the PR pipeline contradicts the GitOps principle where changes are only applied after approval and merge.
    • E. Incorrect. The `-detailed-exitcode` flag is used to return specific exit codes based on whether there are changes, but it does not ensure that the applied changes match the reviewed ones. It only reports the status of a fresh plan.

    Subdomain 3.2: Configure remote state

    17.Your enterprise security team mandates that all Terraform state files stored in AWS S3 must be encrypted at rest using a customer-managed KMS key, and accidental deletion or overwriting of state must be recoverable. Which two configurations are required to meet these security mandates?(Select 2)

    1. A.Set `encrypt = true` and specify `kms_key_id` in the `backend "s3"` block.
    2. B.Enable Object Versioning on the target S3 bucket.
    3. C.Set `prevent_destroy = true` inside the `backend "s3"` block.
    4. D.Configure a DynamoDB table with Point-in-Time Recovery (PITR) enabled.
    5. E.Use the `terraform state pull` command to manually back up the state before every apply.
    6. F.Set `acl = "private"` in the `backend "s3"` block to prevent unauthorized deletion.
    Show answer & explanation

    Correct answers: A, BSet `encrypt = true` and specify `kms_key_id` in the `backend "s3"` block.; Enable Object Versioning on the target S3 bucket.

    • A. Specifying `kms_key_id` along with `encrypt = true` in the S3 backend configuration instructs Terraform to use Server-Side Encryption with AWS KMS (SSE-KMS) using the provided customer-managed key. This satisfies the enterprise mandate for encryption at rest using a CMK.
    • B. Enabling Object Versioning on the S3 bucket is the AWS-native mechanism to ensure that previous versions of an object (the state file) are retained. This allows for recovery in the event of accidental deletion or overwriting, directly addressing the recoverability requirement.
    • C. The `prevent_destroy` lifecycle meta-argument is used within resource blocks to prevent Terraform from destroying infrastructure. It is not a valid parameter within the `backend "s3"` block and cannot protect the state file object itself.
    • D. A DynamoDB table is used for state locking and consistency. While PITR (Point-in-Time Recovery) protects the DynamoDB table data, it does not provide recoverability for the state file stored in S3, nor does it handle S3 encryption.
    • E. Using `terraform state pull` is an operational manual process. It is not a scalable or secure configuration for meeting enterprise mandates regarding automatic recoverability or encryption at rest.
    • F. Setting the Access Control List (ACL) to `private` is a basic security best practice for access control, but it does not fulfill the specific mandates for KMS encryption or version-based recoverability.

    Subdomain 3.2: Configure remote state

    18.You are moving an existing Terraform project from an `azurerm` backend to an `s3` backend. You update the `backend` block in your `terraform` configuration block. When you run `terraform init`, Terraform detects the change. You want to initialize the new backend but ignore the existing state in Azure, starting completely fresh in S3. Which command achieves this?

    1. A.terraform init -migrate-state
    2. B.terraform init -reconfigure
    3. C.terraform init -force-copy
    4. D.terraform init -backend=false
    Show answer & explanation

    Correct answer: Bterraform init -reconfigure

    • A. Incorrect. The -migrate-state flag attempts to migrate the state from the current (Azure) backend to the new backend. This is used when you want to preserve your existing state, rather than ignoring it to start fresh.
    • B. Correct. The -reconfigure flag instructs Terraform to ignore any previous backend configuration and state migration options. It re-initializes the backend using the new configuration as if it were a clean slate, which is the correct way to switch backends while ignoring existing state.
    • C. Incorrect. The -force-copy flag is used to bypass the interactive prompt during migration to automatically copy the state from the old backend to the new one. This would transfer the Azure state to S3, which is the opposite of starting fresh.
    • D. Incorrect. The -backend=false flag disables backend initialization entirely. While this avoids copying state, it also prevents Terraform from configuring the S3 backend for future use.

    Subdomain 3.4: Share data across configurations and workspaces

    19.When configuring a `terraform_remote_state` data source to read outputs from another configuration, which argument is strictly required to specify the storage mechanism where the target state file is located?

    1. A.backend
    2. B.config
    3. C.workspace
    4. D.remote_url
    Show answer & explanation

    Correct answer: Bconfig

    • A. The `backend` argument is a mandatory attribute for the `terraform_remote_state` data source, but it only identifies the type of backend (e.g., 's3', 'azurerm', 'remote'). It does not, by itself, provide the specific storage parameters needed to locate the state file.
    • B. The `config` argument is used to provide the backend-specific configuration details (such as bucket name, key path, region, or organization name) that are required to identify the exact location of the target state file and establish a connection to it.
    • C. The `workspace` argument is an optional parameter used to specify a specific workspace within the remote state. While it helps narrow down the state data, it is not the argument used to define the primary storage mechanism configuration.
    • D. The `remote_url` argument does not exist for the `terraform_remote_state` data source. Storage locations and endpoints are defined within the backend-specific keys of the `config` block.

    Subdomain 3.4: Share data across configurations and workspaces

    20.When using the `terraform_remote_state` data source to read data from another Terraform configuration, which of the following values can be retrieved?

    1. A.Any resource attribute defined anywhere in the target state file.
    2. B.Only the root-level outputs defined in the target configuration.
    3. C.Both root-level outputs and child module-level outputs.
    4. D.Input variables and root-level outputs of the target configuration.
    Show answer & explanation

    Correct answer: BOnly the root-level outputs defined in the target configuration.

    • A. Incorrect. Although resource attributes are stored in the state file, the `terraform_remote_state` data source only exposes values that the target configuration has explicitly defined as root-level outputs. It does not provide arbitrary or direct access to internal resource attributes or the full state structure.
    • B. Correct. The `terraform_remote_state` data source retrieves the state of a remote configuration and specifically exposes its root-level outputs. These outputs act as the explicit interface for sharing data between different Terraform configurations or workspaces.
    • C. Incorrect. Outputs from child modules are not directly accessible through this data source. If data from a child module needs to be shared, the root module of that configuration must explicitly re-export that value as a root-level output.
    • D. Incorrect. Input variables are configuration-level inputs and are not stored as part of the accessible output map in the state file. Only root-level outputs declared in the configuration are available for retrieval via this data source.

    Subdomain 3.1: Manage the Terraform binary, providers, and modules using version constraints

    21.Your root module contains the constraint `required_version = ">= 1.2.0"`. You attempt to run `terraform init` using the Terraform CLI version `1.1.9`. What is the exact behavior of Terraform in this scenario?

    1. A.Terraform produces a fatal error stating the running version does not match the required version.
    2. B.Terraform automatically downloads the 1.2.0 binary and executes the command.
    3. C.Terraform initializes successfully but outputs a warning about the version mismatch.
    4. D.Terraform ignores the constraint during init but fails during terraform apply.
    Show answer & explanation

    Correct answer: ATerraform produces a fatal error stating the running version does not match the required version.

    • A. Terraform checks the `required_version` constraint during the initialization of any command. If the running CLI version (1.1.9) does not satisfy the constraint (>= 1.2.0), Terraform produces a fatal diagnostic error and exits immediately to prevent potential compatibility issues or state corruption.
    • B. Terraform CLI does not have a built-in mechanism to automatically download, install, or switch between different versions of its own binary. While external tools like `tfenv` or `tenv` can perform this task, the Terraform binary itself will only enforce the constraint and exit with an error.
    • C. The `required_version` setting is a strict constraint, not a suggestion. A version mismatch results in a hard error that halts execution, rather than a warning that allows the initialization process to complete.
    • D. Terraform validates the `required_version` constraint early in the execution of almost all commands, including `terraform init`. It does not wait until the `apply` phase to enforce this check; it fails immediately during the initialization process.

    Domain 4: Create, maintain, and use Terraform modules

    Subdomain 4.1: Create a module

    22.You are authoring a standardized S3 bucket module for your organization. You need to ensure that the `bucket_name` variable provided by the user starts with the prefix `corp-` and is at least 10 characters long. If the user provides an invalid name, Terraform should fail immediately during the plan phase with a custom error message. Which approach is the most appropriate?

    1. A.Use a precondition block inside the aws_s3_bucket resource to validate the variable.
    2. B.Use a validation block inside the variable "bucket_name" definition with a condition that checks the regex and length.
    3. C.Define a locals block with a try() function to force a failure if the conditions are not met.
    4. D.Use a check block in the module to validate the variable and output a warning.
    Show answer & explanation

    Correct answer: BUse a validation block inside the variable "bucket_name" definition with a condition that checks the regex and length.

    • A. Resource precondition blocks are intended to assert properties about a resource's configuration or state, often involving data sources or other resources. While they can be evaluated during the plan phase if the values are known, they are not the idiomatic location for validating module input variables.
    • B. Variable validation blocks are the native and recommended mechanism for enforcing constraints on input variables. They support logic such as regex and length checks, and they specifically allow for a custom error message that triggers a failure during the plan phase if the input is invalid.
    • C. Using locals or the try() function to force failures is an outdated, non-idiomatic approach (common before Terraform 0.13). It lacks the structured error reporting and clarity provided by dedicated validation blocks.
    • D. The check block (introduced in Terraform 1.5) is designed for continuous validation of functional requirements after infrastructure is applied. Crucially, check blocks only emit warnings and do not stop the plan or apply process, making them unsuitable for this requirement.

    Subdomain 4.2: Use a module in configuration

    23.A developer is referencing a module hosted in a private Git repository. They want to ensure that the configuration only uses versions of the module in the `2.x` family, so they write the following code: module "app" { source = "git::https://github.com/example/terraform-aws-app.git" version = "~> 2.0" } When running `terraform init`, Terraform throws an error. What is the reason for this error?

    1. A.The `version` argument is only supported for modules installed from a module registry, not for Git sources.
    2. B.The version constraint `~> 2.0` is invalid syntax; it must be written as `>= 2.0, < 3.0`.
    3. C.Git tags must be explicitly prefixed with `v` in the version argument (e.g., `version = "~> v2.0"`).
    4. D.The `source` URL is missing the `.git` extension at the end of the repository path.
    Show answer & explanation

    Correct answer: AThe `version` argument is only supported for modules installed from a module registry, not for Git sources.

    • A. Correct. The `version` argument is specifically reserved for modules sourced from a Terraform module registry (public or private). When sourcing modules directly from Version Control Systems (VCS) like Git, the version (branch, tag, or commit SHA) must be specified within the `source` string using the `ref` query parameter, such as `?ref=v2.0.0`.
    • B. Incorrect. The pessimistic constraint syntax `~> 2.0` is valid Terraform syntax (interpreted as `>= 2.0, < 3.0`). The error occurs because the `version` argument is being used with a non-registry source, not because of the syntax of the constraint.
    • C. Incorrect. While prefixing Git tags with `v` is a common convention, it is not a technical requirement of Terraform. Furthermore, when using Git as a source, you refer to tags via the `ref` parameter in the `source` URL, not via the `version` argument.
    • D. Incorrect. The provided `source` URL already includes the `.git` extension. Even if it were missing, Terraform can often infer the type, and the lack of an extension would not cause a specific error related to the `version` argument.

    Subdomain 4.4: Refactor an existing configuration into modules

    24.You have refactored a Terraform configuration by moving an aws_db_instance resource from the root module into a child module named database. A root module output that previously referenced the resource directly is now failing. What is the correct way to expose the database endpoint in the root module?

    1. A.Update the root output to reference `module.database.aws_db_instance.main.endpoint` directly.
    2. B.Create an output in the `database` child module that exposes the endpoint, and update the root output to reference `module.database.<child_output_name>`.
    3. C.Use a `moved` block to move the output from the root module to the child module.
    4. D.Do nothing; Terraform automatically forwards all resource attributes from child modules to the root module outputs.
    Show answer & explanation

    Correct answer: BCreate an output in the `database` child module that exposes the endpoint, and update the root output to reference `module.database.<child_output_name>`.

    • A. Resource attributes defined within a child module are encapsulated and are not directly accessible from the root module using the resource's internal address (e.g., module.database.aws_db_instance.main). Attempting to reach into a module's internal implementation violates Terraform's encapsulation principles.
    • B. The proper pattern for data flow in Terraform is for child modules to explicitly expose values using output blocks. The root (calling) module then accesses those specific values via the syntax module.<MODULE_NAME>.<OUTPUT_NAME>. This maintains a clean interface between modules.
    • C. The moved block is used to record the refactoring of resource or module addresses within the state file to prevent unnecessary destruction and recreation of infrastructure. It is not used to facilitate the passing of data between modules or to resolve reference errors in output configurations.
    • D. Terraform does not automatically forward resource attributes from child modules to the parent module. To maintain encapsulation and predictability, only attributes explicitly defined in an 'output' block are accessible to the calling module.

    Subdomain 4.4: Refactor an existing configuration into modules

    25.You are refactoring a Terraform configuration where an `aws_security_group` named `db_sg` was previously located inside `module.app`. You have now moved the resource definition into `module.db`. Both modules are called directly from the root module. How should you use a `moved` block to ensure Terraform migrates the state without recreating the resource?

    1. A.Place it in `module.app`: `moved { from = aws_security_group.db_sg; to = module.db.aws_security_group.db_sg }`
    2. B.Place it in `module.db`: `moved { from = module.app.aws_security_group.db_sg; to = aws_security_group.db_sg }`
    3. C.Place it in the root module: `moved { from = module.app.aws_security_group.db_sg; to = module.db.aws_security_group.db_sg }`
    4. D.Cross-module moves are not supported by `moved` blocks; you must use `terraform state mv`.
    Show answer & explanation

    Correct answer: CPlace it in the root module: `moved { from = module.app.aws_security_group.db_sg; to = module.db.aws_security_group.db_sg }`

    • A. Incorrect. In a `moved` block, the `to` address must be relative to the module where the block is defined. Since `module.db` is a sibling, not a child of `module.app`, it cannot be addressed from within `module.app`.
    • B. Incorrect. A `moved` block cannot reference sibling or parent modules. Addresses in the `from` and `to` arguments are always relative to the module instance containing the block. Since `module.app` is a sibling of `module.db`, it is not accessible from within the code of `module.db`.
    • C. Correct. When moving resources between sibling modules, the `moved` block must be placed in the common parent module (in this case, the root module). From the root module's perspective, both `module.app` and `module.db` are accessible, and their respective resources can be referenced using the `module.<NAME>.<RESOURCE>` syntax.
    • D. Incorrect. Terraform version 1.1 and later supports refactoring across modules using `moved` blocks. While `terraform state mv` is still a valid manual alternative, `moved` blocks are the preferred method as they are declarative and part of the configuration code.

    Subdomain 4.3: Refactor a module and use module versioning

    26.You are the author of a widely used Terraform module published to a private Terraform Cloud registry. You need to refactor the module to rename a required input variable from `server_name` to `instance_name` to align with company naming standards. You also rename the internal `aws_instance.web` resource to `aws_instance.app`. Which two actions must you take to implement this refactor while adhering to semantic versioning and minimizing disruption for consumers?(Select 2)

    1. A.Increment the major version number of the module (e.g., from 1.4.2 to 2.0.0).
    2. B.Increment the minor version number of the module (e.g., from 1.4.2 to 1.5.0).
    3. C.Include a `moved` block mapping `aws_instance.web` to `aws_instance.app`.
    4. D.Include a `moved` block mapping `var.server_name` to `var.instance_name`.
    5. E.Instruct consumers to run `terraform state rm` before upgrading the module.
    Show answer & explanation

    Correct answers: A, CIncrement the major version number of the module (e.g., from 1.4.2 to 2.0.0).; Include a `moved` block mapping `aws_instance.web` to `aws_instance.app`.

    • A. Correct. Renaming a required input variable is a breaking change to the module's public API. According to Semantic Versioning (SemVer) principles, breaking changes require a major version increment to signal incompatibility to consumers and prevent accidental breakage during automated updates.
    • B. Incorrect. A minor version increment is reserved for adding functionality in a backward-compatible manner. Since renaming a required variable forces the consumer to change their code, it is not backward-compatible.
    • C. Correct. Using a `moved` block (introduced in Terraform 1.1) allows the provider to declaratively signal that a resource's address has changed. This allows Terraform to update the state file automatically without destroying and recreating the resource, minimizing disruption for the consumer.
    • D. Incorrect. `moved` blocks are used for objects tracked in the Terraform state, such as resources, modules, and outputs. They cannot be used to map or alias input variables; variable renames must be handled by the user in their calling configuration.
    • E. Incorrect. Using `terraform state rm` is a manual and disruptive process that removes resources from state management, likely leading to the recreation of the resource or configuration drift. Using a `moved` block is the recommended, automated alternative.

    Domain 5: Configure and use Terraform providers

    Subdomain 5.2: Configure providers, including aliasing, versioning, sourcing, and managing upgrades

    27.In a Terraform configuration, the `required_providers` block specifies a version constraint for the `azurerm` provider as `~> 3.45.2`. Which of the following provider versions satisfies this constraint?

    1. A.3.45.1
    2. B.3.45.9
    3. C.3.46.0
    4. D.4.0.0
    Show answer & explanation

    Correct answer: B3.45.9

    • A. Incorrect. The constraint `~> 3.45.2` requires versions to be greater than or equal to the specified version. 3.45.1 is below the minimum allowed version of 3.45.2.
    • B. Correct. The `~>` operator (pessimistic constraint operator) allows only the rightmost version component to increment. For a three-segment version like `3.45.2`, this means it allows versions `>= 3.45.2` and `< 3.46.0`. 3.45.9 falls within this range.
    • C. Incorrect. When using `~>` with a three-part version number, the first two parts (3.45) are locked. The constraint allows any patch version within 3.45, but excludes 3.46.0 or higher.
    • D. Incorrect. Version 4.0.0 is a major version upgrade and falls outside the range permitted by `~> 3.45.2`, which restricts updates to patch-level increments within the 3.45 minor version.

    Subdomain 5.3: Manage provider authentication

    28.A developer has a personal Google Cloud identity but needs Terraform to provision resources as a highly privileged Service Account. The security team prohibits downloading Service Account JSON keys. The developer decides to use Service Account impersonation. Which two configurations are required to achieve this securely?(Select 2)

    1. A.The developer's personal identity must be granted the roles/iam.serviceAccountTokenCreator role on the target service account.
    2. B.The developer must download the JSON key for the target service account and reference it in the provider block.
    3. C.The impersonate_service_account argument must be set in the google provider block.
    4. D.The developer must set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the target service account's email address.
    5. E.The target service account must have a static password configured in Cloud IAM.
    Show answer & explanation

    Correct answers: A, CThe developer's personal identity must be granted the roles/iam.serviceAccountTokenCreator role on the target service account.; The impersonate_service_account argument must be set in the google provider block.

    • A. To impersonate a service account, the source identity (the developer) must have the `roles/iam.serviceAccountTokenCreator` role on the target service account. This permission allows the identity to generate short-lived OAuth2 access tokens for the account.
    • B. Downloading a JSON key is explicitly prohibited by the security team in this scenario. Furthermore, impersonation is specifically used as an alternative to long-lived JSON keys to improve security and reduce the risk of credential leakage.
    • C. The `google` provider includes a built-in `impersonate_service_account` argument. When this is set to the email of the target service account, Terraform will automatically request short-lived credentials for that account using the developer's base credentials.
    • D. The `GOOGLE_APPLICATION_CREDENTIALS` environment variable is intended to point to a local file path containing a JSON key. It cannot be set to an email address. For impersonation, Terraform typically uses Application Default Credentials (ADC) from the developer's environment (e.g., via `gcloud auth application-default login`).
    • E. Google Cloud service accounts do not use static passwords for authentication; they rely on cryptographic keys or token-based mechanisms like OAuth2 and OpenID Connect.

    Subdomain 5.1: Understand Terraform's plugin-based architecture

    29.A company is migrating its custom Terraform providers from the public HashiCorp registry to a private registry hosted at `registry.example.com`. The custom provider is named `internal-cloud` and belongs to the `mycompany` namespace. How must the `required_providers` block be structured to instruct Terraform Core to pull this provider from the private registry?

    1. A.source = "registry.example.com/mycompany/internal-cloud"
    2. B.source = "mycompany/internal-cloud" with a `registry = "registry.example.com"` argument inside the provider block.
    3. C.url = "https://registry.example.com/mycompany/internal-cloud"
    4. D.source = "hashicorp/internal-cloud" with the `TF_REGISTRY_URL` environment variable set to `registry.example.com`.
    Show answer & explanation

    Correct answer: Asource = "registry.example.com/mycompany/internal-cloud"

    • A. Correct. Terraform provider source addresses use the format `[<HOSTNAME>/]<NAMESPACE>/<TYPE>`. When using a private registry or any registry other than the default HashiCorp Registry (registry.terraform.io), the hostname must be explicitly included as the first segment of the source string. This allows Terraform Core to route the request to the correct API endpoint.
    • B. Incorrect. The `provider` block is used to configure settings for a provider (like credentials or regions), but it cannot be used to define the registry source. There is no `registry` argument supported within the provider configuration block; all source resolution must happen in the `required_providers` block.
    • C. Incorrect. The `required_providers` block uses a `source` attribute, not a `url` attribute. Terraform expects a provider source address, which is a shorthand string that the CLI resolves into a registry API call, rather than a direct HTTPS URL.
    • D. Incorrect. Specifying `hashicorp/internal-cloud` would instruct Terraform to look for the provider in the official HashiCorp namespace on the public registry. Furthermore, `TF_REGISTRY_URL` is not a standard environment variable used to redirect provider lookups. To redirect or mirror providers globally, one would use a CLI configuration file (`.terraformrc` or `terraform.rc`) with a `provider_installation` block, not an environment variable on a per-source basis.

    Subdomain 5.4: Troubleshoot provider errors

    30.Your team uses macOS workstations for local Terraform development. You recently added a new community provider to your configuration, ran `terraform init`, and committed the `.terraform.lock.hcl` file to version control. However, your CI/CD pipeline, which runs on Linux runners, fails during `terraform init` with a checksum mismatch error for the new provider. What are the appropriate ways to resolve this issue?(Select 2)

    1. A.Add `disable_checksum = true` to the provider configuration block in your root module.
    2. B.Run `terraform providers lock -platform=linux_amd64 -platform=darwin_amd64` locally and commit the updated lock file.
    3. C.Delete the `.terraform.lock.hcl` file from the repository and configure the CI/CD pipeline to ignore lock files.
    4. D.The lock file generated on macOS only contains hashes for the Darwin architecture; updating it to include Linux hashes will resolve the mismatch.
    5. E.Configure the CI/CD pipeline to run `terraform init -upgrade` to overwrite the lock file during every run.
    Show answer & explanation

    Correct answers: B, DRun `terraform providers lock -platform=linux_amd64 -platform=darwin_amd64` locally and commit the updated lock file.; The lock file generated on macOS only contains hashes for the Darwin architecture; updating it to include Linux hashes will resolve the mismatch.

    • A. There is no supported `disable_checksum` attribute in provider configuration. Terraform relies on the lock file for integrity and security; bypassing checksum verification is not a valid or recommended feature.
    • B. Running `terraform providers lock` with the `-platform` flag allows you to explicitly add checksums for multiple architectures (e.g., macOS and Linux) to the `.terraform.lock.hcl` file. Committing this updated file ensures the CI/CD environment can verify the provider binary.
    • C. Deleting or ignoring the lock file removes the guarantees of reproducibility and security. It is a best practice to keep the lock file in version control to ensure all environments use the same provider versions.
    • D. The lock file contains per-platform checksums. If `terraform init` is run on macOS, it may only capture the checksum (specifically the h1 hash) for the Darwin architecture. Explicitly updating the lock file to include Linux hashes ensures the CI/CD runner can validate the provider.
    • E. Running `terraform init -upgrade` in CI/CD may resolve the mismatch temporarily but it does not fix the root cause in version control. It also introduces the risk of unintended provider upgrades, breaking the determinism of the pipeline.

    Domain 6: Collaborate on infrastructure as code using HCP Terraform ( multiple-choice only )

    Subdomain 6.1: Analyze the HCP Terraform run workflow

    31.A run is currently in the `applying` state in HCP Terraform. An administrator notices a critical issue with the deployment and clicks 'Cancel Run' in the UI. What is the state of the infrastructure and the Terraform state file immediately after the cancellation completes?

    1. A.The infrastructure is automatically rolled back to its previous state, and the state file remains unchanged.
    2. B.The state file is locked permanently to prevent corruption until HashiCorp support intervenes.
    3. C.The state file is updated to reflect any resources that were successfully provisioned before the cancellation, but the infrastructure may be in an inconsistent state.
    4. D.The run is completely reverted, and no changes are recorded in the state file, requiring a manual state refresh.
    Show answer & explanation

    Correct answer: CThe state file is updated to reflect any resources that were successfully provisioned before the cancellation, but the infrastructure may be in an inconsistent state.

    • A. Incorrect. Terraform and HCP Terraform do not perform automatic rollbacks of resources when an apply operation is canceled. Any resources already created or modified remain in the infrastructure.
    • B. Incorrect. While HCP Terraform uses state locks to prevent concurrent changes during a run, these locks are released once the cancellation process finishes. Permanent locking is not a standard response to a cancellation.
    • C. Correct. When an apply is canceled, Terraform attempts to gracefully shut down. Any resources that were successfully created or updated before the cancellation signal stopped the process are recorded in the state file. This ensures the state matches reality, even if the deployment is now in a partially-applied or inconsistent state.
    • D. Incorrect. Canceling an apply does not revert completed resource operations. The state file is updated incrementally as resources are provisioned; it does not remain empty or require a manual refresh to show the progress made prior to cancellation.

    Subdomain 6.4: Analyze policy as code and governance features

    32.A platform team wants to restrict AWS RDS instance sizes using Sentinel in HCP Terraform. If a developer chooses an unapproved instance size, the run should halt. However, a team lead with appropriate permissions should be able to let the run proceed if there is a valid business justification. Which Sentinel enforcement level should be configured for this policy?

    1. A.hard-mandatory
    2. B.soft-mandatory
    3. C.advisory
    4. D.override-mandatory
    Show answer & explanation

    Correct answer: Bsoft-mandatory

    • A. Incorrect. The hard-mandatory enforcement level requires the policy to pass for the run to continue and does not allow any overrides, even by users with high-level permissions or administrators.
    • B. Correct. The soft-mandatory enforcement level halts the run if the policy fails, but allows users with the 'manage-policy-overrides' permission to override the failure and proceed with the run after providing a justification. This meets the requirement of stopping unapproved sizes while allowing an authorized bypass.
    • C. Incorrect. The advisory enforcement level generates a warning message during the run but does not halt or fail the run, even if the policy evaluation fails. It is used for informative purposes rather than enforcement.
    • D. Incorrect. 'override-mandatory' is not a valid Sentinel enforcement level in HCP Terraform. The standard levels are advisory, soft-mandatory, and hard-mandatory.

    Subdomain 6.4: Analyze policy as code and governance features

    33.Your platform team manages all OPA policies in a dedicated GitHub repository connected to HCP Terraform via a VCS-backed Policy Set. A team member merges a pull request that updates an OPA policy to allow a new AWS region. However, subsequent Terraform runs in workspaces attached to this Policy Set are still failing with the old policy violation. What is the most likely cause of this issue?

    1. A.OPA policies require a manual terraform apply within the policy repository to push changes to HCP Terraform.
    2. B.The Policy Set in HCP Terraform is configured to track a specific branch or tag that was not updated by the pull request.
    3. C.HCP Terraform caches OPA policies for 24 hours; the cache must be manually invalidated via the API.
    4. D.The workspace must be destroyed and recreated to pull the latest version of the VCS-backed Policy Set.
    Show answer & explanation

    Correct answer: BThe Policy Set in HCP Terraform is configured to track a specific branch or tag that was not updated by the pull request.

    • A. Policy sets in HCP Terraform are linked to VCS repositories and sync automatically based on the configured branch or tag. There is no concept of running terraform apply inside a policy repository to deploy policies; HCP Terraform fetches the files directly from the source control provider.
    • B. HCP Terraform Policy Sets allow administrators to specify which branch, tag, or commit hash to track. If the Policy Set is configured to track a specific branch (e.g., 'main') but the PR was merged elsewhere, or if it is pinned to a specific tag that was not updated, HCP Terraform will continue to enforce the older version of the policy.
    • C. HCP Terraform does not implement a 24-hour immutable cache for OPA policies. Policies are updated in near real-time via VCS webhooks or polling. If a policy is not updating, it is usually due to a configuration mismatch in the Policy Set settings rather than a cache issue.
    • D. Workspaces do not need to be destroyed and recreated to receive updated Policy Set definitions. Policy evaluation is performed during the 'Plan' phase of a run based on the latest version of the Policy Set associated with the workspace at that time.

    Subdomain 6.3: Manage provider credentials in HCP Terraform

    34.You are configuring Dynamic Provider Credentials for Google Cloud Platform (GCP). You have created a Workload Identity Pool and Provider in GCP. Which environment variable must be set in the HCP Terraform workspace to specify the resource name of the Workload Identity Provider?

    1. A.TFC_GCP_WORKLOAD_PROVIDER_NAME
    2. B.GOOGLE_CREDENTIALS
    3. C.TFC_GCP_RUN_SERVICE_ACCOUNT_EMAIL
    4. D.TFC_GCP_PROVIDER_AUTH
    Show answer & explanation

    Correct answer: ATFC_GCP_WORKLOAD_PROVIDER_NAME

    • A. Correct. TFC_GCP_WORKLOAD_PROVIDER_NAME is the environment variable used to provide the full resource name of the Workload Identity Provider (e.g., projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL/providers/PROVIDER). This enables HCP Terraform to use workload identity federation to authenticate with GCP.
    • B. Incorrect. GOOGLE_CREDENTIALS is the standard variable used to supply a static service account JSON key file. In the context of Dynamic Provider Credentials, this is replaced by OIDC-based authentication.
    • C. Incorrect. TFC_GCP_RUN_SERVICE_ACCOUNT_EMAIL specifies the service account that Terraform should impersonate once authenticated, but it does not specify the resource name of the identity provider itself.
    • D. Incorrect. While TFC_GCP_PROVIDER_AUTH is a required variable (usually set to 'true') to enable the Dynamic Credentials feature for the Google provider, it is not used to specify the resource name of the Workload Identity Provider.

    Subdomain 6.2: Understand HCP Terraform workspaces and their configuration options, including access management

    35.Your security team is implementing a new CI/CD pipeline using GitLab CI to trigger runs in a specific HCP Terraform workspace named `payment-gateway-prod`. To adhere to the principle of least privilege, the pipeline must only be able to interact with this single workspace and no others in the organization. Which of the following actions should you take to generate the appropriate credentials?(Select 2)

    1. A.Generate a User API token for a service account with 'Write' access to the organization.
    2. B.Generate a Team API token for a team that only has access to the `payment-gateway-prod` workspace.
    3. C.Generate a Workspace API token directly from the `payment-gateway-prod` workspace settings.
    4. D.Workspace API tokens can be used to read state from other workspaces if Remote State Sharing is enabled.
    5. E.Workspace API tokens are strictly scoped to perform operations only within the workspace they were generated for.
    Show answer & explanation

    Correct answers: C, EGenerate a Workspace API token directly from the `payment-gateway-prod` workspace settings.; Workspace API tokens are strictly scoped to perform operations only within the workspace they were generated for.

    • A. Incorrect. Generating a User API token for a service account with organization-level 'Write' access grants broad permissions across all workspaces and settings in the organization, which violates the principle of least privilege.
    • B. Incorrect. While a Team API token can be restricted to a single workspace, it is tied to team management and can inadvertently gain access to other workspaces if team permissions change. Workspace tokens are a more direct and granular mechanism for single-workspace access.
    • C. Correct. Generating a Workspace API token from the specific workspace's settings ensures that the credentials are limited only to that workspace, satisfying the least privilege requirement for CI/CD pipelines.
    • D. Incorrect. This statement is factually wrong. Workspace API tokens cannot access state in other workspaces even if state sharing is enabled. Cross-workspace state access requires a token with explicit permissions on the target workspace (usually a User or Team token).
    • E. Correct. This statement accurately identifies the primary security benefit of Workspace API tokens: they are locked to the specific workspace where they were created and cannot perform actions outside of that scope.

    Want the full experience?

    These are just samples. Practice the full HashiCorp Terraform Authoring and Operations Professional question bank in quiz mode — free, no signup, with domain practice and exam simulation.