Run a handler play and exit play if rc == 0 in ansible

筅森魡賤 提交于 2021-02-11 12:54:37

问题


Hi is there a way I can run a handler play then exit the play if rc == 0. It can only do is exit the play using failed_when and proceed if rc != 0. I can't make notify: Service Guard execute. Been play with other approach like creating 2 play notify and exit no luck.

- name: Exit SG server from play
  command: /usr/local/cmcluster/bin/cmversion
  register: sg_check
  notify: Service Guard
  failed_when: sg_check.rc == 0

Here is new code I tried

- name: Check if Service Gurad then exit
  command: /usr/local/cmcluster/bin/cmversion
  register: sg_check
  notify: Service Guard
  changed_when: sg_check.rc == 0
  ignore_errors: true
- meta: end_play
  when: sg_check.rc == 0

but I get this:

ERROR! The conditional check 'sg_check.rc == 0' failed. The error was: error while evaluating conditional (sg_check.rc == 0): 'sg_check' is undefined

The error appears to have been in '/home/ansible/linuxpatchingv2/roles/applyPatch/tasks/main.yml': line 9, column 3, but may be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

ignore_errors: true

  • meta: end_play ^ here

回答1:


Q: "Run a handler play then exit the play if rc == 0"

A: This is not possible to accomplish in one task because a task can't be both changed and failed at the same time. These two actions must be split. For example, in the playbook below the command will succeed, notify the handler, and end the play

shell> cat pb.yml
- hosts: localhost
  gather_facts: false
  tasks:
    - command: "{{ cmd|default('/bin/true') }}"
      register: sg_check
      notify: Service Guard
      changed_when: sg_check.rc == 0
      ignore_errors: true
    - meta: end_play
      when: sg_check.rc == 0
    - debug:
        msg: Continue
  handlers:
    - name: Service Guard
      debug:
        msg: Service Guard notified

gives (abridged)

shell> ansible-playbook pb.yml
...
RUNNING HANDLER [Service Guard] ****
ok: [localhost] => 
  msg: Service Guard notified

PLAY RECAP ****
localhost: ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

The same playbook will continue if the command fails. For example

shell> ansible-playbook pb.yml -e "cmd=/bin/false"

PLAY [localhost] ****

TASK [command] ****
fatal: [localhost]: FAILED! => changed=false 
  cmd:
  - /bin/false
  delta: '0:00:00.003035'
  end: '2020-08-24 09:33:22.039762'
  msg: non-zero return code
  rc: 1
  start: '2020-08-24 09:33:22.036727'
  stderr: ''
  stderr_lines: <omitted>
  stdout: ''
  stdout_lines: <omitted>
...ignoring

TASK [debug] ****
ok: [localhost] => 
  msg: Continue

PLAY RECAP ****
localhost: ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1


来源:https://stackoverflow.com/questions/63555584/run-a-handler-play-and-exit-play-if-rc-0-in-ansible

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!