Created
July 19, 2024 16:05
-
-
Save joshbeard/9bf002b6d2b9e5b806722fbd3b7e3c98 to your computer and use it in GitHub Desktop.
Parse Markdown Front Matter with Terraform
This file contains hidden or 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
# Helper module for parsing front matter from a markdown file and returning | |
# the front matter content as a map. | |
# | |
# Usage: | |
# module "frontmatter" { | |
# source = "./path/to/modules/frontmatter" | |
# content = file("path/to/markdown/file.md") | |
# } | |
# | |
# output "title_from_front_matter" { | |
# value = module.frontmatter.map.title | |
# } | |
# | |
variable "content" { | |
description = "The content of the markdown file with front matter" | |
type = string | |
} | |
locals { | |
# Replace newline characters with actual newlines for regex parsing | |
content_with_newlines = replace(var.content, "\\n", "\n") | |
# Use regex to match the front matter | |
front_matter_matches = regexall("(?s)^---\n(.*?)\n---", local.content_with_newlines) | |
# Extract the front matter content if found | |
front_matter = length(local.front_matter_matches) > 0 ? local.front_matter_matches[0] : null | |
# Debug: Output the raw front matter | |
front_matter_raw = local.front_matter | |
# Extract the front matter content without the delimiters if front matter is found | |
front_matter_content = local.front_matter != null ? local.front_matter[0] : "" | |
# Split the front matter into lines if content is not empty | |
front_matter_lines = local.front_matter_content != "" ? split("\n", local.front_matter_content) : [] | |
# Parse each line into a map | |
front_matter_map = length(local.front_matter_lines) > 0 ? { | |
for line in local.front_matter_lines : | |
split(":", line)[0] => trimspace(split(":", line)[1]) | |
if line != "" && can(split(":", line) && length(split(":", line)) > 1) | |
} : {} | |
} | |
# Output the parsed front matter map | |
output "map" { | |
value = local.front_matter_map | |
} | |
# Debug: Output the front matter content and lines | |
output "raw" { | |
value = local.front_matter_raw | |
description = "The raw front matter content (for debugging)" | |
} | |
output "matches" { | |
value = local.front_matter_matches | |
description = "The matches found in the content (for debugging)" | |
} | |
output "content" { | |
value = local.front_matter_content | |
description = "The content of the front matter (for debugging)" | |
} | |
output "lines" { | |
value = local.front_matter_lines | |
description = "The lines of the front matter content (for debugging)" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment