TECHNOLOGIESTieInn Technologies

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_on only when there's a hidden dependency.
  • count / for_each create 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 moved block.
  • count with a list shifts indexes when an item is removed; for_each with 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 →

Questions

Open in Code Lab5 free questions
5 questions

    HCL basics: blocks, references and data sources

  1. Question 1easy

    In resource "google_storage_bucket" "landing" { ... }, what is landing?

  2. HCL basics: blocks, references and data sources

  3. Question 2medium

    Which line correctly turns on versioning as a nested block?

  4. HCL basics: blocks, references and data sources

  5. Question 3easy

    Which type is { team = "data", env = "dev" }?

  6. HCL basics: blocks, references and data sources

  7. Question 4medium

    You want the bucket name from google_storage_bucket.landing in another resource. Which is right?

  8. HCL basics: blocks, references and data sources

  9. Question 5hard

    When is depends_on the right tool?

8 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.