Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a random unused port in ansible

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.

like image 669
FailureGod Avatar asked Sep 13 '25 18:09

FailureGod


1 Answers

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.

like image 157
toydarian Avatar answered Sep 16 '25 06:09

toydarian