Complete the code to assign a default value if the variable is null.
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" }
The variable default is set to null to allow overriding. The resource uses a conditional to assign t2.micro if the variable is null.
Complete the code to use the coalesce function to handle null values.
resource "aws_s3_bucket" "example" { bucket = coalesce(var.bucket_name, [1]) acl = "private" }
The coalesce function returns the first non-null argument. If var.bucket_name is null, it uses "default-bucket".
Fix the error in the code to correctly handle null values in a list variable.
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" }
The default should be an empty list [] so length(var.subnets) returns 0 and count = 0, preventing index access errors. Null causes plan-time errors on length(null).
Fill both blanks to create a map that excludes null values using the compact function.
locals {
raw_tags = {
Name = var.name
Environment = var.environment
Owner = [1]
}
filtered_tags = zipmap(keys([2]), compact(values([2])))
}The raw_tags map includes var.owner which may be null. values(local.raw_tags) produces a list, compact removes nulls, and zipmap(keys(local.raw_tags), ...) reconstructs the map without null-value entries.
Fill all three blanks to safely access nested attributes that may be null using the lookup function.
resource "aws_instance" "example" { ami = lookup(var.ami_map, [1], [2]) instance_type = lookup(var.instance_types, [3], "t2.micro") }
The lookup function safely retrieves values from maps. It uses a key and a default if the key is missing or null. Here, "us-east-1" and "us-west-2" are keys, and "ami-123456" is the default AMI.