Define input variables
You now have enough Terraform knowledge to create useful configurations, but the examples so far have used hard-coded values. Terraform configurations can include variables to make your configuration more dynamic and flexible.
Note
This tutorial builds on configuration from an earlier tutorial. If you have not yet completed it, do so now.
Define your variables
In your learn-terraform-azure
directory, create a new file called
variables.tf
. Copy and paste the variable declaration below.
This declaration includes a default value for the variable, so the
resource_group_name
variable will not be a required input.
Update your Terraform configuration with your variables
Update your azurerm_resource_group
configuration to use the input variable for the resource group name. Modify the virtual machine block as follows:
Apply your configuration
Re-run terraform apply
to recreate your infrastructure using input variables. Respond yes
to the prompt to confirm the operation.
Now apply the configuration again, this time overriding the default resource
group name by passing in a variable using the -var
flag. Updating the
resource group name is a destructive update that forces Terraform to recreate the
resource, and in turn the virtual network that depends on it. Respond to the
confirmation prompt with yes
to rename the resource group and create the new resources.
Setting variables via the command-line will not save their values. Terraform supports many ways to use and set variables so you can avoid having to enter them repeatedly as you execute commands. To learn more, follow our in-depth tutorial, Customize Terraform Configuration with Variables.