Infrastructure as Code

Terraform (IaC): The LEGO Blueprint for Servers

Updated June 2026
Tech Engineer Blueprint Architecture
Terraform reads text file configurations and builds complex cloud server systems automatically.

Hello, future Cloud Engineers! Today we are discussing Infrastructure as Code (IaC). Before IaC, setting up a website required logging into cloud dashboards, clicking 50 different setup buttons, selecting options, typing passwords, and crossing your fingers. If you made a single typo, your server crashed. Terraform was created to automate all of this!

Let's learn how Terraform acts like a magical 3D printer for cloud servers.

The LEGO Blueprint Metaphor

Imagine you want to build a giant LEGO city. It needs 100 houses, 5 fire stations, and 3 shopping malls. If you try to build it by hand, you will spend days looking for bricks, counting studs, and making mistakes. If you wanted to build an identical second LEGO city in another room, you'd have to start the painful manual process all over again!

Now, imagine you had a magical printer and a paper blueprint file. You put the blueprint in the printer, and *POOF!* The entire LEGO city constructs itself in seconds. If you copy the blueprint file and run the printer in another room, it builds another identical city instantly.

Terraform is that magical printer for server infrastructure. Instead of manually clicking buttons to buy servers, open ports, and create databases, you write a text file describing the setup. Terraform reads this blueprint and constructs the servers automatically.

Real-World Scenario: Launching a Testing Environment

Your development team has finished coding a new payment option. Before releasing it to the public, the QA team wants a complete, secure clone of your live AWS production setup (which has 10 EC2 servers, 2 databases, and 1 load balancer) to test it.

If you set this up manually, it would take a cloud engineer 2 days of dashboard clicking. With Terraform, you open your terminal and type terraform apply. In less than 5 minutes, Terraform reads your infrastructure code and builds the exact identical setup in AWS. Once testing is complete, you type terraform destroy, and Terraform cleans up every single resource so you don't get billed. That is efficiency!

Core Terraform Vocabulary

To write Terraform code, you write files using the HashiCorp Configuration Language (HCL). Here are the core terms you need to know:

Provider

The target cloud company you want to build on (e.g., AWS, Microsoft Azure, Google Cloud, or even Kubernetes).

Resource

The individual blocks you want to create (like an EC2 virtual server, an S3 folder, or a SQL database).

State File

Terraform's memory bank. A secret JSON file where it tracks what it has already built in the cloud so it doesn't build duplicates.

Plan

A preview summary. Terraform compares your blueprint text against the state file and shows you exactly what it will add or delete before doing it.

5 Everyday Terraform Commands Every Engineer Needs

To run Terraform blueprints, you open your terminal console and run HCL commands. Here is a cheat sheet of the 5 core commands you will use daily:

Purpose Terraform Command Real-World Analogy & Example
Initialize Project terraform init Downloads the necessary cloud plug-ins and connects to the providers.
Example: terraform init (Run once in a new project folder).
Check Syntax terraform validate Checks your code files for spelling mistakes or syntax errors before executing.
Example: terraform validate
Preview Changes terraform plan Displays a dry-run report showing exactly what will be added, modified, or deleted.
Example: terraform plan (Shows a list with green + or red - signs).
Build Infrastructure terraform apply Executes the HCL blueprint and builds the resources in the live cloud account.
Example: terraform apply (Type "yes" to confirm).
Delete Infrastructure terraform destroy Tears down and deletes every single cloud resource created by this project config to stop billing.
Example: terraform destroy (Warning: This deletes live databases!).

Warning: Protect the State File!

The terraform.tfstate file is the absolute source of truth. If you lose or delete it, Terraform will forget what servers it built and might try to build duplicates, causing massive configuration clashes. Always back up your state file in cloud storage like AWS S3 with state locking enabled!

Next Steps on Your DevOps Journey

Now that you can write code to automatically construct entire cloud architectures in minutes with Terraform, you face a new problem: How do we automate the testing, packaging, and deploying of our code whenever a developer pushes a change to Git? Enter CI/CD pipelines!

Test Your Knowledge

Answer these 35 questions to check your understanding of this module. Click on an option to reveal the correct answer instantly.

