HI,
I have a list of servers that only part of them are running port 9090.
I need to create two tasks, each should loop the server’s hostnames. the first task should define inside a register the first server hostname that was found running port 9090 , the second task should define in a register all server’s hostnames that are running port 9090. If no server is running port 9090 the tasks should fail
I have nc installed on the server and i thought about using a shell with the command "nc -zv {{ item}} 9090
But I don’t know how to filter the relevant answers
For example:
server1
server2
server3 running 9090
server4
server5 running 9090
The first task should include in a register server 3 or server 5 hostname
The second task should include in a register server 3 and server 5 hostname
Let’s assume (ha!) you’ve got a shell task that loops over a list of servers, and for any server with port 9090 open it prints “{{item}} running 9090” to its stdout. And that you register that to “fake” to match the code below.
---
- name: Working with registered data
hosts: localhost
gather_facts: no
vars:
fake:
results:
- item: server1
stdout: ""
- item: server2
stdout: ""
- item: server3
stdout: "server3 running 9090\n"
- item: server4
stdout: ""
- item: server5
stdout: "server5 running 9090\n"
tasks:
- name: task1 pick the first server running 9090
debug:
msg: "{{ fake.results | selectattr('stdout', 'search', 'running 9090') | first }}"
- name: task2 pick all servers running 9090
debug:
msg: "{{ fake.results | selectattr('stdout', 'search', 'running 9090') | map(attribute='item') }}"
That produces the following output:
TASK [task1 pick the first server running 9090] ********************************
task path: /home/utoddl/ansible/register-games.yml:19
ok: [localhost] => {
"msg": "server3"
}
TASK [task2 pick all servers running 9090] *************************************
task path: /home/utoddl/ansible/register-games.yml:25
ok: [localhost] => {
"msg": [
"server3",
"server5"
]
}
name: Check if port 9090 is listening (times out in 3 secs per host)
wait_for:
port: 9090
timeout: 3
msg: “Timeout waiting for 9090 to respond”
register: port_check
ignore_errors: yes
Then you can look in port_check to see whether it succeeded.