Imagine the scenario, we want to create multiple S3 buckets using the Cloudformation block below:
| |
But we don’t want to repeat and hardcode values inside the manifest, one alternative is using a template engine to allow variables and loops to generate the final manifest.
For example, we will use Jinja2 Template Engine with a CLI tool named Jinja2 CLI to be easy to execute the templates.
$ python3 -m venv venv $ source venv/bin/activate $ pip3 install jinja2-cli
Now is possible to create a jinja2 template with a parametrized name variable following Jinja2 Syntax:
| |
And with our dependencies installed, we can execute it to render the template.
| |
The output was a rendered template with my-api-bucket, But if we want to create 5 different buckets ? First, we will define our variables in a JSON file.
| |
And create a jinja2 template with a for loop to iterate through the list creating an S3 block for each name:
| |
Below is the command to render the template passing a JSON file with variables:
| |
With that, we can receive the output for our final manifest.
| |
With this simple case, we saw how to use jinja2-cli to iterate to generate dynamic configuration and declarative files.