Parameterize with variables
Learn
Variables: parameters
variable "cpu" {
default = 2
}
resource "demo_server" "web" {
cpu = var.cpu
}
Declare a variable block, then reference it as var.<name>. A default makes it
optional. Now the value lives in one place instead of being sprinkled through the
resource.
A variable without a default is required: Terraform asks for it, or takes it from
a -var flag, a .tfvars file, or a TF_VAR_<name> environment variable. That's how
one configuration serves several environments: same code, different inputs.
Refactoring hard-coded values into variables doesn't change what gets built. The plan
is the same server as before, Plan: 1 to add, with cpu = 2 filled in from the
variable's default.
Your task
Pull the hard-coded values out into inputs. Declare variable "server_name" (default "web") and variable "cpu" (default 2), then reference them in the server as var.server_name and var.cpu. Run plan — it should still be Plan: 1 to add, 0 to change, 0 to destroy. (same server, just parameterized).