Question 1 of 35
What is Terraform?
A. A game
B. Infrastructure as Code tool
C. A database
D. A monitoring tool
Explanation: Terraform is an IaC tool for building, changing, and versioning infrastructure.
Question 2 of 35
What file tracks the state of infrastructure?
A. main.tf
B. terraform.tfstate
C. vars.tf
D. output.tf
Explanation: terraform.tfstate tracks the IDs of created resources.
Question 3 of 35
Which command initializes a directory?
A. terraform start
B. terraform init
C. terraform begin
D. terraform create
Explanation: terraform init prepares the working directory.
Question 4 of 35
Which command creates an execution plan?
A. terraform plan
B. terraform map
C. terraform preview
D. terraform test
Explanation: terraform plan shows what actions will be taken.
Question 5 of 35
Which command applies the changes?
A. terraform go
B. terraform apply
C. terraform run
D. terraform exec
Explanation: terraform apply executes the changes defined in the plan.
Question 6 of 35
Which command destroys the infrastructure?
A. terraform delete
B. terraform destroy
C. terraform remove
D. terraform kill
Explanation: terraform destroy removes all managed infrastructure.
Question 7 of 35
What is a "Provider"?
A. The user
B. A plugin to interact with APIs (e.g., AWS)
C. The source code
D. The output
Explanation: Providers interact with cloud providers, SaaS providers, etc.
Question 8 of 35
What allows code reuse in Terraform?
A. Functions
B. Modules
C. Scripts
D. Classes
Explanation: Modules are containers for multiple resources that are used together.
Question 9 of 35
What file usually contains the main configuration?
A. config.tf
B. main.tf
C. index.tf
D. root.tf
Explanation: main.tf is the convention for the primary entry point.
Question 10 of 35
How do you define input variables?
A. output block
B. variable block
C. input block
D. const block
Explanation: Variables are defined using the variable block.
Question 11 of 35
What command formats code to a canonical style?
A. terraform style
B. terraform fmt
C. terraform lint
D. terraform clean
Explanation: terraform fmt rewrites config files to a canonical format.
Question 12 of 35
What is "HCL"?
A. High Code Language
B. HashiCorp Configuration Language
C. Hyper Config Language
D. Hardware Control Language
Explanation: HCL is the language used by Terraform.
Question 13 of 35
Which command checks for syntax errors?
A. terraform check
B. terraform validate
C. terraform verify
D. terraform test
Explanation: terraform validate checks whether the configuration is syntactically valid.
Question 14 of 35
How do you output values after apply?
A. print
B. output block
C. echo
D. return
Explanation: Output values are defined using the output block.
Question 15 of 35
What is "terraform refresh"?
A. Reloads page
B. Updates state to match real-world resources
C. Restarts server
D. Clears cache
Explanation: It updates the state file with the current status of the infrastructure.
Question 16 of 35
What is a "Backend"?
A. The database
B. Where state is stored (e.g., S3)
C. The code logic
D. The user interface
Explanation: The backend defines where Terraform stores its state data files.
Question 17 of 35
What is "State Locking"?
A. Encrypting state
B. Preventing concurrent operations
C. Hiding state
D. Deleting state
Explanation: Locking prevents others from acquiring the lock while an operation is running.
Question 18 of 35
What is "Terraform Cloud"?
A. A weather app
B. Managed service for Terraform
C. A new language
D. A database
Explanation: It is a platform that manages Terraform runs in a consistent environment.
Question 19 of 35
How do you mark a resource for recreation?
A. terraform recreate
B. terraform taint
C. terraform mark
D. terraform redo
Explanation: terraform taint marks a resource to be destroyed and recreated.
Question 20 of 35
What is a "Data Source"?
A. Input variable
B. Read-only information from provider
C. A database
D. A module
Explanation: Data sources allow data to be fetched or computed for use elsewhere.
Question 21 of 35
What file extension does Terraform use?
A. .xml
B. .json
C. .tf
D. .yaml
Explanation: Terraform configuration files end in .tf.
Question 22 of 35
Can Terraform manage existing resources?
A. No
B. Yes, using terraform import
C. Only AWS
D. Only Azure
Explanation: terraform import can import existing infrastructure into your state.
Question 23 of 35
What is a "Resource"?
A. A variable
B. An infrastructure object (e.g., EC2)
C. A plugin
D. A function
Explanation: Resources describe one or more infrastructure objects.
Question 24 of 35
What is a "Provisioner"?
A. A tool to execute scripts on local/remote machine
B. A provider
C. A variable
D. A module
Explanation: Provisioners execute scripts during resource creation/destruction.
Question 25 of 35
How do you upgrade provider versions?
A. terraform update
B. terraform init -upgrade
C. terraform upgrade
D. terraform get
Explanation: terraform init -upgrade upgrades modules and plugins.
Question 26 of 35
Which service combination is commonly used to store Terraform state securely with state locking?
A. S3 bucket and CloudWatch Logs
B. Amazon S3 (storage) and DynamoDB (locking)
C. RDS PostgreSQL and Elasticache Redis
D. EFS storage and IAM policies
Explanation: Amazon S3 backend stores state files, and uses a DynamoDB table index to establish read/write locks, preventing concurrent edits.
Question 27 of 35
How do you define an explicit dependency between two resources in Terraform?
A. Reference a resource's attribute.
B. Use the "depends_on" meta-argument.
C. Nest one resource block inside another.
D. Set the dependency order in provider block.
Explanation: Terraform infers implicit dependencies. If it cannot, use the depends_on array meta-argument to force creation ordering.
Question 28 of 35
Where can you write custom validation logic for input variables?
A. Inside a "validation" block within the variable declaration.
B. Under variables schema properties in providers.
C. In the outputs.tf validation statement.
D. In a local-exec script configuration.
Explanation: Input variables support a nested validation block to check variables conditions using functions and return custom error messages.
Question 29 of 35
What is the purpose of a "dynamic" block in Terraform?
A. To provision resources across cloud regions dynamically.
B. To generate multiple nested blocks (e.g. ingress rules) iteratively based on a list or map.
C. To dynamically reload provider definitions.
D. To run script actions during deployment.
Explanation: A dynamic block generates nested settings blocks inside resources by iterating over collections using `for_each`.
Question 30 of 35
Why are provisioners (like local-exec or remote-exec) considered a last resort in Terraform?
A. They do not run on Linux servers.
B. They break Terraform's declarative model and state tracking since actions occur outside standard resource cycles.
C. They cannot read input variables.
D. They run synchronously, blocking plan execution.
Explanation: Provisioners cannot map actions cleanly to state attributes. Declarative configuration options (like user-data or configuration management tools) are preferred.
Question 31 of 35
What is the modern, recommended alternative to using the "terraform taint" command?
A. terraform apply -replace="resource_address"
B. terraform destroy -replace
C. terraform plan -force-recreate
D. terraform state rm
Explanation: Rather than altering state via taint, the -replace flag is standard for target recreation plans without state modification.
Question 32 of 35
Which lifecycle rule meta-argument is essential to prevent downtime when replacing a resource?
A. prevent_destroy = true
B. create_before_destroy = true
C. ignore_changes = [all]
D. replace_on_trigger = true
Explanation: create_before_destroy creates the new replacement resource before tearing down the old one, avoiding request downtime.
Question 33 of 35
How do you rename a resource in your configuration without destroying it in state?
A. Run terraform refresh.
B. Use the command "terraform state mv [old_addr] [new_addr]".
C. Edit state file JSON manually using vim.
D. Taint the resource and re-apply.
Explanation: terraform state mv moves the resource record in state to map the new name in config, bypassing destructive recreate cycles.
Question 34 of 35
What does the "terraform import" command do?
A. It downloads third-party provider code libraries.
B. It brings existing infrastructure resources under Terraform state tracking.
C. It loads variable files dynamically.
D. It updates module version dependencies.
Explanation: Import associates real-world resources (e.g. an existing EC2 instance) with a local Terraform configuration file and state address.
Question 35 of 35
How do you separate dev and prod environment state values when using the same Terraform configuration directory?
A. Use Terraform Workspaces.
B. Declare variables named dev and prod.
C. Modify the provider configuration profile blocks.
D. Re-run init with different credentials.
Explanation: Workspaces isolate state tracking dynamically (e.g. dev workspace state, prod workspace state) using a single codebase.

Real-Time Interview Questions & Answers

1. Why is the Terraform State file critical, and how do you secure it in a team environment?

Answer: The state file tracks the mapping between your configuration code and real-world deployed resources. We secure it by using a remote backend (like AWS S3) with state locking (via DynamoDB) and enabling encryption.

Example: “We configure our backend in a `backend.tf` file using S3 for encrypted storage and a DynamoDB table for concurrent state locks.”

2. What is the difference between `terraform plan` and `terraform apply`?

Answer: `terraform plan` creates an execution plan, showing what actions Terraform will take without modifying real resources. `terraform apply` executes the actions proposed in the plan.

Example: “In our pipeline, we run `terraform plan -out=tfplan` for pull request reviews, and run `terraform apply tfplan` only after approval.”

3. What is Infrastructure Drift, and how does Terraform reconcile it?

Answer: Drift occurs when resources are modified manually outside of Terraform. Running `terraform plan` reads the real state of resources and identifies discrepancies against the state file.

Example: “When someone manually changed an EC2 security group rule, I ran `terraform plan` to identify the change, then applied to restore code configuration.”

4. How do you organize Terraform code using Modules?

Answer: A module is a container for multiple resources used together. We write reusable modules for infrastructure blocks (like VPCs or ALB setups) and call them with environment-specific variables.

