I want to get a random unused port so that I can wait_for
it. Preferably in the range of dynamic ports but, at this point, I'm not picky. I'm using Linux and this does not have to be compatible with windows or Mac.
While this question is marked as answered, if anyone has a way to do this simpler and with less calls to shell, post it below. I don't care if this question is four years old.
As discussed in the comments, you do not want to wait_for
a port, but open one and wait for a ping.
I don't know a simple way to get a random port, so I wrote a little shell script to find one:
- hosts: all
tasks:
- name: find port
shell: |
PORT=5000
while true; do
ss -tulpen | grep ":${PORT}" &> /dev/null
if [[ "$?" == "1" ]]; then
echo "${PORT}"
exit
fi
((PORT++))
done
args:
executable: /bin/bash
register: port
- name: print port
debug:
msg: "{{ port.stdout }}"
- name: wait for ping
shell: nc -l "{{ port.stdout }}"
- name: debug
debug:
msg: "Ping received"
This looks for a port, prints it to you and then opens the port and waits for a ping using netcat
. When the ping is received, it prints a message.
Tested this on a ubuntu. You might need different arguments for netcat
(or here it is nc
) as different distros ship different version.
EDIT:
After sending the ping to the port, you need to close the TCP connection, because netcat
will only exit, after the connection is closed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With