Special variable group_names list items out of order

Hello,

While searching for my use-case, I stumbled upon this issue https://github.com/ansible/ansible/issues/73208 when the explanation provided was “The group_names variable is purposefully alphanumerically sorted by name, and not sorted by definition order.” However, this explanation doesn’t tell me for what purpose (in my mind, I could sort the list if I needed it that way), while I would benefit of having it sorted depending on the level. Nevertheless, is there a workaround to get the list of groups on which you can rely, level-wise ?

Thanks,
Goran

https://github.com/ansible/ansible/issues/73208 when the explanation
provided was "The group_names variable is purposefully alphanumerically
sorted by name, and not sorted by definition order." ... get the list
of groups on which you can rely, level-wise ?

Use *ansible-inventory* and parse the inventory on your own. Given
the example from the issue

cat hosts

all:
  children:
    NonprodAppDefault:
      children:
        CHG0240322:
          vars:
            controller_env: test
          hosts:
            hdqqclansiap001:
            hdqqclbcbwtb001:

1) Declare the variables

    inventory: "{{ out.stdout|from_yaml }}"
    my_groups: {}
    my_groups_0: "{{ inventory.all.children }}"

2) Parse the inventory

    - command: ansible-inventory --list --yaml
      register: out

gives

  inventory:
    all:
      children:
        NonprodAppDefault:
          children:
            CHG0240322:
              hosts:
                hdqqclansiap001:
                  controller_env: test
                hdqqclbcbwtb001:
                  controller_env: test
        ungrouped: {}

3) Create the dictionary of your groups

    - set_fact:
        my_groups: "{{ my_groups|
                       combine({item: _groups}) }}"
      loop: "{{ my_groups_0.keys()|list }}"
      vars:
        _groups: "{{ (my_groups_0[item].children|
                      default({})).keys()|list }}"

gives (probably what you want)

  my_groups:
    NonprodAppDefault:
    - CHG0240322
    ungrouped: