0
0
Terraformcloud~10 mins

Null values handling in Terraform - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to assign a default value if the variable is null.

Terraform
variable "instance_type" {
  type    = string
  default = [1]
}

resource "aws_instance" "example" {
  instance_type = var.instance_type != null ? var.instance_type : "t2.micro"
  ami           = "ami-123456"
}
Drag options to blanks, or click blank then click option'
A"t2.micro"
B"m5.large"
Cnull
D""
Attempts:
3 left
💡 Hint
Common Mistakes
Setting default to an empty string instead of null
Not handling null in the resource block
2fill in blank
medium

Complete the code to use the coalesce function to handle null values.

Terraform
resource "aws_s3_bucket" "example" {
  bucket = coalesce(var.bucket_name, [1])
  acl    = "private"
}
Drag options to blanks, or click blank then click option'
A"default-bucket"
Bnull
C""
D"public-bucket"
Attempts:
3 left
💡 Hint
Common Mistakes
Using null as fallback which causes errors
Using empty string which is invalid bucket name
3fill in blank
hard

Fix the error in the code to correctly handle null values in a list variable.

Terraform
variable "subnets" {
  type    = list(string)
  default = [1]
}

resource "aws_instance" "example" {
  count         = length(var.subnets)
  subnet_id     = var.subnets[count.index]
  ami           = "ami-123456"
  instance_type = "t2.micro"
}
Drag options to blanks, or click blank then click option'
A[]
B[""]
C[null]
Dnull
Attempts:
3 left
💡 Hint
Common Mistakes
Setting default to null instead of empty list
Using list with null element which causes index errors
4fill in blank
hard

Fill both blanks to create a map that excludes null values using the compact function.

Terraform
locals {
  raw_tags = {
    Name        = var.name
    Environment = var.environment
    Owner       = [1]
  }

  filtered_tags = zipmap(keys([2]), compact(values([2])))
}
Drag options to blanks, or click blank then click option'
Avar.owner
Blocal.raw_tags
Cvar.tags
Dvar.owner != null ? var.owner : "unknown"
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the wrong variable to compact
Using a conditional expression inside the map instead of compact
5fill in blank
hard

Fill all three blanks to safely access nested attributes that may be null using the lookup function.

Terraform
resource "aws_instance" "example" {
  ami           = lookup(var.ami_map, [1], [2])
  instance_type = lookup(var.instance_types, [3], "t2.micro")
}
Drag options to blanks, or click blank then click option'
A"us-east-1"
B"ami-123456"
C"us-west-2"
D"m5.large"
Attempts:
3 left
💡 Hint
Common Mistakes
Using values instead of keys in lookup
Not providing a default value causing errors