I wrote a playbook that creates a new resource or multiple resources. Name for this resource is generated with various user inputs with one addition - a number. So, generated name looks like resource_name_1, resource_name_2, depending on how many resources is created. That works well, if there are no existing resources with the same name (combination of user inputs and a number).
So, I need to check is there already deployed resource with the same name in other words to compare this new generated name with gathered list of names.
If there is no match, then create it the "ordinary" way. If there is a match, then find the matching name with the highest number (because there can be for example 20 resources already in place), extract and increment this highest number (20), and use it for a new resource name.
I can gather a list of existing resource names like this:
resources_names_list: "{{ resource_name_info.resource | map(attribute='name') }}"
And sample list looks like:
ok: [localhost] => {
"msg": [
"resource-1",
"ex1",
"someresource2",
"ppp-1",
"pd5",
"sample65kk ",
"prod5",
"sample",
"stars3232demo",
]
}
Here is the loop:
- debug: msg: match is found "{{item2}}"
when: (my_generated_resource_name in item2)
loop: "{{resources_names_list}}"
loop_control:
loop_var: item2
This loop does compare generate resource name with gathered names from the list. So now it should be adapted to find the match, but with the highest number.. That highest number should be extracted, incremented and then used for generation of new resource name.
Thanks!
I made other tasks (max and increment) work like this:
- name: Find maximum number from the list list2
set_fact:
max_number: "{{ list2 | map('int') | max }}"
- debug:
msg: "{{ max_number }}"
- name: increment number
set_fact:
number: "{{max_number|int + 1}}"
- debug:
msg: incremented number is "{{ number }}"