Example: “We created a standard `modules/database` folder and call it from our `prod/main.tf` to spin up PostgreSQL RDS instances consistently.”

5. What are Terraform Workspaces, and when should you use them?

Answer: Workspaces allow you to manage separate state files for the same configuration code directory. This is useful for managing different environments (like dev, QA, prod) using the same IaC code.

Example: “We run `terraform workspace select dev` or `prod` to deploy similar resources with isolated states and settings.”

6. How do you import existing cloud resources into Terraform?

Answer: I write the resource block configuration in code, then run `terraform import . ` to import the current real-world state into the state file.

Example: “I imported an existing S3 bucket by declaring `resource 'aws_s3_bucket' 'assets'` and running `terraform import aws_s3_bucket.assets my-bucket-name`.”

7. How do you destroy specific resources in Terraform without affecting the rest of the infrastructure?

Answer: I use the `-target` flag to target a specific resource for destruction: `terraform destroy -target=.`.

Example: “To remove a temporary dev VM, I ran `terraform destroy -target=aws_instance.dev_test` to keep the surrounding network assets intact.”

8. What is the difference between input variables and local values in Terraform?

Answer: Input variables act as parameters to pass configuration values into modules. Local values are internal variables defined within the module that calculate values dynamically (like constants).

Example: “We declare an input variable `environment` for inputs, and define a local `name_prefix = '${var.project}-${var.environment}'` for naming resources.”

9. What do you do if a Terraform execution is interrupted, leaving the state locked?

Answer: First, I verify that no other CI/CD pipeline is active. Then, I retrieve the Lock ID from the error output and run the `force-unlock` command to release the lock.

Example: “After our Jenkins agent crashed, I ran `terraform force-unlock a1b2c3d4-e5f6-7890` to enable edits to the infrastructure again.”

10. What are Provisioners in Terraform, and why should they be avoided?

Answer: Provisioners (like local-exec or remote-exec) execute scripts on local or remote machines. They should be avoided because they do not track state or offer declarative configuration management.

Example: “Instead of using remote-exec provisioners, we use EC2 user_data scripts and Cloud-Init to handle initial package installs on VMs.”

11. How do you handle sensitive outputs (like passwords or API keys) in Terraform?

Answer: I define the variable or output with the `sensitive = true` attribute. This prevents Terraform from printing the secret values in console output and logs.

Example: “We set `sensitive = true` on our database password output so it remains hidden in our automated Jenkins console outputs.”

12. What is the purpose of outputs in Terraform?

Answer: Output values expose information about your resources. They are useful for querying attributes post-deployment or sharing data between separate Terraform configurations.

Example: “We output the DNS name of our ALB so our frontend CI/CD pipeline knows where to route API calls.”

13. How do you lock provider versions in Terraform configurations?

Answer: I configure provider version locks inside a `required_providers` block inside the `terraform` configuration block, setting specific version requirements.

Example: “We configure `aws = { source = 'hashicorp/aws', version = '~> 5.0' }` to ensure our builds use stable AWS features.”

14. What is the difference between `terraform state rm` and destroying resources?

Answer: `terraform state rm` removes the resource tracking from the Terraform state file, leaving the real-world resource untouched. Destroying deletes the resource entirely from the cloud provider.

Example: “I ran `terraform state rm aws_instance.legacy_app` to stop managing an old server in IaC without terminating the running VM.”

15. What is the difference between `terraform clean` and deleting `.terraform` directory?

Answer: There is no `terraform clean` command. To reset local providers and modules, you delete the `.terraform` folder and the `.terraform.lock.hcl` file, then run `terraform init`.

Example: “When provider configuration got corrupted, I deleted the `.terraform` folder locally and ran `terraform init` to download clean dependencies.”
Live Sandbox

Don't Just Read. Code Live!

Practice what you just learned in our secure, zero-setup interactive labs. Boot up Linux containers, orchestrate AWS infrastructure, and run Docker right in your browser.

100% Free & Interactive for Growth School Community No Setup Required Real-time Terminal Feedback
Start Live Sandbox
ubuntu@growthschool:~

docker run -d -p 80:80 nginx

Unable to find image 'nginx:latest' locally...

latest: Pulling from library/nginx

Digest: sha256:4c087b3289aa6b185...

Status: Downloaded newer image for nginx:latest

Container running at http://localhost:80

_