Variables
This lesson will address Terraform variables and their uses.
We'll cover the following
Terraform variables#
A variable in Terraform is something that can be set at runtime. It allows you to vary what Terraform will do by passing in or using a dynamic value.
Our first Variable#
Let’s dive into an example of how to use variables so we can learn how they work:
You declare a variable by using the keyword variable, and then specify the identifier for the variable in quotes. We are using "bucket_name" as the identifier. Inside the variable block, we add a description to describe to the user what this variable is used for. The description parameter is completely optional. We could have defined the variable as follows:
variable "bucket_name" {}
📝Note: It is often a good idea to provide a
descriptionas it gives the user some indication as to what values to use and what thevariableis used for.
To use the value of a variable in our Terraform code, we use the syntax var.<variable_identifier>. We set the bucket property on the aws_s3_bucket resource to the value of
our variable var.bucket_name. This means that Terraform will use whatever value we give our variable as the name of the S3 bucket.
Running the project#
After clicking the terminal, terraform init and terraform apply will run. Terraform will then pause and you will see the following output:
Terraform has paused because it is asking you to provide a value for the variable. The variable name
is printed to the screen and underneath is the description we provided.
📝Note: If you do not set a description, only the variable name will be shown here.
Steps you should follow to run the project:
-
Type in a bucket name that you think will be unique. I used
kevholditch-variable-bucketbut it really doesn’t matter what value you use. -
Press enter. You will notice that Terraform will pause again and ask if you want to apply the changes.
-
Type
yesand create the bucket. Terraform will have created the bucket with a name of whatever value you gave it.
Destroy the project#
Once you have run the project go ahead and destroy it again:
-
Run
terraform destroy.Terraform will ask you for a value for the variable again. It doesn’t actually matter what value you give it this time as the
variableis not needed for Terraform to destroy the bucket. -
Press enter and then type
yeswhen Terraform asks you if you really want to destroy the project.
