I have a specific scenario that I’m thinking to implement. Let’s say I have a playbook that takes user input for something like a “Group name”. Each time the playbook runs, 1 group name is captured and added to a cached list. The tricky part is that I want every group name to be unique, but I don’t want to bother the user with the “unique” requirement. For example, if they want their group name to be “group” and there’s already a “group-1”, then they’ll simply be added to the list as “group-2”.
So, to start, I create an empty list (my_list) with the condition that it hasn’t been previously defined (so this step only executes the first time the playbook is run).
Then I take USER INPUT and register that user_input to a group_name var.
To achieve group name uniqueness, I’m thinking to use some numerical suffix like my previous example.
Maybe implement something like:
N = 1
unique_group = group_name + str(N)
WHILE unique_group IN my_list
N += 1
unique_group = group_name + str(N)
END LOOP
(at this point, we’ve ensured that we have a unique_group that is not in my_list)
So now we append the unique group to the cached list:
SET FACT my_list: “{{ my_list + [unique_group] }}” cacheable: yes
Each time the playbook is run, it prompts the user for a group name, and it appends a suffix to that group name that ensures it is unique, and saves it to a cached list. During the playbook execution, it starts with “Some-Group-Name-1” and checks the cached list to see if it’s been used already. If it’s in the list, then it checks for “Some-Group-Name-2” and continues until it has a name that hasn’t been used, then proceeds to add that group name to the cached list.
Hopefully that was a clear enough explanation between what I’m hoping to achieve and my current thought process for how to achieve it.
I have been working with Ansible for a few months learning bits and pieces at a time. This particular solution is more complicated than what I normally work with. Is Ansible capable of doing this type of algorithm? Am I overthinking it? I’ve been troubleshooting this for a few days and I’m not making great progress. I can see that Ansible is powerful and I assume it can handle this situation, but I’m struggling to figure out how to implement it. Do I need to use specific collections or plugins?
Or would this be something that I write in a py script, and I have Ansible run the script passing the args and registering the output?
Any feedback is certainly appreciated. Thanks!