Python (re)

HCL / Terraform Variable Reference in PY

Match Terraform / HCL references like `var.name`, `local.foo`, `module.x.output`, or `data.aws_ami.ubuntu.id`.

Try it in the PY tester →

Pattern

regexPY
\b(?:var|local|module|data)\.[a-zA-Z_][\w\-]*(?:\.[a-zA-Z_][\w\-]*)*   (flags: g)

Python (re) code

pyPython
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+.

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_id

Matches

  • module.network.vpc_id

Input

tags = merge(var.common_tags, local.env_tags)

Matches

  • var.common_tags
  • local.env_tags

Input

no references here

No match

Same pattern, other engines

← Back to HCL / Terraform Variable Reference overview (all engines)