Create Random GUID with Jinja

Once in a while, when working with Jinja templating engine, you might need to create a random GUID with Jinja.

Here is how to do it:

{% macro random_string(len) -%}{% for i in range(0,len) -%}{{ [0,1,2,3,4,5,6,7,8,9,"a","b","c","d","e","f"]|random }}{% endfor %}{%- endmacro -%}
{% macro random_guid() -%} {{ random_string(8) + "-" + random_string(4) + "-" + random_string(4) + "-" + random_string(4) + "-" + random_string(12) }}{%- endmacro -%}
{% set myGUID = random_guid() %}

Now let’s explain it line by line

{% macro random_string(len) -%}{% for i in range(0,len) -%}{{ [0,1,2,3,4,5,6,7,8,9,"a","b","c","d","e","f"]|random }}{% endfor %}{%- endmacro -%}

I decided to go with Jinja macro as I had to create different random strings of various lengths, not necessarily aligned with the default GUID (8-4-4-4-12) format. so random_string macro accepts a len parameter, that specifies what length should the randomly generated string should be.

Note: that the random string will have only 0-9 and a-f characters and not any alphanumeric character.

Also the resulting GUID-like string is just a set of random string that look like GUID, but don’t necessary adhere to the string formats and variants described here

{% macro random_guid() -%} {{ random_string(8) + "-" + random_string(4) + "-" + random_string(4) + "-" + random_string(4) + "-" + random_string(12) }}{%- endmacro -%}

random_guid macro is actually a wrapper that calls the random_string macro with a specific value for the len parameter a number of times and creates a random string that adheres to the expected GUID format.

{% set myGUID = random_guid() %}

Here we are just calling the random_guid macro and assigning the returned value to the myGUID Jinja parameter

More posts about Jinja

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.