Generate FlowId

This script was created to help me create uniq 5 digit IDs for ansible playbooks. It can be executed in the same directory where the playbooks are and from there it will search the string “workflow_id: " in every *.yml file. workflow_id is an ansible playbook variable that keeps the unique flow ID. It’s actually a common ID that I share with the people requested the workflow (playbook). Each playbook reports an email with that workflow ID to the people involved.

#!/usr/bin/env python

import glob
import re
from random import randint


def search_id_in_file(file_name):

    id_found = ""
    fh = open(file_name, "r")
    for line in fh:
        line = line.rstrip()
        regex_result = re.findall("\\sworkflow_id: ([0-9.]+)", line)
        if len(regex_result) != 1:
            continue
        id_found = int(regex_result[0])

    return id_found


def generate_random_id(workflow_ids, gen_min, gen_max):

    new_id_found = False

    while not new_id_found:
        gen_random_id = randint(gen_min, gen_max)
        unique = True
        for item in workflow_ids:
            if gen_random_id == item:
                unique = False
                break

        if unique:
            new_id_found = gen_random_id

    return gen_random_id


def main():

    file_list = glob.glob("*.yml")
    workflow_ids = []

    for file in file_list:
        id_found = search_id_in_file(file)
        if id_found != "":
            workflow_ids.append(id_found)
        else:
            continue

    new_id = generate_random_id(workflow_ids, 10000, 99999)
    print("The new workflow ID is")
    print("workflow_id:", new_id)


if __name__ == '__main__':
    main()