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)

2
  • 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
    Commented May 23, 2018 at 2: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
    Commented May 23, 2018 at 6:36

1 Answer 1

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.

2
  • 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
    Commented May 23, 2018 at 2:39
  • oh okay. thats good idea. Thanks @rda, let me try.
    – Gineesh
    Commented Jun 26, 2018 at 8:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .