Sling Academy
Home/DevOps/Using Regular Expressions in Terraform: A Practical Guide

Using Regular Expressions in Terraform: A Practical Guide

Last updated: February 03, 2024

Overview

Regular expressions (regex) can be a powerful tool in the arsenal of a Terraform developer, allowing for sophisticated string manipulation and validation within your infrastructure code. This tutorial will guide you through the practical application of regular expressions within Terraform, enhancing your infrastructure as code (IaC) workflows. From basic examples to more advanced scenarios, you will gain the knowledge to effectively integrate regex into your Terraform projects.

Regular Expressions in Terraform

Terraform, an open-source infrastructure as code software tool by HashiCorp, enables developers to define and provision infrastructure through a high-level configuration language. One of its lesser-known features is its ability to use regular expressions for string validation and manipulation, offering a flexible way to handle dynamic inputs and configurations.

Before diving into the examples, ensure you have Terraform installed and are familiar with its basic syntax and usage. If not, HashiCorp provides excellent documentation to get you started.

Basic Examples

Validating Email Addresses

variable "email" {
  description = "The email address to validate."
  type        = string
}

resource "null_resource" "validate_email" {
  triggers = {
    email = var.email
  }

  provisioner "local-exec" {
    command = "if [[ ${var.email} =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$ ]]; then echo 'Valid email'; else echo 'Invalid email'; fi"
  }
}

In this example, we use a basic regular expression to perform client-side validation of an email address. While more complex validations might require adjusting the regex pattern, this showcases a straightforward approach to integrating regex within a Terraform configuration.

Intermediate Examples

Extracting Substrings

variable "log_path" {
  type = string
}

resource "null_resource" "extract_substring" {
  triggers = {
    path = var.log_path
  }

  provisioner "local-exec" {
    command = "echo ${var.log_path} | grep -oP '(?<=/log/).*(?=.txt)'"
  }
}

This code snippet uses a Perl-compatible regular expression (PCRE) to extract a substring from a file path, specifically the filename without its extension. By utilizing the positive lookahead and lookbehind assertions, we can flexibly extract the needed information for further processing.

Advanced Examples

Validating and Transforming Input

variable "instance_name" {
  type = string
}

resource "null_resource" "name_validation_and_transform" {
  triggers = {
    name = var.instance_name
  }

  provisioner "local-exec" {
    command = "[[ ${var.instance_name} =~ ^[a-z]+([\-][a-z0-9]+)*$ ]] && echo ${var.instance_name} | sed 's/-/_/g'"
  }
}

This example demonstrates a more complex use case, combining validation and transformation of an input string. By first validating the input against a specific pattern, it then uses Unix’s sed command to transform dashes to underscores, showcasing a practical use case of regex in Terraform to enforce naming conventions and perform string manipulation.

Conclusion

Regular expressions in Terraform can drastically enhance your IaC practices, enabling sophisticated string manipulations and validations directly within your configuration files. By mastering the basics and gradually tackling more complex scenarios, you can leverage the full power of regex to make your configurations more dynamic and powerful.

Next Article: Terraform: How to check if a string contains a substring

Previous Article: Terraform: How to join list elements into a string

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