Learn Terraform · 6/11

Advanced HCL & Logic

7 min read

Advanced HCL & Logic

Hello there, Cloud Architect! 🏗️ Welcome to Module 6.

Up until now, your Terraform code has likely been very "static." You declare a bucket, you get a bucket. You declare a server, you get a server. It’s reliable, but let’s be honest—it’s a bit repetitive. It’s like writing a grocery list where you have to write "Apple" on 10 separate lines because you want 10 apples.

Today, we are unlocking the programming superpowers of HCL (HashiCorp Configuration Language). We are going to make your code smart. We will teach your code to make decisions, multiply resources automatically, and iterate through data like a pro.

⚠️ Warning: Once you learn for_each, you will never want to go back. It's addictive.


1. Conditional Expressions: If-This-Then-That

Before we build complex loops, we need to learn the alphabet of logic: The Condition.

Definition

A conditional expression uses the value of a boolean expression to select one of two values. It looks exactly like the ternary operator found in JavaScript, Python, or Java.

Syntax:

hcl
condition ? true_val : false_val

The Problem it Solves

Imagine you have a main.tf file. You want to create a powerful (and expensive) database server for Production, but a tiny, cheap one for Development.

Without logic, you would need two separate configuration files or manually change the code every time you run it. That leads to "Human Error" (the leading cause of "Why is the site down?").

The Solution

We use a conditional expression to dynamically select values based on an input variable.

Practical Example: The Environment Toggle

Let's say we have a variable env.

hcl
variable "env" {
  description = "The deployment environment (dev or prod)"
  type        = string
  default     = "dev"
}

resource "aws_instance" "app_server" {
  ami           = "ami-12345678"
  # IF env is prod, use t3.large, ELSE use t3.micro
  instance_type = var.env == "prod" ? "t3.large" : "t3.micro"
}

🧠 Industry Standard Tip: The "Count" Toggle

A very common pattern in the industry is using conditionals to decide whether to create a resource at all. Terraform doesn't have an enabled = true flag for resources. Instead, we use count combined with math.

If the condition is true, we set count to 1. If false, count is 0 (which means create nothing).

hcl
variable "enable_monitoring" {
  type    = bool
  default = false
}

resource "aws_cloudwatch_metric_alarm" "cpu_alert" {
  # If enable_monitoring is true, return 1, else return 0
  count = var.enable_monitoring ? 1 : 0

  alarm_name = "cpu-high"
  # ... other config ...
}

2. The count Meta-Argument

Definition

count is a meta-argument defined by the Terraform language. It can be used with modules and every resource type. It tells Terraform to create that many instances of the resource or module.

The Problem it Solves

You need 5 EC2 instances for a web cluster.
Without count: You copy-paste the resource "aws_instance" block 5 times. Your file is 200 lines long.
With count: You write the block once, set count = 5, and go grab a coffee.

The Solution

Terraform creates an internal array (list) of these resources. You can access the current iteration number using count.index.

Practical Example

hcl
resource "aws_instance" "web" {
  count         = 3 # Create 3 copies
  ami           = "ami-12345678"
  instance_type = "t3.micro"

  tags = {
    # count.index starts at 0. So: Web-0, Web-1, Web-2
    Name = "Web-Server-${count.index}"
  }
}

💥 The "Gotcha" (Critical Industry Knowledge)

count relies on a numerical index (0, 1, 2).
If you have a list of names ["Alice", "Bob", "Charlie"] and you create IAM users using count:

  1. Index 0: Alice
  2. Index 1: Bob
  3. Index 2: Charlie

Scenario: Bob quits the company. You remove "Bob" from the list.
New List: ["Alice", "Charlie"]

Terraform sees:

  1. Index 0: Alice (Unchanged)
  2. Index 1: Charlie (Changed from Bob)

Terraform will destroy Bob's user and update/recreate Charlie's user to match Index 1. This is disastrous for stateful resources like databases or subnets.

Rule of Thumb: Use count only for identical resources where the specific identity doesn't matter (like a pool of identical web servers). For everything else, use for_each.


3. The for_each Meta-Argument

Definition

for_each accepts a map or a set of strings, and creates an instance for each item in that map or set.

The Problem it Solves

It solves the "Bob/Charlie" shifting index problem described above. It allows you to reference resources by key (names) rather than index (numbers).

The Solution

