Skip to content

Data & Locals

Locals in Terraform allow you to define values that are computed from expressions. You can use locals to simplify your infrastructure code and make it more readable. Here’s an example of how you can define a local in Terraform:

locals {
region = "us-west-2"
ami = lookup(data.aws_ami.ubuntu, "id")
}

In this example, we define a local called region that has a value of us-west-2. We also define a local called ami that looks up the ID of an Ubuntu AMI using a data resource. You can reference these locals later in your Terraform code by using the ${local.region} and ${local.ami} syntax.

locals are often stored in a file called locals.tf. There is no strict requirement for this, however it could be considered a best practice for organizing your Terraform code, especially in larger projects to help keep your code readable, and maintainable.

Data resources in Terraform allow you to retrieve data from an external data source, such as an AWS EC2 instance, an AWS S3 bucket, or a DNS record. You can use data resources to obtain information that is required to provision infrastructure resources. Here’s an example of how you can define a data resource in Terraform:

Using a data resource, over using a fixed value or even an input, gives you an advantage when wanting to keep your infrastructure up-to-date. For example, you can always ensure that your EC2 instance is always using the latest AMI, when you deploy avoiding the need to update hardcoded AMI IDs whenever there is a change.

data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"]
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
}
}

In this example, we define a data resource called aws_ami that retrieves the ID of the most recent Ubuntu AMI that matches a specific naming pattern. We use this data resource to obtain the ID of the Ubuntu AMI that we want to launch.


Variables, locals, and data resources are essential concepts in Terraform that allow you to organize and manage your infrastructure resources more effectively.

With locals, you can define values that are computed from expressions, making your infrastructure code more readable.

Using data resources, you can retrieve information from external data sources, such as an AWS EC2 instance or an S3 bucket, to provision your infrastructure resources.