Terraform Workflow and CLI Quiz
Quiz
terraform init command?terraform init prepares your working directory by downloading provider plugins, initializing the backend, installing modules, and creating/updating the lock file.terraform init prepares your working directory by downloading provider plugins, initializing the backend, installing modules, and creating/updating the lock file.terraform init do?terraform init creates the .terraform/ directory, downloads providers, initializes the backend, downloads modules, and manages the lock file. It does NOT apply infrastructure changes.terraform init creates the .terraform/ directory, downloads providers, initializes the backend, downloads modules, and manages the lock file. It does NOT apply infrastructure changes.terraform init create to store downloaded provider plugins?.terraform/ directory is created during initialization and contains downloaded provider plugins, modules, and workspace information. It should be excluded from version control..terraform/ directory is created during initialization and contains downloaded provider plugins, modules, and workspace information. It should be excluded from version control..terraform/ directory should be committed to version control..terraform/ directory should NOT be committed to version control (add to .gitignore) because it contains downloaded plugins and can be regenerated with terraform init. However, .terraform.lock.hcl should be committed..terraform/ directory should NOT be committed to version control (add to .gitignore) because it contains downloaded plugins and can be regenerated with terraform init. However, .terraform.lock.hcl should be committed.Terraform State File (terraform.tfstate)
The state file is Terraform’s database of managed infrastructure. It serves to:
- Map configuration to real-world resources - Links your .tf code to actual cloud resources
- Track metadata - Stores dependencies and provider information
- Improve performance - Caches attribute values to avoid constant API queries
- Enable collaboration - Allows teams to share infrastructure state
⚠️ Contains sensitive data (passwords, keys) and should never be manually edited.
Did you get it right?
terraform plan, how does Terraform detect state drift?terraform plan _____terraform plan -refresh-only detects drift by refreshing the state without planning any infrastructure changes. To update the state to match reality, use terraform apply -refresh-only.terraform plan -refresh-only detects drift by refreshing the state without planning any infrastructure changes. To update the state to match reality, use terraform apply -refresh-only.terraform plan output indicates a resource will be destroyed and then recreated?-/+ symbol indicates a resource will be replaced (destroyed then recreated). This happens when certain attributes change that require replacement, causing the resource ID to change.-/+ symbol indicates a resource will be replaced (destroyed then recreated). This happens when certain attributes change that require replacement, causing the resource ID to change.‘known after apply’
This appears in plan output when a value cannot be determined until the resource is actually created.
Example:
+ public_ip = (known after apply)This happens because:
- The cloud provider assigns the value (e.g., AWS assigns the public IP)
- Terraform can’t predict what the provider will assign
- The value becomes known only after the resource is created
Common examples: resource IDs, auto-assigned IPs, generated ARNs
Did you get it right?
terraform apply:terraform apply (how many resources can be created simultaneously)?-parallelism flag.-parallelism flag.terraform apply without a saved plan?terraform apply without a saved plan, it re-generates the plan (same as running terraform plan), shows you the changes, and then prompts for approval before applying.terraform apply without a saved plan, it re-generates the plan (same as running terraform plan), shows you the changes, and then prompts for approval before applying.terraform apply, Terraform acquires a state lock to prevent concurrent modifications.terraform apply _____-auto-approve flag skips the interactive approval prompt. Use with caution, especially in production!-auto-approve flag skips the interactive approval prompt. Use with caution, especially in production!terraform fmt command do?terraform fmt formats Terraform configuration files to a canonical style, ensuring consistent formatting. Use terraform fmt -recursive to format all subdirectories.terraform fmt formats Terraform configuration files to a canonical style, ensuring consistent formatting. Use terraform fmt -recursive to format all subdirectories.Provider Dependency Lock File (.terraform.lock.hcl)
Ensures consistent provider versions across team members and environments.
Without lock file:
- Developer A uses AWS provider 5.84.0
- Developer B uses AWS provider 5.85.0 (newer release)
- CI/CD uses AWS provider 5.86.0
- Result: Inconsistent behavior, potential bugs
With lock file:
- All developers use the exact same provider version
- Prevents unexpected changes from provider updates
- Should be committed to version control
Update providers: terraform init -upgrade
Did you get it right?
terraform init -upgrade upgrades providers to the latest version allowed by your version constraints and updates the lock file accordingly.terraform init -upgrade upgrades providers to the latest version allowed by your version constraints and updates the lock file accordingly.terraform plan _____terraform plan -out=tfplan saves the plan to a file. You can then apply this exact plan with terraform apply tfplan, which skips the approval prompt since the plan was already reviewed.terraform plan -out=tfplan saves the plan to a file. You can then apply this exact plan with terraform apply tfplan, which skips the approval prompt since the plan was already reviewed.terraform plan -detailed-exitcode return?-detailed-exitcode, terraform plan returns: 0 (no changes needed), 1 (error occurred), or 2 (changes are present). This is useful in CI/CD pipelines to determine if infrastructure drift exists.-detailed-exitcode, terraform plan returns: 0 (no changes needed), 1 (error occurred), or 2 (changes are present). This is useful in CI/CD pipelines to determine if infrastructure drift exists.terraform state commands DO NOT modify actual cloud infrastructure?terraform state commands only modify the state file, not actual infrastructure. terraform state rm removes from state but doesn’t destroy the resource. Only terraform destroy actually deletes cloud resources.terraform state commands only modify the state file, not actual infrastructure. terraform state rm removes from state but doesn’t destroy the resource. Only terraform destroy actually deletes cloud resources.terraform state rm vs terraform destroy
terraform state rm <resource>
- Removes resource from state file only
- Resource continues to exist in the cloud
- Terraform stops managing it
- Use case: Move resource out of Terraform management
terraform destroy
- Actually deletes resources from the cloud
- Updates state file to reflect deletion
- Resource is permanently removed
- Use case: Clean up infrastructure
⚠️ Critical: state rm doesn’t destroy—it just stops tracking!
Did you get it right?
terraform import brings existing resources into Terraform management. Syntax: terraform import aws_instance.web i-0abc123. You must also add the corresponding configuration to your .tf files.terraform import brings existing resources into Terraform management. Syntax: terraform import aws_instance.web i-0abc123. You must also add the corresponding configuration to your .tf files.terraform apply _____ aws_instance.webterraform apply -replace=aws_instance.web forces Terraform to destroy and recreate the specified resource, even if no configuration changes require it. This replaced the deprecated -taint flag.terraform apply -replace=aws_instance.web forces Terraform to destroy and recreate the specified resource, even if no configuration changes require it. This replaced the deprecated -taint flag.terraform init?terraform init when first using a directory, adding providers, changing backends, cloning a repo, or upgrading provider versions. You don’t need to run it every time or after just modifying resources.terraform init when first using a directory, adding providers, changing backends, cloning a repo, or upgrading provider versions. You don’t need to run it every time or after just modifying resources.~ symbol mean in terraform plan output?~ symbol indicates an in-place update—the resource will be modified without destroying and recreating it. The resource ID stays the same.~ symbol indicates an in-place update—the resource will be modified without destroying and recreating it. The resource ID stays the same.Terraform Workspaces
Workspaces are named state instances for the same configuration, allowing you to manage multiple environments.
Commands:
terraform workspace list- Show all workspacesterraform workspace new staging- Create workspaceterraform workspace select prod- Switch workspaceterraform workspace show- Show current workspace
Use case: Same code, different environments (dev/staging/prod)
- Each workspace has its own state file
- Easy to switch between environments
⚠️ Note: For production use, many teams prefer separate directories/repos rather than workspaces for better isolation.
Did you get it right?
terraform.tfstate.backup before updating the state file. This provides a safety net if the state gets corrupted.terraform.tfstate.backup before updating the state file. This provides a safety net if the state gets corrupted.terraform force-unlock <lock-id> can force-release a stuck state lock. Use with extreme caution—only when you’re certain no one else is running Terraform, as forcing unlock during an active operation can corrupt the state.terraform force-unlock <lock-id> can force-release a stuck state lock. Use with extreme caution—only when you’re certain no one else is running Terraform, as forcing unlock during an active operation can corrupt the state.terraform show -json displays the current state in JSON format. This is useful for parsing state data in scripts or for integration with other tools.terraform show -json displays the current state in JSON format. This is useful for parsing state data in scripts or for integration with other tools.terraform state _____terraform state list shows all resources currently managed in the state file. This is useful for getting an overview of what Terraform is managing.terraform state list shows all resources currently managed in the state file. This is useful for getting an overview of what Terraform is managing.terraform validate command?terraform validate checks the syntax and internal consistency of your configuration files. It validates the configuration without accessing remote state or provider APIs.terraform validate checks the syntax and internal consistency of your configuration files. It validates the configuration without accessing remote state or provider APIs.Scope of Drift Detection
CAN DETECT (Managed Resources): ✅ Changes to resources in the state file ✅ Modified attributes (e.g., instance type changed from t2.micro to t2.small) ✅ Deleted resources that Terraform manages ✅ Tags added/removed from managed resources
CANNOT DETECT (Unmanaged Resources): ❌ New resources created outside Terraform ❌ Resources in other regions not managed by Terraform ❌ Resources created by other teams/tools
Key Point: Terraform only queries resources listed in its state file. It does NOT scan your entire cloud account.
Solution: Use terraform import for existing resources or cloud inventory tools to discover unmanaged resources.
Did you get it right?
terraform apply _____ aws_instance.webterraform apply -target=aws_instance.web applies changes only to the specified resource and its dependencies. Use sparingly—targeting can cause inconsistencies.terraform apply -target=aws_instance.web applies changes only to the specified resource and its dependencies. Use sparingly—targeting can cause inconsistencies.terraform state show aws_instance.web displays detailed information about a specific resource from the state file, including all its attributes.terraform state show aws_instance.web displays detailed information about a specific resource from the state file, including all its attributes.-refresh=false flag skips the refresh step, meaning Terraform won’t query the cloud provider and will use only what’s in the state file. This is faster but won’t detect drift.-refresh=false flag skips the refresh step, meaning Terraform won’t query the cloud provider and will use only what’s in the state file. This is faster but won’t detect drift.terraform state rm on it?terraform state rm removes the resource from the state file only—the actual resource continues to exist in the cloud. Terraform simply stops managing it. The resource is NOT destroyed.terraform state rm removes the resource from the state file only—the actual resource continues to exist in the cloud. Terraform simply stops managing it. The resource is NOT destroyed.State Locking
Prevents concurrent state modifications that could corrupt the state file.
How it works:
- User A runs
terraform apply - Terraform acquires a lock (e.g., in DynamoDB)
- User B tries to run
terraform apply - User B gets an error: “state is locked by User A”
- User A completes, releases the lock
- User B can now proceed
Backends with locking:
- S3 (with DynamoDB table)
- Terraform Cloud
- Azure Blob Storage
- Google Cloud Storage
Local backend: No locking support (not safe for teams)
Force unlock (emergency only): terraform force-unlock <lock-id>
Did you get it right?