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.
Prerequisites
After following the earlier tutorials, you will have a
directory named learn-terraform-aws-instance
with the following configuration
in a file called main.tf
.
Ensure that your configuration matches this, and that you have run terraform init
in the learn-terraform-aws-instance
directory.
Set the instance name with a variable
The current configuration includes a number of hard-coded values. Terraform variables allow you to write configuration that is flexible and easier to re-use.
Add a variable to define the instance name.
Create a new file called variables.tf
with a block defining a new
instance_name
variable.
Note
Terraform loads all files in the current directory ending in .tf
,
so you can name your configuration files however you choose.
In main.tf
, update the aws_instance
resource block to use the new variable.
The instance_name
variable block will default to its default value ("ExampleAppServerInstance") unless you declare a different value.
Apply your configuration
Apply the configuration. Respond to the confirmation prompt with a yes
.
Now apply the configuration again, this time overriding the default instance
name by passing in a variable using the -var
flag. Terraform will update the
instance's Name
tag with the new name. Respond to the confirmation prompt with yes
.
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.