Go (RE2)

HCL / Terraform Variable Reference in GO

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

Try it in the GO tester →

Pattern

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

Go (RE2) code

goGo
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.

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)