Skip to content

Instantly share code, notes, and snippets.

@jcollado
Created June 25, 2022 07:16
Show Gist options
  • Save jcollado/3caf195f616076eaf1009280e5cc307d to your computer and use it in GitHub Desktop.
Save jcollado/3caf195f616076eaf1009280e5cc307d to your computer and use it in GitHub Desktop.
Use jinja2 templates to generate multiple terraform providers in a loop
# Doit database files
.doit.db.*
# Terraform files created from templates
_*.tf
from jinja2 import Environment, FileSystemLoader
from pathlib import Path
DEFAULT_REGION = "us-east-1"
REGIONS = [
"ap-northeast-1",
"ap-northeast-2",
"ap-northeast-3",
"ap-south-1",
"ap-southeast-1",
"ap-southeast-2",
"ca-central-1",
"eu-central-1",
"eu-north-1",
"eu-west-1",
"eu-west-2",
"eu-west-3",
"sa-east-1",
"us-east-1",
"us-east-2",
"us-west-1",
"us-west-2",
]
def task_render():
""" "Render jinja2 templates.
Yields:
Render task for each jinja2 template file.
"""
cwd = Path(".")
environment = Environment(loader=FileSystemLoader(cwd))
j2_templates = cwd.glob("*.j2")
def render_template(template_path):
"""Render template.
Args:
template_path: Path to jinja2 template file
"""
template = environment.get_template(str(template_path))
with open(f"_{template_path.stem}", "w") as output_file:
output_file.write(template.render(default_region=DEFAULT_REGION, regions=REGIONS))
for j2_template in j2_templates:
target = f"_{j2_template.stem}"
yield {
"name": target,
"actions": [
(
render_template,
[j2_template],
{},
),
],
"file_dep": [j2_template],
"targets": [target],
"clean": True,
}
{% for region in regions %}
provider "aws" {
{%- if region != default_region %}
alias = "{{ region | replace("-", "_") }}"
{%- endif %}
default_tags {
tags = local.tags
}
region = "{{ region }}"
}
{% endfor %}
@nimblenitin
Copy link

Thanks. Will try it out

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment