Created
June 25, 2022 07:16
-
-
Save jcollado/3caf195f616076eaf1009280e5cc307d to your computer and use it in GitHub Desktop.
Use jinja2 templates to generate multiple terraform providers in a loop
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
# Doit database files | |
.doit.db.* | |
# Terraform files created from templates | |
_*.tf |
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
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, | |
} |
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
{% for region in regions %} | |
provider "aws" { | |
{%- if region != default_region %} | |
alias = "{{ region | replace("-", "_") }}" | |
{%- endif %} | |
default_tags { | |
tags = local.tags | |
} | |
region = "{{ region }}" | |
} | |
{% endfor %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@nimblenitin It depends on the content of your template, but if you expect
account_details
to be available in the template file, you need to pass it to thetemplate.render
method. One way to do that would be as follows: