Terraform - Define variables using locals

by
Jeremy Canfield |
Updated: July 20 2023
| Terraform articles
Variables can be defined in a locals block. Let's say you have the following files on your Terraform server.
├── locals.tf
├── modules.tf
├── outputs.tf
├── provider.tf
├── terraform.tfstate
├── variables.tf
├── child (directory, child module)
│ ├── data.tf
│ ├── outputs.tf
│ ├── resources.tf
And let's say locals.tf has the following.
locals {
environment = "dev"
}
And let's say resources.tf in your child module has the following. In this example, the "environment" variable contains a value of "dev" to create an Amazon Web Services (AWS) Virtual Private Cloud (VPC) named dev-my-vpc.
resource "aws_vpc" "my-vpc" {
cidr_block = "10.0.0.0/16"
tags = {
Name = "${local.environment}-my-vpc"
}
}
Did you find this article helpful?
If so, consider buying me a coffee over at