Created
August 11, 2021 22:44
-
-
Save shoddyguard/3da13eaa79f415acedececc5c3175c8b to your computer and use it in GitHub Desktop.
Regex matching Terraform blocks in .NET
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
resource "github_repository" "terraform_example" { | |
name = "terraform-example" | |
visibility = "private" | |
description = "Test Repo" | |
homepage_url = "" | |
has_issues = true | |
has_wiki = true | |
has_projects = false | |
has_downloads = true | |
} | |
resource "github_branch_protection" "terraform_example_master" { | |
repository_id = github_repository.terraform_example.node_id | |
pattern = "master" | |
enforce_admins = false | |
required_status_checks { | |
strict = true | |
contexts = ["Jenkins - Test Repo"] | |
} | |
required_pull_request_reviews { | |
} | |
push_restrictions = [ | |
github_team.DevTeam.node_id | |
] | |
depends_on = [github_team_repository.DevTeam_terraform_example] | |
} | |
# Many more repo configurations below |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This a crude but reasonably effective way of extracting blocks from Terraform/HCL in something like PowerShell. | |
I'm sure there are edge cases that are not covered here but this is handy when you want to parse Terraform configurations en masse. | |
In my particular case I needed to replace all `github_branch_protection` resources with `github_branch_protection_v3` resources due to the current GraphQL implementation of the GitHub Terraform provider causing lengthy Terraform runs. :( |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Import the terraform config as a raw string | |
$TerraformConfig = Get-Content './github.repos.tf' -Raw | |
# The below matches only on the 'github_branch_protection' resource above | |
$Regex = '(resource "github_branch_protection" "terraform_example_master" {(?>[^{}]+|{(?<curly>)|}(?<-curly>))*(?(curly)(?!))})' | |
# Replace the matched regex with nothing | |
$TerraformConfig -replace $Regex,'' | |
# Export the content back out to the original file | |
Set-Content './github.repos.tf' -Value $TerraformConfig -Force |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment