Detect if server listen on port 80 och 443

I would like to detect if a server listens on port 80 or 443, I have a list of IPs that I get from an API.

- name: "Try https on the remote server"
  uri:
    url: "https://{{ item.ipAdress }}"
    method: GET
    timeout: 1
    validate_certs: no
  register: https_result
  failed_when: "'FAILED' in https_result"
  with_items: "{{ results.json }}"

When I run this code I get status -1 if the connection fails and status 200 if the connection works.

After this I would like to make 2 lists with IPs, one that failed and one that worked, then I use these two lists in a template and make a working config.

But I can’t figure out how to solve this bit. Does anyone have any ideas?

If you set failed_when to false and post the results from:

- name: Debug https_result
  ansible.builtin.debug:
    var: https_result

I’m sure someone could post a set_fact task to write the two lists you are after.

BTW I’d probably use the community.general.listen_ports_facts module to get a list of open ports on servers.

2 Likes

As Chris mentioned, set the failed_when option to false.

After this you can then create your two lists using set_fact as follows:

- name: Create Lists of Addresses
  ansible.builtin.set_fact:
    https_success_list: "{{ https_success_list | default([]) + ([https_result_item['item']['ipAddress']] if https_result_item['status'] == 200 else []) }}"
    https_fail_list: "{{ https_fail_list | default([]) + ([https_result_item['item']['ipAddress']] if https_result_item['status'] != 200 else []) }}"
  loop: "{{ https_result['results'] }}"
  loop_control:
    loop_var: https_result_item

The https_fail_list will be any item that doesn’t respond with a 200 status, if you only want to match a status of -1, just change the 200 to -1.

2 Likes

Thanks, that worked as I wanted.

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.