When you use for_each, the resource object exposes:

  • each.key: The map key (or value if it's a set).
  • each.value: The value associated with the key.

Practical Example: Managing IAM Users safely

hcl
variable "user_roles" {
  type = map(string)
  default = {
    "alice"   = "admin"
    "bob"     = "developer"
    "charlie" = "auditor"
  }
}

resource "aws_iam_user" "employees" {
  for_each = var.user_roles

  name = each.key
  
  tags = {
    Role = each.value
  }
}

If we remove "bob" from the map, Terraform sees that the key "bob" is gone and destroys only that resource. "alice" and "charlie" are untouched. This is Stability.

🧪 Simulation: Validating Inputs

You can also use for_each with a set if you don't have key-value pairs, just a list of unique names.

hcl
variable "subnet_names" {
  type    = list(string)
  default = ["subnet-a", "subnet-b"]
}

resource "aws_subnet" "main" {
  # distinct() ensures unique values, toset() converts list to set
  for_each = toset(var.subnet_names) 
  
  cidr_block = "10.0.1.0/24" # (Simplified for example)
  
  tags = {
    Name = each.key
  }
}

4. Dynamic Blocks: Nested Logic

Definition

Dynamic blocks act like a for_each loop, but inside a resource block. They are used to generate repeatable nested blocks (like ingress rules in a Security Group, or lifecycle_rule in an S3 bucket).

The Problem it Solves

Standard count and for_each repeat the entire resource. But what if the resource is unique (like one Load Balancer), but it needs 10 listeners?
Before dynamic blocks, you had to copy-paste the ingress { ... } block inside the resource 10 times.

The Solution

Use dynamic "block_name". It iterates over a complex variable and generates the nested configuration.

Practical Example: Security Groups

Imagine defining a list of ports you want to open in a variable, rather than writing code for each one.

hcl
variable "ingress_rules" {
  description = "List of ports to open"
  type = list(object({
    port        = number
    description = string
  }))
  default = [
    { port = 80,  description = "HTTP" },
    { port = 443, description = "HTTPS" },
    { port = 22,  description = "SSH" }
  ]
}

resource "aws_security_group" "web_sg" {
  name = "web-server-sg"

  # Start the dynamic block
  dynamic "ingress" {
    for_each = var.ingress_rules
    
    # "iterator" is optional. If skipped, use the name of the dynamic block (ingress)
    # We will use 'rule' here for clarity.
    iterator = rule 

    content {
      from_port   = rule.value.port
      to_port     = rule.value.port
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
      description = rule.value.description
    }
  }
}

🧐 Under the Hood

Terraform expands this dynamic block before making the API call to AWS. It literally generates the configuration text in memory as if you had typed out three separate ingress blocks.

Best Practice

Don't overuse Dynamic Blocks. If you have a single ingress rule, just write it out normally. Only use Dynamic Blocks when the configuration is repetitive or depends on input variables that change frequently. Readable code > Clever code.


Summary

  1. Conditionals (? :): Use for simple logic or toggling resources (0 vs 1).
  2. count: Good for creating N identical copies. Bad for lists where items might be removed from the middle.
  3. for_each: The gold standard for creating resources based on maps/sets. Stable indexing.
  4. Dynamic Blocks: Used for loops inside a resource configuration.

You are now essentially a Terraform Programmer. You aren't just configuring; you are scripting logic. Go forth and automate! 🚀


📚 References & Further Reading

Challenge

Challenge: Create a Dynamic AWS S3 Bucket Configuration

Your task is to write a Terraform configuration for a single aws_s3_bucket resource that is highly dynamic and reusable. You will use advanced HCL features to control its creation, configuration, and sub-resources based on input variables.

Requirements:

  1. Conditional Creation: The entire S3 bucket resource should only be created if the enable_bucket variable is true.
  2. Dynamic Versioning: The bucket's versioning configuration block should only be included if the enable_versioning variable is true. When enabled, the status must be set to Enabled.
  3. Dynamic Lifecycle Rules: Create multiple lifecycle_rule blocks within the bucket resource. These rules must be generated dynamically from the lifecycle_rules map variable. Each rule in the map should translate to a corresponding lifecycle_rule block inside the S3 bucket resource.
    • Map the id from the variable to the rule's id.
    • Map the enabled boolean from the variable to the rule's status (which should be Enabled or Disabled).
    • Map the prefix from the variable to the rule's prefix.
    • Map expiration_days to the days argument inside an expiration block.
  4. Tagging: Assign all tags from the common_tags map variable to the bucket.

Expected result

Your code should consist of a single aws_s3_bucket resource block that correctly implements all the specified dynamic features.

A correct solution will have the following structure:

hcl
resource "aws_s3_bucket" "this" {
  # 1. Conditional creation using the 'count' meta-argument
  count  = var.enable_bucket ? 1 : 0

  bucket = var.bucket_name
  tags   = var.common_tags

  # 2. Conditional versioning block using a dynamic block
  dynamic "versioning" {
    for_each = var.enable_versioning ? [1] : []
    content {
      enabled = true
    }
  }

  # 3. Dynamic lifecycle rules using a dynamic block
  dynamic "lifecycle_rule" {
    for_each = var.lifecycle_rules

    content {
      id      = lifecycle_rule.value.id
      prefix  = lifecycle_rule.value.prefix
      enabled = lifecycle_rule.value.enabled

      expiration {
        days = lifecycle_rule.value.expiration_days
      }
    }
  }
}

Verification Checklist:

  • The resource is aws_s3_bucket and named this.
  • count is set to var.enable_bucket ? 1 : 0.
  • bucket and tags arguments are correctly assigned from their respective variables.
  • A dynamic "versioning" block is present and its for_each is set to var.enable_versioning ? [1] : [].
  • A dynamic "lifecycle_rule" block is present and its for_each iterates over var.lifecycle_rules.
  • The content block for lifecycle_rule correctly maps the id, prefix, enabled status, and the nested expiration block with days from the iterator's value.
hcl

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.