The goal:
I want to get a list of ansible hosts (could be made out of the ansible inventory e.g.) and each element should be separated by a space. The reason for that is that I want to run a bash script which needs a list attached to it like script.sh host_1 host_2 host_3 ...
The problem:
I need to specify one host, which needs to be in front of every other host e.g. script.sh **host_2.example.de** host_1.example.de host_3.example.de ...
My ansible inventory.ini example looks like:
[manager]
host_2.example.de
[utility_nodes]
host_1.example.de host_template=Utility1
host_2.example.de host_template=Utility2
[master_nodes]
host_3.example.de host_template=Master1
host_4.example.de host_template=Master2
CodePudding user response:
To do exactly what you're asking, you could do something like this:
$ hosts=$(ansible-inventory -i hosts --list |
jq -r '[values[]|.hosts|select(.)[]]|unique[]')
$ echo $hosts
host_1.example.de host_2.example.de host_3.example.de host_4.example.de
This uses ansible-inventory
to produce a JSON dump of your inventory, and then jq
to query that for a list of hosts.
But that seems like a terrible idea.
Since you're already using Ansible, why not just use Ansible to run your script? Use a playbook like this:
- hosts: localhost
gather_facts: false
tasks:
- name: Run script
command: ./script.sh {{ groups.all|join(' ') }}
To ensure that host_2
is the first host, you could write:
- hosts: localhost
gather_facts: false
become: true
tasks:
- name: Run script
command: ./script.sh {{ groups.manager|join(' ') }} {{ groups.all|reject("in", groups.manager)|join(' ') }}
register: res
- debug:
var: res.stdout
This will ensure that members of the manager
group are always at the front of the list of host.s