Bird
Raised Fist0
Terraformcloud~10 mins

Terraform file organization - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Process Flow - Terraform file organization
Start: Create main.tf
↓
Define provider and resources
↓
Create variables.tf
↓
Declare input variables
↓
Create outputs.tf
↓
Declare outputs
↓
Optional: Create terraform.tfvars
↓
Assign variable values
↓
Run terraform init & apply
↓
Infrastructure deployed
↓
End
Terraform files are organized by purpose: main.tf for resources, variables.tf for inputs, outputs.tf for outputs, and optional terraform.tfvars for variable values. This flow shows how these files work together to deploy infrastructure.
Execution Sample
Terraform
provider "aws" {
  region = var.region
}

resource "aws_s3_bucket" "bucket" {
  bucket = var.bucket_name
}
Defines AWS provider and an S3 bucket resource using variables for region and bucket name.
Process Table
StepFile ProcessedActionEffectNext Step
1main.tfRead provider and resource blocksProvider and resource defined with variable referencesProcess variables.tf
2variables.tfRead variable declarationsVariables region and bucket_name declaredProcess outputs.tf
3outputs.tfRead output declarationsOutputs defined for resource attributesCheck terraform.tfvars (optional)
4terraform.tfvarsRead variable valuesVariables assigned actual valuesRun terraform init
5terraform initInitialize working directoryPlugins downloaded, backend configuredRun terraform apply
6terraform applyApply configurationInfrastructure created with given variablesEnd
7-EndInfrastructure deployed successfully-
💡 All files processed and terraform commands run to deploy infrastructure.
Status Tracker
VariableDeclaredAssigned in terraform.tfvarsUsed in main.tfFinal Value
regionDeclared as string"us-east-1"Used in provider blockus-east-1
bucket_nameDeclared as string"my-unique-bucket"Used in resource bucket namemy-unique-bucket
Key Moments - 3 Insights
Why do we separate variables into variables.tf instead of putting them directly in main.tf?
Separating variables in variables.tf keeps main.tf focused on resources and makes it easier to manage inputs separately, as shown in execution_table steps 1 and 2.
What happens if terraform.tfvars is missing?
Terraform uses default variable values or prompts for input. Without terraform.tfvars (step 4), variables may be undefined causing errors or manual input.
Why do we have outputs.tf as a separate file?
Outputs.tf organizes outputs separately for clarity and reuse, as seen in step 3, making it easier to find what information Terraform will show after apply.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step are variable values assigned?
AStep 4
BStep 2
CStep 5
DStep 6
💡 Hint
Check the 'Action' column for 'Read variable values' in execution_table.
According to variable_tracker, what is the final value of 'bucket_name'?
Aus-east-1
BUndefined
Cmy-unique-bucket
Dbucket_name
💡 Hint
Look at the 'Final Value' column for 'bucket_name' in variable_tracker.
If we remove outputs.tf, what impact is shown in the execution flow?
ATerraform apply will fail at step 6
BOutputs will not be declared or shown after apply
CVariables will not be assigned
DProvider will not initialize
💡 Hint
Refer to execution_table step 3 about outputs.tf role.
Concept Snapshot
Terraform files are organized by role:
- main.tf: resources and provider
- variables.tf: input variable declarations
- outputs.tf: output declarations
- terraform.tfvars: variable values
This separation keeps configs clean and manageable.
Full Transcript
Terraform file organization involves splitting configuration into files by their purpose. The main.tf file contains provider and resource definitions, referencing variables declared in variables.tf. Outputs.tf declares outputs to show after deployment. Optionally, terraform.tfvars assigns values to variables. The process starts by reading main.tf, then variables.tf, outputs.tf, and terraform.tfvars if present. Terraform commands init and apply then deploy the infrastructure. Variables track from declaration to assignment and usage. This organization helps keep Terraform projects clear and easy to manage.

Practice

(1/5)
1. What is the main purpose of organizing Terraform files into separate files like main.tf, variables.tf, and outputs.tf?
easy
A. To avoid using variables in the configuration
B. To reduce the number of resources created
C. To speed up Terraform apply operations
D. To make the code easier to read and maintain

Solution

  1. Step 1: Understand file separation purpose

    Separating files by purpose helps organize code logically, making it easier to find and update parts.
  2. Step 2: Recognize benefits of organization

    This organization improves readability and maintainability but does not affect resource count or speed directly.
  3. Final Answer:

    To make the code easier to read and maintain -> Option D
  4. Quick Check:

    File organization = easier maintenance [OK]
