In an ansible host(or inventory) file, you can group host using brackets. I want to sort these groups using sort function in linux but it will sort the individual hosts, and I want the right host to still be under the correct group. For example,
[webservers] examplehostserver hostname3 [database] db_server_1 local_db_server [ExampleGroup] Server05 Myserver01
I’m looking for a way to sort by group while keeping the host under the correct group
I have a feeling this is not possible within terminal commands or bash
Advertisement
Answer
You could do it with a simple Python script:
#!/usr/bin/python import sys groups = {} group = None for line in sys.stdin: line = line.rstrip() if line.startswith('['): # look for inventory groups group = line[1:-1].lower() # extract the group name groups[group] = [] if group and line: # gather up non-blank lines groups[group].append(line) for group in sorted(groups): # sort groups by name print('n'.join(groups[group])) # print out the group print()
Assuming that we have your example inventory in the file hosts
, and the above script in sortinv.py
, the following command:
python sortinv.py < hosts
Produces:
[database] db_server_1 local_db_server [ExampleGroup] Server05 Myserver01 [webservers] examplehostserver hostname3
The advantage of this mechanism is that it will preserve things like host variables and group variables. For example, given this input:
[webservers] examplehostserver ansible_host=10.0.0.1 hostname3 [database] db_server_1 local_db_server [ExampleGroup] Server05 Myserver01 [webservers:vars] apache_package_name=httpd
We get:
[database] db_server_1 local_db_server [ExampleGroup] Server05 Myserver01 [webservers] examplehostserver ansible_host=10.0.0.1 hostname3 [webservers:vars] apache_package_name=httpd
Much of that additional data would be lost by Vladimir’s solution.