HCL basics: blocks, references and data sources
Terraform · 13 questions
Short notes
Key idea
HCL is built from blocks with a type, labels and arguments. Resources refer to each other's attributes, and Terraform uses those references to work out the order of creation. Data sources read things that exist outside your config.
Syntax
resource "google_bigquery_dataset" "sales" {
dataset_id = "sales"
location = "asia-south1"
}
resource "google_bigquery_table" "orders" {
dataset_id = google_bigquery_dataset.sales.dataset_id # reference
table_id = "orders"
}
data "google_project" "this" {}
# use: data.google_project.this.number
- Reference form:
TYPE.NAME.ATTRIBUTE. depends_ononly when there's a hidden dependency.count/for_eachcreate several copies.
Example
Because the table refers to google_bigquery_dataset.sales.dataset_id, Terraform creates the dataset first, with no ordering written by you.
Traps
- Hard-coding a value instead of referencing it loses the ordering and breaks if the name changes.
- Renaming a resource label looks like destroy + create; use a
movedblock. countwith a list shifts indexes when an item is removed;for_eachwith keys is safer.- Data sources fail if the thing doesn't exist yet.
Want the full lesson with step-by-step examples, a project and a certificate? Terraform course, ₹120 →
- Question 1easy
In
resource "google_storage_bucket" "landing" { ... }, what islanding? - Question 2medium
Which line correctly turns on versioning as a nested block?
- Question 3easy
Which type is
{ team = "data", env = "dev" }? - Question 4medium
You want the bucket name from
google_storage_bucket.landingin another resource. Which is right? - Question 5hard
When is
depends_onthe right tool?
HCL basics: blocks, references and data sources
HCL basics: blocks, references and data sources
HCL basics: blocks, references and data sources
HCL basics: blocks, references and data sources
HCL basics: blocks, references and data sources
8 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.