Terraform has a vocabulary of its own that will turn up in every lesson, every error message and every team conversation. If you cannot tell a resource from a data source with precision, or cannot read the symbols a plan prints, everything else feels confusing. This lesson is the course's dictionary: we will see what a provider, a resource, an attribute and the state are; how Terraform works out the order of operations through a dependency graph; what lifecycles a resource can go through; what each of the main commands does; and what the .terraform/ directory and the .terraform.lock.hcl file contain. We are not building a complete project yet — that is the next lesson — but we will look at real fragments of EcoMarket's infrastructure.
- Provider
A provider is a plugin that teaches Terraform how to talk to a specific platform. Terraform's core knows nothing about AWS, about Kubernetes or about the file system: all that intelligence lives in the providers.
Each provider contributes:
- A set of resource types it can manage (
aws_s3_bucket,local_file,random_petand so on). - A set of data source types it can query (
aws_ami,local_fileand so on). - Its own configuration schema (region, credentials, endpoint and so on).
It is declared like this:
# Configuration for the "local" provider, which knows how to manipulate files on disk.
# This provider needs no arguments: there are no credentials and no region.
provider "local" {}
# Configuration for the "random" provider, which generates random values
# and remembers them in the state so they do not change on every run.
provider "random" {}Providers are identified by a full address in the registry. For example, registry.terraform.io/hashicorp/local breaks down into:
| Part | Value | Meaning |
|---|---|---|
| Host | registry.terraform.io |
Registry where the provider lives |
| Namespace | hashicorp |
Organisation that publishes it |
| Type | local |
The provider's short name |
In the code you use the short name (local), but the formal declaration, with the version, goes in the terraform block:
terraform {
# Minimum version of the Terraform binary this configuration supports.
required_version = ">= 1.5.0"
required_providers {
# "local" is the short name we will use in provider/resource blocks.
local = {
source = "hashicorp/local" # where it is downloaded from
version = "~> 2.5" # which versions we accept: >= 2.5.0 and < 3.0.0
}
random = {
source = "hashicorp/random"
version = "~> 3.6"
}
}
}The ~> operator is called a pessimistic constraint: it allows updates to the last number given, but not to the one before it. ~> 2.5 accepts 2.5.1 and 2.9.0, but not 3.0.0. It is the usual constraint, because providers follow semantic versioning and a major version bump can break your configuration.
Detailed provider configuration (aliases, multiple regions, authentication) is the subject of the lesson Providers.
- Resource
A resource is an infrastructure object that Terraform creates, updates and destroys. It is the most important block in the language: everything else revolves around it.
# ┌─ keyword ┌─ resource type ┌─ local name
# │ │ │
resource "random_pet" "suffix" {
length = 2 # two words
separator = "-" # joined by a hyphen
}Two identifiers you must not mix up:
| Identifier | Example | Who decides it | What it is for |
|---|---|---|---|
| Resource type | random_pet |
The provider | Determines which object is managed and which arguments it accepts |
| Local name | suffix |
You | Identifies the resource inside your configuration; it does not exist outside Terraform |
The combination of the two forms the resource address: random_pet.suffix. That address is unique within the module and is what appears in plans, in the state and in commands.
A fragment with two EcoMarket resources:
# Random suffix used to give EcoMarket resources unique names.
resource "random_pet" "suffix" {
length = 2
separator = "-"
}
# Inventory file documenting the deployed environment.
resource "local_file" "inventory" {
filename = "${path.module}/ecomarket-dev-inventory.json"
# jsonencode turns an HCL object into a valid JSON string.
content = jsonencode({
project = "ecomarket"
environment = "dev"
region = "eu-west-1"
suffix = random_pet.suffix.id
managed_by = "terraform"
})
}Pay attention to random_pet.suffix.id: that is a reference, and it is the key to everything that follows.
- Data source
A data source is the opposite of a resource: it only reads existing information, it never creates or modifies it.
# Reads a file that ALREADY exists on disk. Terraform neither creates nor deletes it;
# it just queries its content so it can be used elsewhere.
data "local_file" "template" {
filename = "${path.module}/templates/base-tags.json"
}Its address carries the data. prefix: in this case, data.local_file.template, and its content is referenced as data.local_file.template.content.
The mental rule is simple:
resource |
data |
|
|---|---|---|
| Creates objects | Yes | No |
| Modifies objects | Yes | No |
| Destroys objects | Yes | No |
| Appears in the plan as a change | Yes | No (it is only read) |
| Address prefix | (none) | data. |
Data sources are covered in depth in Resource and Data Blocks. Here it is enough that you recognise the word data when you see it.
- Attributes, arguments and references
Two kinds of value live inside a block, and telling them apart avoids an enormous amount of confusion:
- Arguments: the values you write to configure the resource. In
local_file, the arguments arefilename,content,file_permissionand so on. - Attributes: the values the provider returns once the object has been created. In
local_file, read-only attributes includeid,content_md5,content_sha256and others.
Many arguments can also be read as attributes (you can read local_file.inventory.filename), but read-only attributes are only known after applying. That is why you see the famous (known after apply) in plans.
A reference has this shape:
Examples with EcoMarket:
resource "random_pet" "suffix" {
length = 2
}
resource "random_password" "db" {
length = 24
special = true
}
resource "local_file" "example_credentials" {
filename = "ecomarket-dev-db.json"
content = jsonencode({
# A reference to an ATTRIBUTE of the random_pet resource:
identifier = "ecomarket-dev-db-${random_pet.suffix.id}"
# A reference to a SENSITIVE attribute of random_password.
# Terraform will mark it as sensitive and hide it in the plan output.
password = random_password.db.result
})
}There are also special reference values that come up constantly:
| Reference | What it holds |
|---|---|
var.<name> |
The value of an input variable |
local.<name> |
The value of a local value (a computed constant) |
data.<type>.<name>.<attr> |
An attribute of a data source |
module.<name>.<output> |
An output of a module |
path.module |
Path of the current module's directory |
path.root |
Path of the configuration's root directory |
each.key / each.value |
Key and value inside a for_each |
count.index |
Index inside a count |
They are all covered in detail in module 2; for now you only need to recognise them.
- State
The state is the record Terraform keeps of the correspondence between the resources in your configuration and the real objects. Without it, Terraform would have no way of knowing that local_file.inventory corresponds to a file it already created.
For each resource it stores:
- Its address (
local_file.inventory). - The provider that manages it.
- All its arguments and attributes, exactly as they were at the last
apply. - Its dependencies.
A simplified extract from terraform.tfstate:
{
"version": 4,
"terraform_version": "1.9.8",
"serial": 3,
"lineage": "8a1f0b4c-2d7e-4c11-9f3a-5b6c7d8e9f00",
"resources": [
{
"mode": "managed",
"type": "random_pet",
"name": "suffix",
"provider": "provider[\"registry.terraform.io/hashicorp/random\"]",
"instances": [
{
"schema_version": 0,
"attributes": {
"id": "cheerful-mammoth",
"keepers": null,
"length": 2,
"prefix": null,
"separator": "-"
}
}
]
}
]
}How to read it:
mode: "managed"indicates a managed resource. Data sources appear withmode: "data".serialincrements with every change; it is used to detect conflicting writes.lineageidentifies the state's lineage; it stops you accidentally mixing two different states.attributesholds the snapshot of what was applied. This is where you see why the state can contain secrets: if a resource has a password, it will be there in plain text.
By default the state is a local file, terraform.tfstate, in the working directory. That is not good enough for a team: you need a remote backend with locking, and that is the content of module 3. For now, hold on to three ideas:
- The state is the source of truth for what Terraform believes exists.
- It can contain sensitive data, so it is never versioned in Git.
- If the state and reality diverge (because someone changed something by hand), we call it drift, and Terraform detects it when it refreshes.
- Plan versus apply
This separation is Terraform's most valuable feature for an operations team.
terraform plan |
terraform apply |
|
|---|---|---|
| Does it modify infrastructure? | No | Yes |
| Does it modify the state? | No (it may refresh it in memory) | Yes |
| Does it read the provider's APIs? | Yes, to refresh | Yes |
| Result | A description of the planned changes | The changes executed |
| When it is used | On every pull request, before any change | After reviewing and approving the plan |
Internally, this is what happens:
- Load the configuration: Terraform reads every
.tffile in the directory. - Read the state: it gets the snapshot of what it believes exists.
- Refresh: it queries the APIs to check how those objects actually look right now.
- Compare: it computes the difference between the desired state (the configuration) and the real state (the refreshed one).
- Produce the plan: an ordered list of actions.
In apply, a sixth step is added: execute those actions respecting the graph's order and update the state.
It is good practice to save the plan to a file and apply exactly that plan, to guarantee that what was approved is what gets executed:
# Generate the plan and save it into a binary file.
$ terraform plan -out=ecomarket.tfplan
# Apply EXACTLY that plan, recomputing nothing and asking nothing.
$ terraform apply ecomarket.tfplanThis pattern is the foundation of the pipelines in module 8. The advanced flags (-target, -replace, -refresh=false) are covered in Provisioning Basics.
- The dependency graph
Terraform does not execute operations in the order you write the blocks. It builds a directed acyclic graph (DAG) of every object in the configuration and walks that graph, running in parallel everything that does not depend on anything else (by default, up to 10 simultaneous operations).
7.1. Implicit dependencies
These are the ones Terraform works out on its own, from the references. They are always the preferable kind.
resource "random_pet" "suffix" {
length = 2
}
# By referencing random_pet.suffix.id, this resource DEPENDS on the previous one.
# There is nothing more to tell Terraform.
resource "local_file" "inventory" {
filename = "ecomarket-dev-inventory-${random_pet.suffix.id}.json"
content = jsonencode({ environment = "dev" })
}7.2. Explicit dependencies
When a relationship exists that no reference reflects, you declare it with depends_on:
resource "local_file" "backup_policy" {
filename = "ecomarket-dev-backup-policy.json"
content = jsonencode({ retention_days = 30 })
}
resource "local_file" "deployment_record" {
filename = "ecomarket-dev-record.txt"
content = "dev deployment completed.\n"
# We use no attribute of the policy, but we want to guarantee
# that the record is written AFTER the policy exists.
depends_on = [local_file.backup_policy]
}Practical rule: use
depends_ononly when it is unavoidable. It adds edges to the graph that Terraform cannot optimise away and, if you overdo it, you end up serialising deployments that could have run in parallel. If you can express the dependency with a reference, use a reference.
7.3. EcoMarket's graph
This is what the graph of EcoMarket's target platform will look like once we get to deploying it on a real cloud provider (module 5). Notice that there is no single linear chain: there are branches Terraform can create at the same time.
flowchart TD
P["provider: aws<br/>(eu-west-1 region)"] --> VPC["vpc<br/>ecomarket-prod-vpc"]
P --> S3["images bucket<br/>ecomarket-prod-images"]
P --> RND["random_password<br/>database password"]
VPC --> SUB1["public subnet A"]
VPC --> SUB2["public subnet B"]
VPC --> SUBD["private subnets<br/>database"]
VPC --> SGL["security group<br/>load balancer"]
VPC --> SGA["security group<br/>application"]
VPC --> SGD["security group<br/>database"]
SUB1 --> LB["load balancer<br/>ecomarket-prod-lb"]
SUB2 --> LB
SGL --> LB
SUBD --> DB[("postgresql<br/>ecomarket-prod-db")]
SGD --> DB
RND --> DB
SGA --> APP["servers<br/>ecomarket-prod-web"]
SUB1 --> APP
DB --> APP
S3 --> APP
LB --> APP
What the graph tells you:
- The images bucket does not depend on the VPC: Terraform creates it in parallel from the very first second.
- The database needs its subnets, its security group and the random password.
- The application servers are the last node: they need the database (for their connection string), the bucket (for the images) and the load balancer.
- To destroy, Terraform walks the graph backwards: the servers first, the VPC last. That is why
terraform destroyworks without you specifying any order.
You can generate the real graph of any project:
# Produces a description of the graph in DOT format.
$ terraform graph > graph.dot
# If you have graphviz installed, you can turn it into an image:
$ terraform graph | dot -Tsvg > graph.svg
- A resource's lifecycle and the plan symbols
Every resource in a plan carries a symbol indicating which action will be taken on it. Learning to read them at a glance is a basic skill.
| Symbol | Action | Meaning | Risk |
|---|---|---|---|
+ |
create | The resource does not exist and is going to be created | Low |
~ |
update in-place | The resource exists and is modified without recreating it | Low–medium |
-/+ |
replace | It is destroyed and created again | High: there is an outage and possible data loss |
+/- |
replace (create before destroy) | The new one is created and then the old one destroyed | Medium |
- |
destroy | The resource is deleted | High |
<= |
read | A data source is read during the apply | None |
| (no symbol) | no-op | No changes | None |
Why a change triggers a replacement rather than an update: each provider marks in its schema which arguments force a new object (ForceNew). Changing a bucket's name, a machine's availability zone or a local_file's filename cannot be done "in place": the object must be recreated.
A real plan output showing all three cases:
Terraform will perform the following actions:
# local_file.deployment_record will be created
+ resource "local_file" "deployment_record" {
+ content = "dev deployment completed.\n"
+ content_base64sha256 = (known after apply)
+ filename = "ecomarket-dev-record.txt"
+ id = (known after apply)
}
# local_file.inventory will be updated in-place
~ resource "local_file" "inventory" {
~ content = jsonencode(
~ {
~ environment = "dev" -> "staging"
}
)
id = "d0b9a7..."
# (2 unchanged attributes hidden)
}
# local_file.backup_policy must be replaced
-/+ resource "local_file" "backup_policy" {
~ filename = "ecomarket-dev-backup.json" -> "ecomarket-dev-backup-policy.json" # forces replacement
~ id = "9fc1e2..." -> (known after apply)
}
Plan: 2 to add, 1 to change, 1 to destroy.Keys to reading it:
# forces replacementnext to an attribute is the explanation for why the resource carries-/+. Terraform always tells you which argument is to blame.(known after apply)means the value will be decided by the provider when it creates the object.(2 unchanged attributes hidden): the plan hides what does not change in order to reduce noise. Withterraform plan -no-color | less, or the-concise=falseflag in recent versions, you can see more.- The summary line (
Plan: 2 to add, 1 to change, 1 to destroy) is the first thing to look at. If you seeto destroyin production and were not expecting it, stop and review.
This is the full lifecycle from the engine's point of view:
stateDiagram-v2
[*] --> DoesNotExist
DoesNotExist --> Exists: create (+)
Exists --> Exists: update in-place (~)
Exists --> Exists: replace (-/+)
Exists --> DoesNotExist: destroy (-)
Exists --> Exists: no changes (no-op)
DoesNotExist --> [*]
The lifecycle block, which lets you alter this behaviour (prevent_destroy, create_before_destroy, ignore_changes), is studied in module 5.
- The main commands
This table is the cheat sheet you will use every day:
| Command | What it does | Modifies infrastructure | When it is used |
|---|---|---|---|
terraform init |
Downloads providers and modules, configures the backend, writes .terraform/ and the lock file |
No | When cloning the repository and when changing providers, modules or the backend |
terraform fmt |
Reformats the .tf files into the canonical style |
No | Before every commit (or on save in your editor) |
terraform validate |
Checks the configuration's syntax and internal coherence | No | After editing; requires a prior init |
terraform plan |
Computes and shows the planned changes | No | Before every apply, and on every pull request |
terraform apply |
Executes the changes and updates the state | Yes | After reviewing the plan |
terraform destroy |
Destroys every managed resource | Yes | Ephemeral environments; never casually |
terraform show |
Shows the current state or a saved plan, as text or JSON | No | Inspecting what is deployed |
terraform output |
Shows the defined output values | No | Getting URLs, IDs or names for other processes |
terraform console |
Opens an interactive expression interpreter | No | Trying out functions and references without applying anything |
Annotated examples of the less obvious ones:
# fmt: -recursive applies to subdirectories too; -check makes no changes,
# it only returns an exit code != 0 if something is badly formatted (ideal in CI).
$ terraform fmt -recursive
main.tf
variables.tf
$ terraform fmt -check -recursive
# No output = everything is fine.# validate catches configuration errors, NOT provider API errors.
# For example, it catches a reference to a non-existent resource,
# but not that a bucket name is already taken in the real world.
$ terraform validate
Success! The configuration is valid.# show with no arguments displays the current state in readable form.
$ terraform show
# With -json it produces output that tools such as jq can process.
$ terraform show -json | jq '.values.root_module.resources[].address'
"local_file.inventory"
"random_pet.suffix"# output shows every output...
$ terraform output
inventory_name = "ecomarket-dev-inventory.json"
unique_suffix = "cheerful-mammoth"
# ...or one specific output, with -raw to get the value without quotes
# (very handy for chaining in scripts).
$ terraform output -raw unique_suffix
cheerful-mammoth# console lets you experiment with the language without touching anything.
$ terraform console
> upper("ecomarket")
"ECOMARKET"
> "ecomarket-${"prod"}-web"
"ecomarket-prod-web"
> [for e in ["dev","staging","prod"] : "ecomarket-${e}-db"]
[
"ecomarket-dev-db",
"ecomarket-staging-db",
"ecomarket-prod-db",
]
> exitterraform console is a magnificent learning tool: whenever you are unsure what a function or expression returns, try it there.
- The
.terraform/ directory and the .terraform.lock.hcl file
.terraform/ directory and the .terraform.lock.hcl fileAfter running terraform init, two items appear in the working directory that are worth understanding well, because Git treats them in opposite ways.
10.1. .terraform/
This is the internal working directory. It is always regenerated by init, so it goes into .gitignore.
$ tree -a .terraform
.terraform
├── providers
│ └── registry.terraform.io
│ └── hashicorp
│ ├── local
│ │ └── 2.5.2
│ │ └── linux_amd64
│ │ └── terraform-provider-local_v2.5.2_x5
│ └── random
│ └── 3.6.3
│ └── linux_amd64
│ └── terraform-provider-random_v3.6.3_x5
└── modules
└── modules.jsonWhat it contains:
| Item | Contents |
|---|---|
providers/ |
The downloaded provider binaries (or links into the cache) |
modules/ |
A copy of the external modules and their modules.json index |
terraform.tfstate |
Only if you use a remote backend: the backend's configuration, not the state |
environment |
The active workspace, if it is not default |
If something behaves oddly after changing providers or modules, deleting
.terraform/and runningterraform initagain is a safe remedy: you lose nothing that cannot be regenerated. Deletingterraform.tfstateis not safe at all; they are different things despite the similar names.
10.2. .terraform.lock.hcl
This is the provider dependency lock file, the equivalent of package-lock.json or Cargo.lock. It is versioned in Git, always.
# This file is maintained automatically by "terraform init".
# Manual edits may be lost in future updates.
provider "registry.terraform.io/hashicorp/local" {
version = "2.5.2"
constraints = "~> 2.5"
hashes = [
"h1:JlMZD6nYqJ8sSrFfEAH0Vk/SL8WLZRmFaMUF9PJK5wM=",
"zh:136299545178ce281c56f36965bf91c35407c11897f7082b3b983d86cb79b511",
"zh:3b4486858aa9cb8163378722b642c57c529b6c64bfbfc9461d940a84cd66ebea",
]
}What each field means:
version: the exact version that was selected and installed.constraints: the constraint you wrote inrequired_providers.hashes: the cryptographic hashes of the accepted packages. If someone swapped the provider binary for another,initwould fail with a verification error.
Its value is twofold:
- Reproducibility: the whole EcoMarket team and the CI pipeline install exactly the same provider version, so a plan gives the same result everywhere.
- Security: the hashes protect against a tampered package.
Related commands:
# Updates providers to the latest version allowed by the constraints
# and rewrites the lock file.
$ terraform init -upgrade
# Adds the hashes for OTHER platforms to the lock file.
# Essential if you develop on macOS and CI runs on Linux:
# without this, the CI init would fail for lack of a linux_amd64 hash.
$ terraform providers lock \
-platform=linux_amd64 \
-platform=darwin_arm64 \
-platform=windows_amd64A summary of what goes into Git:
| File / directory | Versioned? | Why |
|---|---|---|
*.tf |
Yes | It is the code |
.terraform.lock.hcl |
Yes | It pins provider versions and hashes |
.terraform-version |
Yes | It pins the binary's version |
.terraform/ |
No | It is regenerated by init |
terraform.tfstate |
No | It can contain secrets; it belongs in a remote backend |
*.tfplan |
No | An ephemeral binary |
- Idempotence and convergence
Two words that define Terraform's behaviour.
Idempotence: applying the same configuration several times produces the same result as applying it once. If you have changed nothing, the second apply does nothing.
$ terraform apply -auto-approve
local_file.inventory: Creating...
local_file.inventory: Creation complete after 0s [id=a1b2c3...]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
# We run it again without touching anything:
$ terraform apply -auto-approve
local_file.inventory: Refreshing state... [id=a1b2c3...]
No changes. Your infrastructure matches the configuration.
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.Convergence: every apply brings the real infrastructure closer to the desired state, whatever the starting point. If someone at EcoMarket edits the inventory file by hand, the next plan will detect that drift and propose putting it back to what the code says:
# Someone modifies the file outside Terraform
$ echo "environment=production" > ecomarket-dev-inventory.json
$ terraform plan
local_file.inventory: Refreshing state... [id=a1b2c3...]
Terraform detected the following changes made outside of Terraform:
# local_file.inventory has been deleted
- resource "local_file" "inventory" {
- id = "a1b2c3..." -> null
}
Terraform will perform the following actions:
# local_file.inventory will be created
+ resource "local_file" "inventory" {
+ content = jsonencode({ environment = "dev" })
+ filename = "ecomarket-dev-inventory.json"
}
Plan: 1 to add, 0 to change, 0 to destroy.(The local provider reports the change as a "deletion" because it compares the content hash; with a cloud provider you would see a ~ update in-place putting the attribute back to its declared value.)
This property is the direct answer to EcoMarket's problem with undocumented changes: with Terraform, a manual change is not quietly forgotten, it shows up in the next plan.
flowchart LR
D["Desired state<br/>(.tf files)"] --> C{"Comparison<br/>engine"}
R["Real state<br/>(refreshed from the API)"] --> C
C -->|identical| N["No changes<br/>(idempotence)"]
C -->|different| A["Actions to converge<br/>(+ ~ -/+ -)"]
A --> R
Common Mistakes and Tips
- Confusing the local name with the object's real name.
resource "local_file" "inventory"does not create anything called "inventory": the real name is defined by thefilenameargument. The local name exists only inside Terraform. - Confusing
resourcewithdata. If you writedataexpecting to create something, Terraform will fail saying the object does not exist. - Overusing
depends_on. It serialises the graph and slows deployments down. Use it only when the dependency cannot be expressed with a reference. - Ignoring the plan's
-/+. That is the symbol that destroys and recreates. On a production database it means data loss. Always look for the# forces replacementcomment to understand which argument caused it. - Reading only the plan's last line.
Plan: 3 to add, 0 to change, 1 to destroydoes not say what is being destroyed. Read the body. - Versioning
terraform.tfstate. On top of the merge conflicts, it is a secrets leak. - Ignoring
.terraform.lock.hcl. Without it, each machine may install a different provider version and get different plans from the same code. - Confusing
.terraform/terraform.tfstatewith./terraform.tfstate. The first (inside the hidden directory) stores the backend's configuration; the second is the real state. Deleting the second is catastrophic. - Tip: use
terraform consoleto experiment. It is free, it touches nothing and it speeds up learning the language enormously. - Tip: get into the habit of
terraform plan -out=plan.tfplanfollowed byterraform apply plan.tfplan. It guarantees you apply exactly what you reviewed.
Exercises
Exercise 1: reading a plan
The EcoMarket team receives this terraform plan output before a deployment to prod:
Terraform will perform the following actions:
# local_file.record will be created
+ resource "local_file" "record" { ... }
# local_file.inventory will be updated in-place
~ resource "local_file" "inventory" {
~ content = jsonencode({ ~ version = "1.3" -> "1.4" })
}
# random_password.db must be replaced
-/+ resource "random_password" "db" {
~ length = 16 -> 24 # forces replacement
~ result = (sensitive value)
}
Plan: 2 to add, 1 to change, 1 to destroy.Answer:
- How many resources are created, how many modified and how many destroyed, and why does the total not match the number of blocks shown?
- Why is
random_password.dbreplaced instead of updated? - What operational consequence does that replacement have for EcoMarket's database, and what would you do before applying?
Exercise 2: drawing the graph
Given this configuration fragment, draw (in text or in mermaid) the dependency graph and state which resources can be created in parallel:
resource "random_pet" "suffix" {
length = 2
}
resource "random_password" "db" {
length = 24
}
resource "local_file" "inventory" {
filename = "ecomarket-dev-${random_pet.suffix.id}.json"
content = jsonencode({ environment = "dev" })
}
resource "local_file" "credentials" {
filename = "ecomarket-dev-credentials.json"
content = jsonencode({ password = random_password.db.result })
}
resource "local_file" "summary" {
filename = "ecomarket-dev-summary.txt"
content = "Deployment completed\n"
depends_on = [
local_file.inventory,
local_file.credentials,
]
}Exercise 3: what goes into Git
The EcoMarket team has this listing after a while working in infra/. Classify each item as "versioned" or "ignored", justifying each decision in one line:
.terraform/ .terraform.lock.hcl .terraform-version main.tf variables.tf terraform.tfstate terraform.tfstate.backup ecomarket.tfplan terraform.tfvars .terraform.tfstate.lock.info
Solutions
Solution 1:
- 2 created, 1 modified, 1 destroyed. The total looks wrong because a replacement counts twice:
random_password.dbis counted both as "1 to destroy" (the old object) and as part of "2 to add" (the new object). So the 2 "add" entries arelocal_file.recordand the newrandom_password.db. - Because
lengthis an argument marked as forcing a new object in therandomprovider's schema. You cannot lengthen a password that has already been generated: you have to generate another one. Terraform flags this with the# forces replacementcomment. - The password will change. If that password is EcoMarket's database password, any resource or application using it will be out of sync until it is updated too. Before applying you would need to: (a) check which resources reference
random_password.db.result, (b) confirm that the application will pick up the new credential (from a secrets manager, not a static file), (c) schedule the change during a maintenance window, and (d) consider alifecycle { create_before_destroy = true }or a dual-credential strategy so the service is not interrupted.
Solution 2:
flowchart TD
RP["random_pet.suffix"] --> INV["local_file.inventory"]
RPW["random_password.db"] --> CRED["local_file.credentials"]
INV --> RES["local_file.summary"]
CRED --> RES
Parallelism by level:
| Level | Resources | Comment |
|---|---|---|
| 1 | random_pet.suffix, random_password.db |
No dependencies: created at the same time |
| 2 | local_file.inventory, local_file.credentials |
Each depends on a different level-1 resource; also in parallel |
| 3 | local_file.summary |
Waits for the previous two because of depends_on |
local_file.inventory and local_file.credentials do not depend on each other: even though they are written one after the other, Terraform creates them simultaneously. Destruction would walk the graph in reverse: summary first, then the two files, and finally the two random resources.
Solution 3:
| Item | Decision | Reason |
|---|---|---|
.terraform/ |
Ignore | Working directory, regenerable with terraform init |
.terraform.lock.hcl |
Version | Pins provider versions and hashes for the whole team and CI |
.terraform-version |
Version | Pins the binary version tfenv uses |
main.tf |
Version | It is the infrastructure's source code |
variables.tf |
Version | It declares the variables; it holds no sensitive values |
terraform.tfstate |
Ignore | It can contain secrets in plain text; its place is a remote backend |
terraform.tfstate.backup |
Ignore | Same reason: it is a copy of the state |
ecomarket.tfplan |
Ignore | An ephemeral binary artefact from one specific run |
terraform.tfvars |
It depends | If it only holds non-sensitive values (project name, region), version it; if it holds secrets or personal values, ignore it. At EcoMarket we will version it because it only carries public environment parameters |
.terraform.tfstate.lock.info |
Ignore | A temporary lock file; it exists only while an operation is under way |
Conclusion
You now command the vocabulary the rest of the course is written in:
- A provider is the plugin that translates Terraform's intentions into calls to a specific API; it is declared with its
sourceand itsversionconstraint. - A resource is an object Terraform creates, updates and destroys; its address is
type.local_name. A data source only reads, and carries thedata.prefix. - Arguments are written by you; attributes are returned by the provider, which is why
(known after apply)shows up in plans. - The state is the record of what Terraform believes exists: the source of truth, a possible carrier of secrets, and what makes the declarative model work.
plantouches nothing,applydoes; saving the plan and applying that file is the professional practice.- The dependency graph builds itself from the references;
depends_onis the exceptional case. - The symbols
+ ~ -/+ -tell you at a glance whether a change is harmless or destructive;# forces replacementalways explains the reason behind a replacement. .terraform/is ignored in Git;.terraform.lock.hclis versioned, because it guarantees reproducibility and protects the supply chain.- Idempotence and convergence are the reason manual changes stop being invisible.
Enough theory. In the next lesson, Your First Terraform Configuration, the EcoMarket team will write its first real configuration end to end — with the local and random providers, no cloud account and no credit card — and run init, fmt, validate, plan, apply and destroy, analysing each command's output line by line.
