HCL / Terraform Variable Reference
Match Terraform / HCL references like `var.name`, `local.foo`, `module.x.output`, or `data.aws_ami.ubuntu.id`.
Try it in RegexPro →Available in
JavaScript / ECMAScript code
const re = new RegExp("\\b(?:var|local|module|data)\\.[a-zA-Z_][\\w\\-]*(?:\\.[a-zA-Z_][\\w\\-]*)*", "g");
const input = "vpc_id = module.network.vpc_id";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
Python (re) code
import re
pattern = re.compile(r"\b(?:var|local|module|data)\.[a-zA-Z_][\w\-]*(?:\.[a-zA-Z_][\w\-]*)*")
input_text = "vpc_id = module.network.vpc_id"
for m in pattern.finditer(input_text):
print(m.group(0))Stdlib `re` module — no third-party dependency. Works on Python 3.6+.
Go (RE2) code
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\b(?:var|local|module|data)\.[a-zA-Z_][\w\-]*(?:\.[a-zA-Z_][\w\-]*)*`)
input := `vpc_id = module.network.vpc_id`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
Pattern
\b(?:var|local|module|data)\.[a-zA-Z_][\w\-]*(?:\.[a-zA-Z_][\w\-]*)* (flags: g)Raw source: \b(?:var|local|module|data)\.[a-zA-Z_][\w\-]*(?:\.[a-zA-Z_][\w\-]*)*
How it works
Examples
Input
vpc_id = module.network.vpc_idMatches
module.network.vpc_id
Input
tags = merge(var.common_tags, local.env_tags)Matches
var.common_tagslocal.env_tags
Input
no references hereNo match
—Common use cases
- •Terraform dependency graph extraction
- •Refactor tooling (rename a variable across all files)
- •Linting for unused variables
- •Module-boundary auditing
Related patterns
Unix Environment Variable Reference
Text ProcessingMatch Unix shell environment variable references in both $VAR and ${VAR} forms.
Terraform Resource Block Header
Text ProcessingMatch the opening line of a Terraform `resource "type" "name" {` block, capturing the resource type and local name.
JavaScript Variable Declaration
Text ProcessingMatch JavaScript / TypeScript variable declarations (`var`, `let`, `const`), capturing the keyword and identifier name.
GraphQL Operation Header
Text ProcessingMatch GraphQL operation headers — `query`, `mutation`, or `subscription` — capturing the operation name.