Why Use Input Variables?
Hard-coding values limits the adaptability of your configuration. By leveraging input variables, you can easily update resource configurations without modifying multiple code sections. This not only improves maintenance but also supports better scaling practices.Using variables makes your configuration files more modular and easier to manage. Adjust values in a single file to propagate changes across your infrastructure.
Traditional Hard-Coded Resources
Consider the following example where resource attributes are hard-coded:Parameterizing with Variables
To parameterize these values, create a configuration file namedvariables.tf. In this file, you define each variable using the variable keyword and can optionally assign a default value:
main.tf file to reference these variables. You achieve this by prefixing the variable name with var.:
- Execute
terraform planto view the planned changes. - Execute
terraform applyto deploy the resources with the variable values.
Updating Variables
You can modify your infrastructure by simply updating the default values invariables.tf. For instance, to change the file content and adjust the length of the random pet’s name, you might update the file as follows:
terraform apply again, Terraform updates the resources accordingly—the file content will change, and the pet name will now consist of two parts following the prefix.