Locals in Detail
This lesson will cover Terraform local, how they work, and how to use them.
We'll cover the following
Terraform local#
A local is Terraform’s representation of a normal programming language variable. Confusingly, Terraform also has a concept called a variable which is really an input (variables are covered in the variables chapter). A local can refer to a fixed value such as a string, or it can be used to refer to an expression such as two other locals concatenated together.
Project example#
Let’s dive into an example:
Project code in detail#
In the code above:
-
We define a local block by using the keyword
locals
and then an opening{
. -
We define each local on a new line by giving it a name. The first local we define is called
first_part
. -
We then follow it with an
=
and give it a value. For thefirst_part
local, we give it the value of the string literalhello
. -
For the second local
second_part
, we are use the value"${local.first_part}-there"
. -
As the whole expression is inside quotes, we need to use the
${
and}
around our expression so Terraform evaluates it. -
To reference a local, we use the expression syntax
local.local_identifier
. -
The
second_part
local will be set to“hello-there”
. In thebucket_name
local, we are using thesecond_part
local in the expression"${local.second_part}-how-are-you-today"
which will evaluate tohello-there-how-are-you-today
.
- At the bottom of the project, we define an S3 bucket and set the name to
local.bucket_name
. This will create an S3 bucket with the namehello-there-how-are-you-today
.
📝Note: We do not need the
${
and}
as we are not inside quotes here.
-
We could also have set the bucket to
"${local.bucket_name}"
, which would be evaluated to the same thing.In Terraform version
1.0.0
, though, we can now omit the${
and}
for a single line expression where we are using the whole value. This makes the code cleaner and easier to read. Easily read code becomes vital when we define our infrastructure as code.
Running the project#
Clicking the terminal will run terraform init
and then terraform apply
. When prompted, enter yes
to run the project. This will create the S3 bucket with the name hello-there-how-are-you-today
.
📝Note: Kindly do change
bucket_name
before running the project.
/
- main.tf
📝Note: Once you are done with the project, do not forget to run
terraform destroy
and then confirm with yes to delete all of the resources in this project.
Locals referencing Resources#
Locals can reference the output of a resource or a data source by using the expression syntax we have learned. This allows you to give something a meaningful name or to combine outputs from different resource and data source attributes to build up a more complex value.