5

We are using some pipelines to build servers using ansible and one of the task is to check if server is online (means a production server in inventory list by accident). We check the port 443 and break the build pipeline; this is to ensure that no production or active server touched by accident. We have tried below code - out intention is to make playbook "success" when port 443 is down; so that next task in build pipeline can proceed.

- name: check server online or not
  hosts: localhost
  connection: local

  tasks:
  - name: check ESXI host connection to port 443
    wait_for: host=ams-server-101 port=443 timeout=1
    register: command_result
    failed_when: "'Timeout' not in command_result"

  - debug: var=command_result 

But the this is not working as expected. So we have used a work-around (non-ansible way) as below.

   shell: echo "QUIT" | nc -w 3 ams-server-101 443 > /dev/null 2>&1 && echo Pass || echo Fail
   register: shell_result
   failed_when: shell_result.stdout  == "Pass" 

Any idea ? (maybe some different module to use)

Gineesh
  • 187
  • 1
  • 1
  • 5
  • 1
    You probably want to use `command_result.msg` or something similar. `command_result` is going to be a structure/dictionary/object/whatever with a ton of stuff in it. Use `- debug: var=command_result` to see what it looks like. You should also be able to just invert it with `failed_when: not command_result.failed` – phemmer May 23 '18 at 02:35
  • Thanks Patrick, yes, we have checked; thats a big dictionary. even tried command_result.msg but ansible is saying Undefined variable. Something wrong. failed_when: not command_result.failed --> let me try that anyway – Gineesh May 23 '18 at 06:36

1 Answers1

6

You can use the fail module:

tasks:
  - wait_for:
      host: ams-server-101
      port: 443
      timeout: 1
    register: https_port_check
    ignore_errors: true
  - fail:
      msg: 'HTTPS port is open'
    when: not https_port_check.failed

Or very nice and short as Patrick suggested, but without custom fail message:

  tasks:
    - wait_for:
        host: ams-server-101
        port: 443
        timeout: 1
      register: https_port_check
      failed_when: not https_port_check.failed

For such an important check it might appropriate to blame the user with a vicious fail message.

rda
  • 921
  • 1
  • 6
  • 16
  • 2
    The fail module is overkill in this scenario. Tasks already have a `failed_when` that is more appropriate. `fail` is better suited to when you have much more complex processing, such as a composite conditional involving multiple tasks. – phemmer May 23 '18 at 02:39
  • oh okay. thats good idea. Thanks @rda, let me try. – Gineesh Jun 26 '18 at 08:25