Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference filter not working in Ansible

Tags:

ansible

I am trying to find which ports are available for my use. The logic goes like this, I am firs finding the used ports and providing a list of ports that I can use, the difference filter should filter out the ones that are available, but somehow it is not working.

Here is the code block:

- name: Gather occupied tcp v4 ports
  shell: netstat -nlt| awk '{print $4}'|awk -F':' '{print $2}'
  register: used_ports
- debug:
        var: used_ports
- name: Difference
  vars:
    allowed_ports:
      - 107
      - 823
      - 4750
  set_fact:
        bind_port: "{{ allowed_ports | difference(used_ports) | first }}"
- name: Show bind port
  debug:
       var: bind_port

Output:

ok: [] => { "used_ports": { "changed": true, "cmd": "netstat -nlt| awk '{print $4}'|awk -F':' '{print $2}'", "delta": "0:00:00.077467", "end": "2018-08-12 15:25:04.477710", "failed": false, "rc": 0, "start": "2018-08-12 15:25:04.400243", "stderr": "", "stderr_lines": [], "stdout": ", "stdout_lines": [ "", "", "107", "202", "106" ] } }

TASK [serverbuild : Difference] ********************************************************************* ok: []

TASK [serverbuild : Show bind port] ***************************************************************** ok: [] => { "bind_port": "107" }

Ideally it should not show 107 as it is already used. What am I doing wrong here?

like image 576
Pratik Tambe Avatar asked Oct 27 '25 03:10

Pratik Tambe


1 Answers

There are two problems:

  1. You should use used_ports.stdout_lines as an argument to the difference filter,

  2. You should either define allowed_ports to contain strings, or map used_ports.stdout_lines to integers.

So:

- name: Difference
  vars:
    allowed_ports:
      - "107"
      - "823"
      - "4750"
  set_fact:
    bind_port: "{{ allowed_ports | difference(used_ports.stdout_lines) | first }}"

or:

- name: Difference
  vars:
    allowed_ports:
      - 107
      - 823
      - 4750
  set_fact:
    bind_port: "{{ allowed_ports | difference(used_ports.stdout_lines|map('int')) | first }}"
like image 188
techraf Avatar answered Oct 30 '25 15:10

techraf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!