Using for-loops in Jinja2 to configure an access list
While we can already achieve a lot by being able to pass information from our Python file into a template and use this information in there, this is something that could be done with standard Python strings.
The true power of Jinja2 lies in its ability to include logic in the template. Basically, Jinja2 templates can also be seen as programs written in the Jinja2 template language.
This language supports such constructs as for
-loops and if
-clauses, which we have already seen in Python. This means that instead of copy-pasting the same text over and over and only changing one small part of it, we can create loops to make this more compact, readable, and changeable.
In this recipe, you'll see how to take two lists of IP addresses that are provided in your Python file and create an ACL for all the IPs in both lists, denying access for the IPs in one list while allowing access for IPs in the other list.