0
0
Terraformcloud~30 mins

Optional attributes in objects in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
Optional attributes in objects
📖 Scenario: You are setting up a Terraform configuration to manage cloud resources. Some resources have optional settings that you want to include only if needed.
🎯 Goal: Build a Terraform variable with an object type that includes optional attributes, then use it in a resource configuration.
📋 What You'll Learn
Create a Terraform variable named server_config with an object type that has required and optional attributes
Add a default value for server_config with only the required attributes set
Write a local value that sets a final configuration object using the variable, including optional attributes only if they are defined
Use the final configuration object in a resource block with the correct attribute references
💡 Why This Matters
🌍 Real World
Cloud infrastructure often requires flexible configurations where some settings are optional. This project shows how to handle optional attributes cleanly in Terraform.
💼 Career
Understanding optional attributes in Terraform objects is essential for cloud engineers and DevOps professionals to write adaptable and maintainable infrastructure code.
Progress0 / 4 steps
1
Define the server_config variable with required and optional attributes
Create a Terraform variable called server_config with an object type that has these attributes: name (string, required), cpu (number, required), and tags (map of strings, optional). Set the default value with name as "web-server" and cpu as 2.
Terraform
Need a hint?

Use optional() to mark the tags attribute as optional in the object type.

2
Create a local value to build the final server configuration
Add a local value called final_config that starts with server_config and adds tags only if server_config.tags is defined.
Terraform
Need a hint?

Use merge() with a conditional expression to add tags only if it exists.

3
Use final_config in a resource block
Create a resource block named cloud_server of type example_server that uses local.final_config.name for the name attribute, local.final_config.cpu for the cpu attribute, and includes local.final_config.tags only if it exists.
Terraform
Need a hint?

Use a dynamic block to include tags only if they exist.

4
Add an example override with tags in server_config
Update the default value of the server_config variable to include tags with environment = "production" and owner = "team-a".
Terraform
Need a hint?

Add the tags map inside the default value with the specified keys and values.