0
0
Terraformcloud~30 mins

Why expressions add logic in Terraform - See It in Action

Choose your learning style9 modes available
Why expressions add logic
📖 Scenario: You are setting up a simple cloud infrastructure using Terraform. You want to create a variable that decides the size of a virtual machine based on a condition. This helps you understand how expressions add logic to your infrastructure code.
🎯 Goal: Build a Terraform configuration that uses a count expression with a condition to decide how many virtual machines to create based on a variable.
📋 What You'll Learn
Create a variable called create_vm with a boolean value
Create a local variable called vm_count that uses a conditional expression based on create_vm
Use the vm_count variable in the count argument of a resource
Define a simple aws_instance resource that uses the count to create instances
💡 Why This Matters
🌍 Real World
Cloud engineers often need to create resources conditionally based on environment or user input. Expressions let them add simple logic to infrastructure code.
💼 Career
Understanding expressions and conditional logic in Terraform is essential for writing flexible and reusable infrastructure as code.
Progress0 / 4 steps
1
Create a variable to control VM creation
Create a Terraform variable called create_vm of type bool and set its default value to true.
Terraform
Need a hint?

This variable will control if the VM should be created or not.

2
Add a local variable with a conditional expression
Create a local variable called vm_count that uses a conditional expression: if var.create_vm is true, set vm_count to 1, else 0.
Terraform
Need a hint?

Use the ternary operator ? : to add logic in the local variable.

3
Use the local variable in a resource count
Create an aws_instance resource called example that uses count = local.vm_count to decide how many instances to create. Use ami = "ami-12345678" and instance_type = "t2.micro" as fixed values.
Terraform
Need a hint?

The count argument controls how many instances are created.

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

The provider block tells Terraform which cloud to use.