HCL / Terraform Variable Reference in JS
Match Terraform / HCL references like `var.name`, `local.foo`, `module.x.output`, or `data.aws_ami.ubuntu.id`.
Try it in the JS tester →Pattern
regexJS
\b(?:var|local|module|data)\.[a-zA-Z_][\w\-]*(?:\.[a-zA-Z_][\w\-]*)* (flags: g)JavaScript / ECMAScript code
jsJavaScript
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).
How the pattern works
\b(?:var|local|module|data) anchors at one of the four namespace prefixes. \.[a-zA-Z_][\w\-]* matches the first segment after the prefix. (?:\.[a-zA-Z_][\w\-]*)* matches additional dotted accessors (deep references like `module.network.outputs.vpc_id`).
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
—