Sling Academy
Home/DevOps/How to use local variables to simplify your Terraform code

How to use local variables to simplify your Terraform code

Last updated: February 03, 2024

Introduction

Streamlining Terraform code is essential for developing robust, manageable, and scalable infrastructure as code (IaC) solutions. This tutorial delves into the strategic use of local variables to enhance code readability, maintainability, and reusability in Terraform. By integrating local variables, you can simplify complex expressions, reduce duplication, and make your configurations easier to understand and update.

Getting Started with Local Variables

Local variables in Terraform are named values that you can reference throughout a module. Unlike input variables that are set by users or external sources when Terraform is executed, local variables are defined within your Terraform configurations and used to simplify expressions and manage repeated values.

locals {
  common_tags = {
    Owner = "DevOps Team"
    Environment = "Production"
  }
}

Basic Usage of Local Variables

Let’s start with a simple example of how local variables can make your Terraform code cleaner. Imagine you have multiple resources that share common tags.

resource "aws_instance" "example" {
  ami = "ami-123456"
  instance_type = "t2.micro"
  tags = {
    Name = "ExampleInstance",
    Environment = "${local.common_tags.Environment}",
    Owner = "${local.common_tags.Owner}"
  }
}

This illustration shows how locals can reduce repetitiveness by centralizing shared values. Now, instead of duplicating the tag information for each resource, you can refer to the local variable common_tags.

Intermediate Examples

As you become more comfortable with local variables, you can start leveraging them for more complex scenarios.

locals {
  resource_prefix = "dev-${var.environment}"
}

resource "aws_s3_bucket" "example" {
  bucket = "${local.resource_prefix}-data"
  acl = "private"
}

This example demonstrates how locals can be used to construct resource names dynamically based on input variables, making your configurations more flexible and environment-specific.

Advanced Usage

For more advanced Terraform users, local variables can be instrumental in handling complex data structures and conditionals. Consider this scenario where you need to conditionally include certain resource properties.

locals {
  instance_settings = {
    instance_type = "t2.micro",
    ami = var.use_custom_ami ? var.custom_ami : "ami-123456"
  }
}

resource "aws_instance" "advanced_example" {
  ami = local.instance_settings.ami
  instance_type = local.instance_settings.instance_type
  tags = local.common_tags
}

This setup highlights the power of local variables in managing conditional logic and complex data structures, simplifying your Terraform configurations significantly.

Managing Complexity with Local Variables

Using locals is not just about reducing duplication; it’s about making your codebase manageable and understandable. By encapsulating complex logic and repeated values within local variables, you can make your Terraform code more readable and easier to maintain. Furthermore, locals encourage the DRY (Don’t Repeat Yourself) principle, minimizing the risk of errors and inconsistencies.

Conclusion

Incorporating local variables into your Terraform code can vastly simplify your configurations, making them more maintainable, readable, and flexible. Throughout this tutorial, we’ve seen how locals can transform your code from basic tag management to handling complex conditional logic and data structures. As your infrastructure grows in complexity, the strategic use of local variables will become increasingly valuable in your Terraform toolkit.

Next Article: How to use outputs to expose Terraform provisioned resources

Previous Article: Terraform: How to manipulate variables

Series: Terraform Tutorials

DevOps

You May Also Like

  • How to reset Ubuntu to factory settings (4 approaches)
  • Making GET requests with cURL: A practical guide (with examples)
  • Git: What is .DS_Store and should you ignore it?
  • NGINX underscores_in_headers: Explained with examples
  • How to use Jenkins CI with private GitHub repositories
  • Terraform: Understanding State and State Files (with Examples)
  • SHA1, SHA256, and SHA512 in Terraform: A Practical Guide
  • CSRF Protection in Jenkins: An In-depth Guide (with examples)
  • Terraform: How to Merge 2 Maps
  • Terraform: How to extract filename/extension from a path
  • JSON encoding/decoding in Terraform: Explained with examples
  • Sorting Lists in Terraform: A Practical Guide
  • Terraform: How to trigger a Lambda function on resource creation
  • How to use Terraform templates
  • Understanding terraform_remote_state data source: Explained with examples
  • Jenkins Authorization: A Practical Guide (with examples)
  • Solving Jenkins Pipeline NotSerializableException: groovy.json.internal.LazyMap
  • Understanding Artifacts in Jenkins: A Practical Guide (with examples)
  • Using Jenkins with AWS EC2 and S3: A Practical Guide