Infrastructure as Code with Terraform
Introduction
This lesson covers the first objective area of the HashiCorp Certified: Terraform Associate (004) exam, Infrastructure as Code (IaC) with Terraform, objectives 1a to 1c. HashiCorp does not publish domain weights, so this course gives each area a share proportional to its number of official objectives (three of 37 here, about 8%). The exam lasts one hour, tests Terraform 1.12, and uses true/false, multiple-choice and multiple-answer questions.
The questions in this area are conceptual rather than syntactic. You will be asked to recognise what IaC is, why teams adopt it, and how Terraform's design lets one workflow manage many platforms. Do not skip it because it looks easy: the vocabulary introduced here (declarative, idempotent, provider, state, plan) is used in every other lesson.
By the end of this lesson you will be able to explain what Infrastructure as Code means, list and apply its main advantages, describe why Terraform is called cloud-agnostic and service-agnostic, and choose Terraform or another approach for a given scenario.
Learning objectives
- Define Infrastructure as Code and contrast it with manual, console-driven provisioning.
- Explain the advantages of IaC patterns: automation, repeatability, versioning, collaboration, consistency, documentation and cost control.
- Distinguish declarative from imperative approaches and explain why Terraform is declarative.
- Describe how Terraform supports multi-cloud, hybrid cloud and service-agnostic workflows through providers.
- Recognise what Terraform does not do (configuration management inside servers, application deployment).
1a. What Infrastructure as Code is
Infrastructure as Code is the practice of describing infrastructure (networks, virtual machines, databases, DNS records, permissions, SaaS settings) in text files that a tool reads and turns into real resources. The files are the source of truth: you change the files, not the running systems.
Consider a company, Brightwave Retail, that launches a promotional site every quarter. Before IaC, an engineer opened the cloud console, clicked through screens to create a network, two virtual machines, a load balancer and a database, and wrote the steps in a wiki page. Three problems appeared:
- The staging environment never quite matched production because someone forgot a firewall rule.
- Rebuilding after an incident took a full day, since nobody remembered every setting.
- Nobody could say who had changed the load balancer timeout or why.
With IaC, the same environment is a set of files in a Git repository. A new environment is created by running a command against the same files, in minutes, and every change is a reviewed commit.
Declarative versus imperative
| Approach | You describe | The tool decides | Example |
|---|---|---|---|
| Imperative (procedural) | The steps to execute, in order | Nothing; it runs your steps | A shell script calling cloud CLI commands |
| Declarative | The desired end state | What to create, change or delete to reach it | Terraform configuration |
Terraform is declarative. You write that you want "a network with two subnets and a database" and Terraform compares that wish with what already exists, then computes the actions needed. If you run it twice with no change, the second run does nothing. This property is called idempotence: applying the same configuration repeatedly produces the same result without duplicating resources.
A short example in HashiCorp Configuration Language (HCL):
resource "aws_s3_bucket" "assets" {
bucket = "brightwave-promo-assets"
tags = {
Environment = "staging"
Owner = "web-team"
}
}
The block states that a bucket with this name and these tags must exist. It does not say "call the CreateBucket API". If the bucket already exists and matches, nothing happens. If someone removes a tag by hand, the next plan shows that Terraform will add it back.
Where IaC sits among related tools
IaC is a family of tools, and the exam may ask you to place Terraform among them.
| Category | Purpose | Examples |
|---|---|---|
| Provisioning (infrastructure orchestration) | Create and manage infrastructure resources through APIs | Terraform, OpenTofu, AWS CloudFormation, Azure Bicep |
| Configuration management | Configure software inside existing machines | Ansible, Chef, Puppet |
| Image building | Produce machine images | Packer |
| Secrets and identity | Store and issue secrets | Vault |
Terraform is a provisioning tool. It creates the virtual machine; it is not the tool of choice for installing and tuning packages inside it, although it can hand over to such tools. Remember this when a question describes patching an operating system on a running host.
1b. Advantages of IaC patterns
The official objective says "explain the advantages of IaC patterns". Learn the list below and, more importantly, learn to match each advantage to a situation.
| Advantage | What it means | Brightwave example |
|---|---|---|
| Automation | Provisioning runs from code, without manual clicks | A pipeline builds a full environment on every release branch |
| Repeatability and consistency | The same code yields the same infrastructure | Staging and production use the same configuration with different variable values |
| Versioning | Files live in version control with history | git blame shows who changed the load balancer timeout and the pull request explains why |
| Collaboration and review | Teams propose changes as pull requests | A second engineer reviews a firewall change before it is applied |
| Documentation | The code describes the architecture | New hires read the repository to understand the network layout |
| Speed and reduced human error | Fewer manual steps means fewer mistakes | A disaster-recovery rebuild takes minutes instead of a day |
| Cost control | Environments can be destroyed when unused | Test environments are destroyed every evening |
| Reuse | Patterns are packaged and shared (modules) | One network module is used by ten teams |
Worked example: choosing the benefit that fits
Scenario. After a regional outage, Brightwave must recreate its whole stack in another region. The team has the configuration in Git and parameterises the region as a variable. Which IaC advantage is demonstrated most directly?
Reasoning, step by step.
- The key fact is that the stack can be rebuilt elsewhere by changing one value. That points to repeatability, not to documentation or collaboration.
- Versioning helps (the code is in Git), but versioning alone does not rebuild anything; it only stores the history.
- Cost control is irrelevant: the scenario is about recovery, not spending.
Solution. Repeatability and consistency (supported by automation).
Why the other choices are weaker. "Versioning" explains where the code lives but not why the rebuild works. "Documentation" is a side effect. "Collaboration" is about teamwork, which the scenario does not mention.
Idempotence and drift
Two ideas support these advantages.
- Idempotence: applying a configuration again does not create duplicates. Terraform reads its record of what it manages and the real objects, then plans only the difference.
- Drift: real infrastructure can diverge from the code when somebody edits a resource by hand. IaC makes drift visible: the next plan reports the difference, and applying restores the declared state. Lesson 7 shows how Terraform detects and handles drift with refresh-only plans.
Exam tip. If a question asks how IaC reduces configuration drift, the answer is that the code is the single source of truth and tools can detect and correct differences. "Manual changes in the console" is always the wrong direction.
1c. Multi-cloud, hybrid cloud and service-agnostic workflows
Terraform is often described as cloud-agnostic. The exact meaning matters, because exam writers like to test it.
Terraform core is a single binary that reads configuration, builds a dependency graph, tracks state and talks to plugins. The knowledge of any specific platform lives in providers, separate plugins distributed through the Terraform Registry. A provider translates Terraform's generic create/read/update/delete operations into API calls for one platform: AWS, Azure, Google Cloud, Kubernetes, GitHub, Datadog, Cloudflare, a VMware vCenter server and thousands more.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
cloudflare = {
source = "cloudflare/cloudflare"
version = "~> 4.0"
}
}
}
resource "aws_instance" "web" {
ami = "ami-0abcdef1234567890"
instance_type = "t3.micro"
}
resource "cloudflare_record" "www" {
zone_id = var.zone_id
name = "www"
type = "A"
content = aws_instance.web.public_ip
ttl = 300
}
In one configuration, Terraform creates a virtual machine on AWS and a DNS record at Cloudflare, using the machine's public IP address. The two resources belong to different vendors, yet one workflow (write, plan, apply) handles both, and Terraform knows the DNS record must wait for the instance because it references it.
What "agnostic" does and does not mean:
- It does mean the same language, workflow, state and plan/apply process work for every provider.
- It does not mean the same configuration runs unchanged on every cloud. A resource type such as
aws_instanceis specific to AWS; moving to Azure means writingazurerm_linux_virtual_machineresources. Terraform standardises the workflow, not the resource schemas.
Multi-cloud and hybrid cloud
| Term | Meaning | Terraform's role |
|---|---|---|
| Multi-cloud | Using services from more than one public cloud | One tool and workflow for AWS, Azure and GCP resources |
| Hybrid cloud | Combining public cloud with private or on-premises infrastructure | Providers for VMware, OpenStack, Kubernetes and others sit beside cloud providers |
| Service-agnostic | Managing any API-driven service, not only compute | Providers exist for DNS, monitoring, source control, identity, databases and SaaS products |
Terraform's reach to "any service with an API" explains why it can manage a GitHub repository, a Datadog monitor and an AWS network in the same run. A provider only needs to implement the operations for its resource types.
Worked example: multi-platform dependency
Scenario. Brightwave wants a GitHub repository for its web code, an Azure resource group hosting the site, and a Datadog monitor that alerts when the site is down. One engineer proposes three separate tools and three separate processes. Another proposes Terraform. Explain the advantage of Terraform.
Reasoning.
- All three targets expose APIs, so each can have a provider.
- A single configuration can declare the three resource types, and Terraform records them all in one state.
- The monitor can reference the site URL output from the Azure resource, creating an automatic dependency.
- One
terraform planshows the combined effect before anything changes.
Solution. Use Terraform with three providers. The team gets one language, one review process, one plan and one record of what exists.
Why the alternatives are worse. Three tools means three skill sets, three states of knowledge, and no cross-platform dependencies: the monitor could be created before the URL exists.
How IaC changes a team's daily workflow
Adopting IaC changes habits as much as tooling. A typical flow at Brightwave Retail now looks like this:
- An engineer creates a branch and edits the
.tffiles, for example to add a second subnet. - A pipeline runs
terraform fmt -checkandterraform validate, thenterraform plan, and posts the plan as a comment on the pull request. - A teammate reads the plan: "1 to add, 0 to change, 0 to destroy". The reviewer checks that nothing unexpected will be destroyed.
- After approval and merge, the pipeline runs
terraform applyagainst the reviewed plan. - The Git history records who proposed, who approved and when the change shipped.
Compare this with the console approach, where the "review" is a chat message and the "history" is human memory. The value of IaC is not only speed: it is that infrastructure changes become observable, reviewable and reversible (reverting a commit and applying again restores the previous declaration). Notice also that the plan acts as a safety net: it is a preview computed before any resource is touched, a feature that has no equivalent in a manual click-through.
Costs exist too. The team must learn HCL, protect the state file, and agree that nobody edits resources outside the code. Those organisational rules are what keep drift away, and exam questions about "best practice" usually reward the answer that routes every change through version control and a reviewed plan.
What Terraform is not
Questions sometimes try to stretch Terraform beyond its role.
| Claim | Correct? | Explanation |
|---|---|---|
| Terraform provisions infrastructure through provider APIs | Yes | This is its core purpose |
| Terraform replaces configuration management tools for in-guest software | Not as its main job | It can run provisioners as a last resort, but dedicated tools are recommended |
| Terraform guarantees the same resources exist on every cloud | No | Resource types are provider-specific |
| Terraform needs an agent installed on managed servers | No | It calls remote APIs from where it runs |
| Terraform configuration is written only in JSON | No | HCL is the primary language; JSON is an alternative syntax |
| Terraform is imperative | No | It is declarative |
Common pitfalls
- Confusing "cloud-agnostic" with "portable code". The workflow is portable, resource definitions are not.
- Thinking IaC removes the need for review. IaC makes review possible; teams still need pull requests and plans.
- Treating Terraform as a configuration manager. It provisions; it does not patch operating systems.
- Forgetting that the console is still reachable. Manual edits cause drift. The cure is a policy that changes go through code.
- Assuming a second
applyduplicates resources. Because Terraform is idempotent and tracks state, it does not.
Exam tip. Several questions can be solved by spotting a single word. "Desired state" signals declarative. "API calls to many platforms" signals providers. "Stored history of changes" signals version control. Read the stem for these cues before looking at the options.
Mini case study: an expanding start-up
Situation. Northfield Analytics runs a data product on one cloud. Its CTO announces a customer requirement: the product must also run inside the customer's private data centre, which uses VMware, and alerts must go to PagerDuty. The platform team currently uses console clicks plus a wiki. Three incidents last quarter came from environments that differed.
Question. Recommend an approach and justify it with IaC advantages.
Commented solution.
- Adopt Terraform with version-controlled configuration. The current console process cannot be reviewed or repeated, which explains the divergent environments. Code in Git makes each environment reproducible (repeatability) and every change visible (versioning, collaboration).
- Use several providers. The cloud provider, the VMware provider and the PagerDuty provider let one workflow cover public cloud, private data centre and SaaS: this is hybrid and service-agnostic usage.
- Expect provider-specific resources. The team should not expect to reuse
aws_*resources on VMware. They share the workflow, variables and modules' structure, not resource types. - Plan before apply. Reviewing plans in pull requests catches mistakes before they reach production and reduces the human error behind the three incidents.
- Handle in-guest software separately. If the product needs installed packages, use an image builder or configuration management tool; Terraform provisions the machines.
Key terms
- Infrastructure as Code (IaC): managing infrastructure through machine-readable definition files.
- Declarative: describing the desired result rather than the steps.
- Idempotent: repeating an operation yields the same result.
- Provider: a plugin that lets Terraform manage a platform's resources through its API.
- Drift: divergence between the real infrastructure and its declared definition.
- HCL: HashiCorp Configuration Language, the main Terraform syntax.
- Multi-cloud / hybrid cloud: using several public clouds / combining public and private infrastructure.
- Service-agnostic: able to manage any service exposed through an API.
Summary checklist
- I can define IaC and contrast it with console-driven provisioning.
- I know Terraform is declarative and idempotent.
- I can list the main IaC advantages and match each to a scenario.
- I know that providers carry platform knowledge and that Terraform core is platform-neutral.
- I understand that cloud-agnostic means a common workflow, not identical resource code.
- I can explain multi-cloud, hybrid cloud and service-agnostic usage.
- I know Terraform provisions infrastructure and does not replace in-guest configuration management.
Official sources
- Terraform Associate (004) page: https://developer.hashicorp.com/certifications/terraform-associate (opens in a new tab)
- Exam content list: https://developer.hashicorp.com/terraform/tutorials/certification-004/associate-review-004 (opens in a new tab)
- Learning path: https://developer.hashicorp.com/terraform/tutorials/certification-004/associate-study-004 (opens in a new tab)
