0
0
Terraformcloud~30 mins

Null values handling in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
Null values handling
📖 Scenario: You are setting up a Terraform configuration to create cloud resources. Sometimes, certain optional values might not be provided, and you want to handle these null values safely to avoid errors.
🎯 Goal: Build a Terraform configuration that defines a variable which can be null, then use a default value when the variable is null to configure a resource properly.
📋 What You'll Learn
Create a variable called instance_type that can accept null values
Define a local variable final_instance_type that uses instance_type if it is not null, otherwise uses "t2.micro"
Create an AWS EC2 instance resource that uses final_instance_type as its instance type
Ensure the configuration is valid and deployable
💡 Why This Matters
🌍 Real World
Cloud infrastructure often requires optional configuration values. Handling null values safely prevents deployment errors and allows flexible configurations.
💼 Career
Knowing how to handle null values in Terraform is essential for cloud engineers and DevOps professionals to write robust infrastructure as code.
Progress0 / 4 steps
1
Define a variable that can be null
Create a Terraform variable called instance_type of type string that allows null values and has no default value.
Terraform
Need a hint?

Use nullable = true to allow the variable to accept null values.

2
Create a local variable with a default fallback
Add a local variable called final_instance_type that uses the value of var.instance_type if it is not null, otherwise uses the string "t2.micro".
Terraform
Need a hint?

Use a conditional expression to check if var.instance_type is null.

3
Create an AWS EC2 instance resource using the local variable
Create a resource of type aws_instance named example that uses local.final_instance_type as the value for instance_type. Use ami = "ami-12345678" as a placeholder AMI ID.
Terraform
Need a hint?

Use local.final_instance_type for the instance_type attribute.

4
Add provider configuration for AWS
Add a provider block for aws with region set to us-east-1 to complete the configuration.
Terraform
Need a hint?

The provider block is required to deploy AWS resources.