Visit here for our full HashiCorp Terraform Associate exam dumps and practice test questions.
Question 136:
What is the purpose of the terraform.tfvars file?
A) To store provider plugin binaries
B) To automatically load variable values without explicitly specifying them on the command line
C) To define resource configurations
D) To store Terraform state
Answer: B
Explanation:
The terraform.tfvars file provides a standardized location for defining variable values that Terraform automatically loads during execution without requiring command-line flags or environment variables. This convention simplifies variable management by centralizing values in a well-known file that team members understand and tools can reliably locate for configuration injection.
Terraform’s variable loading hierarchy automatically reads terraform.tfvars and terraform.tfvars.json files from the current directory during plan and apply operations. These files use HCL or JSON syntax to assign values to input variables declared in variable blocks. The automatic loading eliminates the need for -var or -var-file flags reducing command complexity and ensuring consistent variable application across team members.
Variable file best practices include excluding terraform.tfvars from version control when it contains environment-specific or sensitive values, using terraform.tfvars.example files committed to repositories as templates showing required variables without exposing actual values, and implementing separate variable files for different environments like dev.tfvars, staging.tfvars, and prod.tfvars loaded explicitly with -var-file flags.
File format supports simple assignments for primitives, list literals using square brackets, map literals using curly braces, and complex nested structures for object variables. Comments document variable purposes and valid value ranges. The file serves as the primary interface between infrastructure code and deployment-specific configuration enabling the same Terraform code to deploy across environments with different variable values.
Provider plugins reside in the .terraform directory rather than tfvars files. Resource configurations belong in .tf files. State stores in separate state files. The terraform.tfvars file specifically addresses automatic variable value loading providing convenient configuration management essential for maintainable infrastructure code with clear separation between code and data.
Question 137:
Which backend type stores Terraform state locally on disk?
A) s3
B) remote
C) local
D) azurerm
Answer: C
Explanation:
The local backend stores Terraform state files on the local filesystem typically in the terraform.tfstate file within the working directory. This default backend requires no additional configuration and provides the simplest state management option suitable for individual development, learning scenarios, and small projects without collaboration requirements.
Local backend behavior creates and updates the state file in the current directory during Terraform operations. The file contains JSON-formatted data describing all managed resources including their attributes, dependencies, and metadata. Terraform reads this file during plan operations to understand current infrastructure state and writes updates during apply operations to record changes. The local storage approach requires no external dependencies or network connectivity.
Limitations of local backends include lack of collaboration support where multiple team members cannot safely work with shared state, no built-in locking preventing concurrent operations that could corrupt state, limited disaster recovery without manual backup procedures, and security concerns as sensitive values in state are unencrypted on disk. These limitations make local backends inappropriate for team environments and production infrastructure.
Migration from local to remote backends occurs when projects mature beyond individual development. The terraform init command with -migrate-state flag transfers existing local state to newly configured remote backends like S3, Azure Storage, or Terraform Cloud. This migration enables team collaboration, state locking, and enhanced security while preserving existing resource tracking.
S3, remote, and azurerm backends store state remotely in AWS S3, Terraform Cloud, or Azure Storage respectively. The local backend specifically provides filesystem-based state storage serving as the default option and initial development choice before projects transition to remote backends supporting collaboration and enhanced operational requirements.
Question 138:
What is the purpose of the count meta-argument in Terraform?
A) To count the number of resources in the state file
B) To create multiple instances of a resource based on a numeric value
C) To calculate the cost of infrastructure
D) To track how many times Terraform has been run
Answer: B
Explanation:
The count meta-argument creates multiple instances of a resource or module based on a numeric value, enabling dynamic infrastructure scaling where resource quantities depend on variables, conditional logic, or computed values. This capability eliminates configuration duplication by defining resources once then creating multiple instances through parameterization.
Count syntax uses the count argument within resource blocks accepting integer values specifying how many instances to create. Each instance receives a unique index from zero to count minus one accessible through count.index within the resource block. This index enables parameterizing each instance differently using list indexing, calculations, or conditional expressions based on instance position.
Common patterns include creating multiple similar resources like virtual machines, subnets, or security rules with variations based on count.index, conditional resource creation using count with ternary expressions evaluating to zero or one based on boolean conditions, and scaling resources dynamically where count derives from variable values, data source results, or computed expressions.
Resource references to counted resources produce lists containing all instances requiring indexing to access specific instances. For example, aws_instance.web creates a list of instances accessed individually as aws_instance.web[0] or collectively using splat expressions like aws_instance.web[*].id. This list behavior affects how other resources reference counted resources requiring explicit index specification or iteration.
The meta-argument does not count existing resources, calculate costs, or track execution history. Those functions belong to state inspection commands, cost estimation tools, and execution logging respectively. The count meta-argument specifically enables multiple resource instance creation providing declarative scaling essential for managing infrastructure at varying scales through parameterized configuration.
Question 139:
How do you specify that a resource should be created before another resource is destroyed during replacement?
A) Using the prevent_destroy lifecycle argument
B) Using the create_before_destroy lifecycle argument
C) Using the ignore_changes lifecycle argument
D) Using depends_on meta-argument
Answer: B
Explanation:
The create_before_destroy lifecycle argument modifies Terraform’s default replacement behavior to create new resources before destroying old ones rather than destroying first then creating. This ordering prevents downtime during resource replacement ensuring new resources are operational before old resources terminate, which is critical for maintaining service availability during infrastructure updates.
Default Terraform replacement behavior destroys existing resources before creating replacements potentially causing service interruptions during the transition period. For stateful resources, load-balanced services, or resources with external dependencies, this destruction-first approach creates unacceptable downtime. The create_before_destroy argument reverses this order ensuring continuous service availability throughout replacement operations.
Implementation requires adding lifecycle blocks within resource configurations specifying create_before_destroy equals true. This setting affects only that specific resource and its replacement behavior. Terraform creates the new resource, verifies successful creation, updates references to point to the new resource, then destroys the old resource. This sequence maintains at least one functional resource throughout the replacement process.
Considerations include potential temporary resource duplication where both old and new resources exist simultaneously potentially doubling costs briefly or requiring additional capacity, naming conflicts if resource names must be unique requiring name generation or sequential suffixes, and dependency chains where related resources might need coordinated lifecycle settings ensuring consistent replacement ordering across dependent resources.
The prevent_destroy argument prevents resource destruction entirely. The ignore_changes argument excludes specific attributes from change detection. The depends_on meta-argument controls dependency ordering. The create_before_destroy lifecycle argument specifically controls replacement ordering ensuring new resources exist before old resources are removed essential for zero-downtime infrastructure updates.
Question 140:
Which command shows the current Terraform version?
A) terraform -v
B) terraform version
C) terraform –version
D) All of the above
Answer: D
Explanation:
All three command variations display the current Terraform version including terraform -v, terraform version, and terraform –version. This flexibility accommodates different user preferences and conventions from other command-line tools where version flags vary across implementations. The output includes Terraform core version, platform information, and installed provider plugin versions.
Version information appears in standardized format showing major, minor, and patch version numbers following semantic versioning conventions. Additional metadata includes the Git commit identifier for the specific build, whether the build includes development features, and the operating system and architecture. Provider plugin versions list each installed provider with its version number and installation location.
Version checking serves multiple purposes including verifying Terraform installation success, confirming version compatibility with configuration requirements, troubleshooting issues where specific versions contain bugs or introduce breaking changes, and documenting execution environments for reproducibility or compliance. Team coordination benefits from version consistency ensuring all members use compatible versions preventing configuration compatibility issues.
Version constraints in configuration specify minimum required Terraform versions using the required_version argument within terraform blocks. These constraints prevent execution with incompatible versions that might interpret configuration differently or lack required features. The constraint format uses comparison operators enabling minimum versions, version ranges, or pessimistic constraints allowing compatible updates while preventing breaking changes.
All three command variations provide identical functionality supporting various user preferences and muscle memory from other tools. Some users prefer short flags like -v, others prefer explicit subcommands like version, and many expect double-dash long form flags following GNU conventions. Terraform supports all approaches ensuring version information remains easily accessible regardless of user preference.
Question 141:
What is the purpose of the ignore_changes lifecycle argument?
A) To prevent Terraform from tracking changes to specific resource attributes
B) To ignore all changes to a resource
C) To skip resource creation
D) To disable state locking
Answer: A
Explanation:
The ignore_changes lifecycle argument instructs Terraform to ignore differences in specific resource attributes during plan operations, preventing Terraform from attempting to revert changes made outside its control. This capability handles scenarios where external systems or manual modifications intentionally change attributes that should not trigger Terraform updates.
The argument accepts a list of attribute names that Terraform should exclude from its change detection logic. During plan operations, Terraform compares current state against configuration as usual but ignores differences in specified attributes treating them as matching regardless of actual values. This behavior prevents Terraform from generating plans to revert external changes that are expected and desired.
Common use cases include autoscaling group sizes where autoscaling policies dynamically adjust instance counts and Terraform should not revert these automatic adjustments, tags managed by external systems where other tools add metadata tags that shouldn’t be removed, and resource attributes modified by configuration management tools or application logic that operates independently from Terraform.
The special value all ignores all attribute changes effectively preventing Terraform from managing the resource after initial creation. This extreme option creates resources then abandons management leaving them to external control. The approach is generally discouraged as it defeats Terraform’s state management purpose but serves edge cases where initial provisioning requires Terraform while ongoing management occurs elsewhere.
The argument does not completely ignore resources, skip creation, or disable locking. Those functions involve different mechanisms. The ignore_changes argument specifically provides selective attribute exclusion from change detection enabling Terraform to manage resources collaboratively with external systems that control specific attributes essential for integration scenarios where multiple management tools coordinate resource lifecycle.
Question 142:
How do you reference a specific element in a list variable?
A)list_name.element_index
B)list_name[element_index]
C)list_name(element_index)
D)list_name{element_index}
Answer: B
Explanation:
List variable elements are accessed using bracket notation with zero-based indexing following the syntax var.list_name[element_index] where element_index is an integer from zero to list length minus one. This standard indexing syntax applies to lists, tuples, and sequences throughout Terraform enabling element extraction for resource parameterization, conditional logic, and computed expressions.
Zero-based indexing means the first element has index zero, second element has index one, and so forth. Negative indices are not supported unlike some programming languages. Out-of-bounds indices cause errors during plan operations requiring bounds checking or use of defensive functions like try or coalesce handling missing indices gracefully.
Common patterns include iterating through lists using count.index to select elements positionally, mapping list elements to resource attributes creating resources with configurations derived from list values, and combining indexing with conditional expressions selecting elements based on logic like var.environment equals production selecting production-specific values from configuration lists.
Advanced indexing includes nested structures where lists contain maps or objects requiring chained access like var.configs[0].subnet_id, dynamic indexing using computed expressions like var.list[var.selected_index] where index comes from another variable, and slicing operations using slice function extracting list subsets though bracket notation itself only accesses single elements.
Dot notation accesses map keys and object attributes rather than list elements. Parentheses indicate function calls. Curly braces define map or object literals. Bracket notation specifically provides list indexing capability essential for working with ordered collections where element position determines meaning and resources need parameterization from list-based configuration data.
Question 143:
What is the recommended way to manage Terraform provider credentials for team environments?
A) Commit credentials to version control
B) Use environment variables or identity-based authentication
C) Hardcode credentials in provider blocks
D) Share credentials through email
Answer: B
Explanation:
Environment variables and identity-based authentication represent the recommended approaches for managing provider credentials in team environments, preventing credential exposure in configuration files while enabling secure authentication across team members. These methods separate credentials from code ensuring security, auditability, and compliance with security best practices.
Environment variables enable credential injection without hardcoding in configuration files. Team members set provider-specific environment variables like AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, GOOGLE_CREDENTIALS, or ARM_CLIENT_ID before running Terraform. This approach keeps credentials outside version control and state files while providing flexible credential management per user or execution environment.
Identity-based authentication eliminates static credentials using cloud provider identity services for authentication. AWS IAM roles for EC2 instances or ECS tasks, Google Cloud service account impersonation, and Azure managed identities authenticate Terraform automatically using infrastructure identity. CI/CD pipelines leverage similar mechanisms using pipeline service principals or OIDC federation avoiding credential storage entirely.
Secret management systems including HashiCorp Vault, AWS Secrets Manager, or similar services provide centralized credential storage with access control, rotation, and auditing. Terraform retrieves credentials dynamically during execution through data sources or provider configurations. Credentials never persist in configuration files, state, or version control. Access policies control which users and systems can retrieve credentials.
Committing credentials to version control exposes secrets to anyone accessing repositories including in history after deletion. Hardcoded credentials in provider blocks suffer similar exposure. Email sharing lacks security and auditability. Environment variables and identity-based authentication specifically address secure team credential management enabling role-based access, audit trails, and secrets protection essential for production infrastructure security.
Question 144:
Which Terraform command reformats configuration files to follow style conventions?
A) terraform validate
B) terraform fmt
C) terraform plan
D) terraform refresh
Answer: B
Explanation:
The terraform fmt command automatically reformats Terraform configuration files to follow canonical style conventions ensuring consistent code formatting across projects and team members. This automated formatting eliminates formatting debates, improves code readability, and maintains consistent style without manual effort or style guide enforcement.
The command processes all Terraform configuration files in the current directory and subdirectories by default adjusting indentation to two spaces, aligning equals signs in assignments, organizing block arguments alphabetically where appropriate, and applying consistent spacing and line breaks. The formatting rules follow HashiCorp’s Terraform style guide representing community standards for readable maintainable configuration.
Command options include -recursive formatting entire directory trees, -check returning non-zero exit codes without modifying files useful for CI pipeline validation ensuring committed code follows formatting standards, -diff displaying formatting changes without applying them for review, and specific file arguments limiting formatting to designated files rather than entire directories.
Integration with development workflows includes pre-commit hooks automatically formatting changed files before commits, editor integrations providing format-on-save functionality, and CI/CD pipeline checks failing builds when unformatted code is committed. These integrations enforce consistent formatting automatically without requiring manual review or correction.
The terraform validate command checks configuration correctness rather than formatting. The terraform plan command generates execution plans. The terraform refresh command updates state. The terraform fmt command specifically provides automatic code formatting ensuring consistent style essential for maintainable codebases where multiple contributors need shared formatting standards without manual formatting effort.
Question 145:
What is the purpose of the for_each meta-argument?
A) To loop through lists only
B) To create multiple resource instances based on a map or set of strings
C) To format code
D) To validate configuration
Answer: B
Explanation:
The for_each meta-argument creates multiple resource instances based on maps or sets of strings enabling more flexible resource creation than count with better resource addressing and clearer intent. This approach provides stable resource addresses that don’t change when collection elements are added, removed, or reordered preventing unnecessary resource recreation during infrastructure updates.
For_each accepts either maps where keys become instance identifiers and values provide instance configuration data, or sets of strings where each string becomes both the identifier and basis for configuration. Each created instance is addressable using the key or string value rather than numeric indices, creating meaningful resource addresses that survive collection modifications without triggering replacements.
The each object provides access to instance-specific data within resource blocks where each.key contains the map key or set element string and each.value contains the map value. These references enable parameterizing resource configurations based on collection data creating resources with varying attributes derived from input maps or sets.
Advantages over count include stable resource addresses where adding or removing map elements doesn’t affect other resources unlike count where index shifts cause unnecessary replacements, clearer intent as keys describe resources meaningfully compared to numeric indices, and better module outputs where resources can be returned as maps with meaningful keys rather than lists requiring index knowledge.
Use cases include creating resources for each subnet in a map of subnet configurations, deploying instances across availability zones where zone names serve as keys, and implementing resources per application component where component names provide natural identifiers. The for_each meta-argument provides superior flexibility compared to count for scenarios requiring stable identifiable resource instances.
Question 146:
What does the terraform state list command display?
A) Terraform version information
B) A list of all resources tracked in the state file
C) Provider plugin versions
D) Execution plan details
Answer: B
Explanation:
The terraform state list command displays a complete list of all resources tracked in the Terraform state file showing resource addresses without detailed attribute information. This inventory capability enables understanding what infrastructure Terraform manages, identifying resources for state manipulation commands, and auditing managed resource scope.
Output format shows fully qualified resource addresses including resource types, names, and module paths for resources within modules. For resources created with count or for_each, the command lists each instance separately with its index or key. The addresses match the format used throughout Terraform enabling direct copying for use in other state commands requiring resource addresses.
Common use cases include verifying resources exist in state after import operations confirming successful state integration, identifying resources before state removal or movement operations, auditing managed infrastructure inventory understanding complete resource scope, and troubleshooting scenarios where understanding current state contents helps diagnose issues.
Filtering capabilities using address patterns limit output to matching resources. For example, filtering for specific resource types shows only those resources, or filtering by module path displays only resources within specific modules. This targeted listing helps navigate large state files with hundreds or thousands of resources focusing on relevant subsets.
The command provides high-level state inventory without detailed attribute information which terraform state show provides for specific resources. This focused listing serves discovery and navigation purposes enabling operators to understand state contents and locate specific resources for detailed inspection or manipulation operations.
Question 147:
How do you pass a list variable value on the command line?
A) -var ‘list_name=[“item1″,”item2”]’
B) -var list_name=item1,item2
C) -var list_name[item1,item2]
D) -var list_name:item1:item2
Answer: A
Explanation:
List variable values are passed on the command line using -var flag with HCL list syntax enclosed in quotes to prevent shell interpretation. The format -var ‘list_name=[“item1″,”item2”]’ provides the list as a string that Terraform parses as HCL recognizing the square bracket list notation and creating the appropriate list variable value.
Quote usage prevents shells from interpreting brackets, commas, or spaces as special characters. Single quotes in Unix-like shells or double quotes in Windows preserve the list syntax literally passing it to Terraform for parsing. Without quotes, shells might expand brackets as globs, interpret spaces as argument separators, or otherwise corrupt the list structure.
Alternative approaches for complex list values include using -var-file flags pointing to variable files containing list definitions avoiding command-line complexity, or setting TF_VAR_list_name environment variables with JSON-formatted list values that Terraform parses automatically. These methods handle complex nested structures more gracefully than command-line strings.
Type considerations require list elements match the variable’s type constraint. String lists need quoted elements, number lists use unquoted numeric values, and complex object lists require full object syntax. Terraform validates list element types during variable assignment raising errors for type mismatches.
The other syntax options shown don’t represent valid Terraform list input formats. Comma separation without brackets parses as strings rather than lists. Bracket syntax without proper HCL structure confuses Terraform. Colon separation doesn’t match any Terraform syntax. The quoted HCL list syntax specifically provides the correct command-line list variable passing format essential for dynamic configuration during execution.
Question 148:
What is the purpose of Terraform provisioners?
A) To define resource configurations
B) To execute scripts or commands during resource creation or destruction
C) To manage state files
D) To validate syntax
Answer: B
Explanation:
Terraform provisioners execute scripts or commands on local or remote machines during resource creation or destruction enabling configuration management, bootstrapping, and cleanup operations that extend beyond provider capabilities. These tools bridge infrastructure provisioning with configuration management handling scenarios where resources require post-creation setup or pre-destruction cleanup.
Provisioner types include local-exec executing commands on the machine running Terraform, remote-exec executing commands on newly created resources over SSH or WinRM connections, and file provisioners copying files to remote resources. Each provisioner type addresses specific scenarios from local script execution to remote configuration and data transfer.
Execution timing defaults to creation where provisioners run after resources are created but before Terraform considers creation complete. The when parameter enables destruction-time provisioners running before resources are destroyed useful for cleanup operations like deregistering from external systems, backing up data, or notifying monitoring systems about resource removal.
Terraform documentation explicitly recommends using provisioners as last resorts when native resource functionality or provider integrations cannot accomplish requirements. Preferred alternatives include using user_data or startup scripts for instance configuration, leveraging configuration management tool integrations, utilizing provider-specific configuration options, or implementing external systems that respond to infrastructure changes through event notifications.
Provisioner limitations include error handling complexity where failures might leave resources in inconsistent states, lack of idempotency requiring careful script design, dependency on network connectivity and credentials for remote provisioners, and challenges with state consistency when provisioners fail. These limitations make provisioners appropriate only when no better alternatives exist for required functionality.
Question 149:
Which Terraform block is used to configure backend settings?
A) provider
B) terraform
C) backend
D) remote_state
Answer: B
Explanation:
Backend configuration occurs within the terraform block using a nested backend block specifying backend type and configuration parameters. This declarative approach centralizes backend settings within Terraform configuration enabling version control, team coordination, and clear documentation of state storage location and behavior.
The terraform block serves as the container for Terraform core settings including required version constraints, required provider specifications, and backend configuration. Backend blocks within terraform blocks name the backend type like s3, azurerm, or remote, and provide backend-specific arguments like bucket names, storage account details, or remote backend URLs.
Backend configuration examples include S3 backends specifying bucket names, key paths, regions, and optional DynamoDB tables for state locking, Azure backends defining storage accounts, container names, and state blob names, and Terraform Cloud backends identifying organizations and workspaces. Each backend type requires specific parameters documented in backend provider documentation.
Configuration restrictions include limiting configurations to a single backend per configuration with backend switching requiring reinitialization, and prohibiting variable interpolation in backend configurations requiring literal values. The literal value requirement prevents bootstrap issues where backend configuration needs resolution before variables are available. Partial backend configuration enables using command-line flags or configuration files during initialization for environment-specific values.
Provider blocks configure providers rather than backends. Backend blocks must nest within terraform blocks. Remote_state is a data source for reading other configurations’ outputs rather than a backend configuration mechanism. The terraform block specifically contains backend configuration providing the centralized location for state storage settings essential for team collaboration and state management.
Question 150:
What is the purpose of the terraform console command?
A) To open a web-based user interface
B) To provide an interactive command-line interface for evaluating expressions
C) To display log files
D) To configure provider settings
Answer: B
Explanation:
The terraform console command provides an interactive read-eval-print loop (REPL) for evaluating Terraform expressions, testing functions, exploring state data, and debugging configuration logic. This development tool enables immediate feedback on expression evaluation without running full plan or apply operations facilitating learning, troubleshooting, and configuration development.
The console loads current state and configuration providing access to all resources, variables, and data sources defined in the working directory. Users enter expressions at the prompt receiving immediate evaluation results. This interactivity enables rapid experimentation with expressions, function testing with sample data, and exploration of complex data structures without modifying configuration or executing plans.
Common use cases include testing interpolation syntax before adding to configuration verifying expressions produce expected values, debugging complex expressions by breaking them into smaller parts and evaluating incrementally, exploring resource attributes by querying state data understanding available resource outputs, and learning Terraform functions by experimenting with different inputs observing resulting outputs.
Expression evaluation includes all Terraform functions enabling testing of string manipulation, collection operations, encoding functions, and filesystem functions. Access to resources through resource syntax like aws_instance.example.id retrieves current attribute values from state. Variable references return configured values. The console provides complete access to configuration context enabling realistic testing.
The console is not a web interface, log viewer, or configuration tool. Those functions belong to other tools or commands. The terraform console command specifically provides interactive expression evaluation creating a development and troubleshooting environment essential for understanding Terraform behavior and developing correct complex expressions without trial-and-error through full plan cycles.