0
0
Terraformcloud~30 mins

Conditional expressions (ternary) in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Conditional Expressions (Ternary) in Terraform
📖 Scenario: You are setting up a Terraform configuration to deploy cloud resources. You want to control the size of a virtual machine based on an environment variable. If the environment is 'production', the VM should be large; otherwise, it should be small.
🎯 Goal: Build a Terraform configuration that uses a conditional expression (ternary) to set the VM size based on the environment variable.
📋 What You'll Learn
Create a variable called environment with default value 'development'.
Create a local variable called vm_size that uses a conditional expression to set 'large' if environment is 'production', else 'small'.
Create a resource block for a virtual machine that uses the vm_size local variable.
Ensure the configuration is valid Terraform syntax.
💡 Why This Matters
🌍 Real World
Conditional expressions help automate infrastructure decisions based on environment or other inputs, making deployments flexible and reusable.
💼 Career
Cloud engineers often use Terraform conditionals to manage different deployment environments efficiently.
Progress0 / 4 steps
1
Define the environment variable
Create a Terraform variable called environment with type string and default value "development".
Terraform
Need a hint?

Use the variable block with type and default attributes.

2
Create a local variable vm_size with a conditional expression
Add a locals block and inside it create a local variable called vm_size that uses a conditional expression: if var.environment equals "production", set vm_size to "large", else set it to "small".
Terraform
Need a hint?

Use the syntax condition ? true_value : false_value inside the locals block.

3
Create a resource using the vm_size local variable
Add a resource block named aws_instance with resource name example. Set the instance_type attribute to use the local variable local.vm_size. Use ami attribute with a placeholder value "ami-12345678".
Terraform
Need a hint?

Use the resource block with the correct resource type and name. Reference the local variable with local.vm_size.

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

The provider block tells Terraform which cloud provider to use and the region.