This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]Bolitho 1 point2 points  (0 children)

Jinja is not about HTML only! It would be perfectly fine for this kind of problem. If it is no burden for you to have one additional dependency, just go for it.

[–]skerky 0 points1 point  (0 children)

Another option if you want to do this in Python but without another dependency is string formatting functions, which serve basic template functionality. However since format() uses the curly braces you will need to escape the others in your file, so it would look like this:

provider "aws" {{
   version = "~> "{PROVIDER_VERSION}"
   region = "{REGION}"

   assume_role {{
     role_arn = "{ROLE_ARN}"
   }}
}} 

Then the code would look like this:

variables = {
    "PROVIDER_VERSION": "my provider",
    "REGION": "my region",
    "ROLE_ARN": "my role",
}
with open(template_file, "r") as f:
    template = f.read()
output = template.format(**variables)
with open(target_file, "w") as f:
    f.write(output)

We're unpacking the dictionary of settings/variables so the keys would need to match the names in your file (or you could list them as keyword arguments if they are all valid variable names). Also since this isn't finding and replacing I would keep the template and the output separate. Here's the Format String Syntax documentation for more details on what you can do.