0
0
Terraformcloud~30 mins

Object type definition in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
Terraform Object Type Definition
📖 Scenario: You are setting up a Terraform configuration to manage cloud resources. You want to define a clear structure for a server configuration using an object type. This helps you organize server details like name, CPU count, and memory size.
🎯 Goal: Create a Terraform variable with an object type that defines a server configuration with specific attributes.
📋 What You'll Learn
Define a variable named server_config with an object type
The object must have attributes: name (string), cpu (number), and memory (number)
Assign default values: name as "web-server", cpu as 4, and memory as 8192
💡 Why This Matters
🌍 Real World
Defining object types in Terraform helps organize complex configurations like server setups, making infrastructure code clearer and easier to maintain.
💼 Career
Cloud engineers and DevOps professionals use Terraform object types to create reusable and structured infrastructure modules.
Progress0 / 4 steps
1
Create the initial variable declaration
Create a Terraform variable named server_config with type object having attributes name (string), cpu (number), and memory (number). Do not add default values yet.
Terraform
Need a hint?

Use variable "server_config" {} block and define type = object({...}) with the attributes inside.

2
Add default values to the object variable
Add a default attribute to the server_config variable with values: name as "web-server", cpu as 4, and memory as 8192.
Terraform
Need a hint?

Use default = { name = "web-server", cpu = 4, memory = 8192 } inside the variable block.

3
Reference the object variable in a resource
Create a Terraform resource aws_instance named example that uses the server_config variable's attributes for instance_type and tags.Name. Use cpu to decide instance type as "t3.medium" if cpu is 2, otherwise "t3.large". Use server_config.name for the tag.
Terraform
Need a hint?

Use a conditional expression for instance_type and reference var.server_config.name for tags.

4
Add memory attribute usage in user_data
Add a user_data attribute to the aws_instance.example resource that echoes the memory size from server_config.memory in megabytes using a shell command.
Terraform
Need a hint?

Use a heredoc for user_data and include the memory value with interpolation.