赞
踩
在使用 ansible 的 shell 模块时,可能会碰到 non-zero return code ,这时 task 会 failed,但是需要该任务不为 failed。
此时可以在 shell 命令末尾增加 cat,将返回的内容通过管道传递给 cat,使用 cat 返回的 rc 始终为 0,而且也能捕获到原始输出进行判断。
实际应用
目前有如下需求:
往 pacemaker 的集群里面添加资源时,如果资源已经存在,命令返回值非 0,但是需要该任务正常通过执行。
添加重复资源的报错信息,可看到 strerr 中提示资源已存在:
failed: [test1 -> test1] (item=test-com1) => { "ansible_loop_var": "item", "changed": true, "cmd": ["docker", "exec", "masakari_hostmonitor", "pcs", "resource", "create", "test-compute101", "ocf:pacemaker:remote", "reconnect_interval=60"], "delta": "0:00:01.462636", "end": "2020-12-08 11:39:52.689518", "item": "test-com1", "msg": "non-zero return code", "rc": 1, "start": "2020-12-08 11:39:51.226882", "stderr": "Error: 'test-com1' already exists", "stderr_lines": ["Error: 'test-com1' already exists"], "stdout": "Warning: this command is not sufficient for creating a remote connection, use 'pcs cluster node add-remote'", "stdout_lines": ["Warning: this command is not sufficient for creating a remote connection, use 'pcs cluster node add-remote'"] }
给 shell 命令后添加 cat ,最终 task 示例:
--- - name: Register pacemaker_remote node vars: service: "{{ masakari_services['masakari-pacemaker-remote'] }}" become: true shell: > docker exec masakari_hostmonitor pcs resource create {{ item }} ocf:pacemaker:remote reconnect_interval=60 | cat run_once: True delegate_to: "{{ groups['masakari-api'][0] }}" with_items: "{{ groups['masakari-monitors'] }}" # 将执行结果注册到 result register: result # 若 result 中存在 exists 字符串,认为命令正常执行,状态置为 changed # 这样不会引起 task failed changed_when: "'exists' in result.stderr" when: - service.enabled | bool
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。