Terraform Variables & Outputs – Interview Q&A
---
1. What are variables in Terraform?
Answer:
Variables in Terraform allow you to parameterize configurations and make them
reusable. They enable passing dynamic values during Terraform runs.
Example:
variable "region" {
description = "AWS region to deploy"
default = "us-east-1"
}
Summary: Variables let you customize Terraform configurations without changing
code.
---
2. How do you declare variables in Terraform?
Answer:
Use the variable block with optional attributes like type, default, and
description.
Example:
variable "instance_type" {
type = string
default = "t2.micro"
description = "EC2 instance type"
}
Summary: Declare variables using variable blocks with type and defaults.
---
3. How do you assign values to variables?
Answer:
Values can be assigned via CLI flags (-var), environment variables (TF_VAR_<name>),
.tfvars files, or default values in the variable block.
Example CLI:
terraform apply -var="region=us-west-2"
Example .tfvars file:
region = "us-west-2"
Summary: You assign variable values with CLI, env vars, files, or defaults.
---
4. What are variable types supported in Terraform?
Answer:
Terraform supports scalar types (string, number, bool), complex types (list, map,
object), and dynamic types.
Example:
variable "ports" {
type = list(number)
default = [80, 443]
}
Summary: Terraform variables can be simple or complex data types.
---
5. What are outputs in Terraform?
Answer:
Outputs let you extract and display information about your infrastructure after
deployment, which can be used for sharing data or chaining modules.
Example:
output "instance_ip" {
value = aws_instance.my_server.public_ip
description = "Public IP of the EC2 instance"
}
Summary: Outputs expose useful info from Terraform resources after apply.
---
6. How do you declare outputs in Terraform?
Answer:
Use the output block with a name, a value attribute, and optionally a description
and sensitive flag.
Example:
output "db_password" {
value = var.db_password
sensitive = true
}
Summary: Outputs are declared with the output block showing resource info.
---
7. How can you mark outputs as sensitive?
Answer:
By setting sensitive = true in the output block, Terraform hides the output value
in the console and logs to prevent accidental exposure.
Example:
output "api_key" {
value = var.api_key
sensitive = true
}
Summary: Use sensitive = true to protect secrets in output values.
---
8. How do variables and outputs work in modules?
Answer:
Modules accept input variables to customize their behavior and return outputs that
can be consumed by the calling configuration.
Example:
module "webserver" {
source = "./modules/webserver"
instance_type = var.instance_type
}
output "webserver_ip" {
value = module.webserver.ip
}
Summary: Modules use variables for inputs and outputs to share results.