ansible tower messing up the order in which inventory hosts gets played

i have a code like this

  • template:
    src: …/files/kfhost.j2
    dest: /app/bin/kafka/server.properties
    owner: kafka
    group: kafka
    mode: 0755

the jinga file has an entry like this

broker.id={{ play_hosts.index(inventory_hostname)+1 }}

when i have an inventory file like this

[all]
server1
server2
server3

and run this playbook from command line. server1 broker.id is set to 1, server2 broker.id is set to 2 and server3 broker.id is set to 3.

when i run the same in ansbile tower, sometimes the server1 gets value 2, server2 gets value 1

the order is getting mismatched.

just fyi there are other tasks before this task in the playbook

any idea as to why this might be happening in tower and never when i run ansible-playbook command line

My first thought is how do you have your inventory in tower? Does it match the same exact layout as your inventory on the command line?

As in server1 is the first entry, server2 the second, etc…?

But generally speaking, since inventories may not always be perfectly matched, a better solution would be to do some python/jinja2 logic in your Template to scan the inventory provided and generate the server properties.

You may want to try specifying the ordered at the playbook level. You can find that option in the docs.

https://docs.ansible.com/ansible/latest/user_guide/playbooks_intro.html

Tower saves the inventory in the database that it gets from the ansible-inventory command. To the best of my memory, ansible-inventory does an ordered JSON dump. We later take it back out of the database for the job run (at which point I really don’t think the JSON dump is ordered), the ordering is lost at some point along the line. Exactly where, and if it’s one step or multiple steps, I don’t know. We would need to maintain an order field in some shape or form to actually support it, and that’s pretty non-trivial.

This is basically a known issue via https://github.com/ansible/awx/issues/2240