Go (RE2)

Terraform Resource Block Header in GO

Match the opening line of a Terraform `resource "type" "name" {` block, capturing the resource type and local name.

Try it in the GO tester →

Pattern

regexGO
resource\s+"([\w\-]+)"\s+"([\w\-]+)"\s*\{   (flags: g)

Go (RE2) code

goGo
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`resource\s+"([\w\-]+)"\s+"([\w\-]+)"\s*\{`)
	input := `resource "aws_s3_bucket" "main" { bucket = "my-app" }`
	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

resource\s+ matches the keyword and required whitespace. "([\w\-]+)" captures the resource type (e.g. `aws_instance`). "([\w\-]+)" captures the local name. The trailing `\s*\{` confirms a block opener (so we don't match string-literal `resource "x" "y"` in a comment).

Examples

Input

resource "aws_s3_bucket" "main" { bucket = "my-app" }

Matches

  • resource "aws_s3_bucket" "main" {

Input

resource "google_storage_bucket" "backups" {

Matches

  • resource "google_storage_bucket" "backups" {

Input

data "aws_caller_identity" "current" {}

No match

Same pattern, other engines

← Back to Terraform Resource Block Header overview (all engines)