Hint: Think about how folders help organize papers [OK]
Common Mistakes:
  • Confusing file organization with resource optimization
  • Thinking it speeds up Terraform operations
  • Believing variables are avoided by file separation
2. Which of the following is the correct way to declare a variable in a separate variables.tf file?
easy
A. variable "instance_type" { default = "t2.micro" }
B. var instance_type = "t2.micro"
C. variable instance_type = "t2.micro"
D. var "instance_type" { default = "t2.micro" }

Solution

  1. Step 1: Recall Terraform variable syntax

    Terraform variables are declared with the keyword variable followed by the variable name in quotes and a block with attributes.
  2. Step 2: Match correct syntax

    variable "instance_type" { default = "t2.micro" } matches the correct syntax: variable "name" { default = "value" }. Other options use invalid syntax.
  3. Final Answer:

    variable "instance_type" { default = "t2.micro" } -> Option A
  4. Quick Check:

    Correct variable syntax = variable "instance_type" { default = "t2.micro" } [OK]
Hint: Variables use 'variable' keyword with quotes and braces [OK]
Common Mistakes:
  • Omitting quotes around variable name
  • Using 'var' instead of 'variable' keyword
  • Assigning variable like a normal programming variable
3. Given these files:
main.tf:
resource "aws_instance" "web" {
  ami           = var.ami_id
  instance_type = var.instance_type
}

variables.tf:
variable "ami_id" {}
variable "instance_type" {}

outputs.tf:
output "instance_id" {
  value = aws_instance.web.id
}

What will Terraform output after apply if the instance ID is i-1234567890abcdef0?
medium
A. "instance_id" = "i-1234567890abcdef0"
B. "instance_type" = "i-1234567890abcdef0"
C. "ami_id" = "i-1234567890abcdef0"
D. No output will be shown

Solution

  1. Step 1: Identify output block purpose

    The outputs.tf file defines an output named instance_id that returns the ID of the AWS instance resource.
  2. Step 2: Match output value with resource ID

    After apply, Terraform shows outputs with their names and values. The output will show instance_id with the instance's actual ID.
  3. Final Answer:

    "instance_id" = "i-1234567890abcdef0" -> Option A
  4. Quick Check:

    Output name matches resource ID [OK]
Hint: Outputs show resource values by their output names [OK]
Common Mistakes:
  • Confusing variable names with output names
  • Expecting variables to show as outputs automatically
  • Thinking no output is shown without explicit output block
4. You have a variables.tf file with:
variable "region" {
  default = "us-east-1"
}

But Terraform apply fails with an error about missing provider configuration. What is the likely cause?
medium
A. Variables cannot have default values
B. The variable region must be declared in main.tf
C. The provider block is missing or not configured
D. Terraform requires region to be set in outputs.tf

Solution

  1. Step 1: Understand provider role

    Terraform needs a provider block to know which cloud and region to use. Variables alone do not configure providers.
  2. Step 2: Identify missing provider configuration

    If the provider block is missing or lacks region setting, Terraform cannot connect to the cloud, causing errors.
  3. Final Answer:

    The provider block is missing or not configured -> Option C
  4. Quick Check:

    Provider block required for cloud access [OK]
Hint: Always check provider block for cloud setup [OK]
Common Mistakes:
  • Assuming variables configure providers automatically
  • Placing variables in wrong files to fix provider errors
  • Expecting outputs to fix provider configuration
5. You want to organize a Terraform project with multiple environments (dev, prod). Which file organization approach is best practice?
hard
A. Use one main.tf and switch environment by changing variable defaults
B. Create separate folders for each environment, each with its own main.tf, variables.tf, and outputs.tf
C. Put all environments in one folder using different variable names
D. Store environment configs only in terraform.tfvars without separate folders

Solution

  1. Step 1: Understand environment isolation

    Separate folders per environment keep configurations isolated, avoiding accidental resource overlap.
  2. Step 2: Recognize best practice for clarity and safety

    Each folder having its own files allows independent management and clear separation of dev and prod.
  3. Final Answer:

    Create separate folders for each environment, each with its own main.tf, variables.tf, and outputs.tf -> Option B
  4. Quick Check:

    Separate folders = safer multi-env management [OK]
Hint: Use folders to separate environments clearly [OK]
Common Mistakes:
  • Mixing environments in one folder causing conflicts
  • Relying only on variable changes without folder separation
  • Not isolating state files per environment