以ansible条件评估返回代码

时间:2015-12-17 17:19:19

标签: ansible

我正致力于自动执行需要将最新版本的软件附加到文件的任务。我不想为同一版本多次这样做。

它查看以下示例文件:

var software releases = new Array(
    "4.3.0",
    "4.4.0",
    "4.5.0",
    "4.7.0",
    "4.8.0",
    "4.11.0",
    "4.12.1",
    "4.14.0",
    "4.15.0",
    "4.16.0",
);

默认的main.yml会传递类似

的内容
VERSION: 4.16.2

- name: register version check
  shell: cat /root/versions.js | grep -q {{VERSION}}
  register: current_version

- debug: msg="The registered variable output is {{ current_version.rc }}"

- name: append to versions.js
  lineinfile:
    dest: /root/versions.js
    regexp: '^\);'
    insertbefore: '^#\);'
    line: "    \"{{VERSION}}\",\n);"
    owner: root
    state: present
    when: current_version.rc == 1

问题:调试消息正在评估current_version.rc并根据grep命令输出显示布尔值,但是我无法在when条件中重复使用它来确定是否应该运行任务。 / p>

编辑:输出:

PLAY [localhost] **************************************************************

GATHERING FACTS ***************************************************************
ok: [localhost]

TASK: [test | register version check] *****************************************
failed: [localhost] => {"changed": true, "cmd": "cat /root/versions.js | grep -q 3.19.2", "delta": "0:00:00.003570", "end": "2015-12-17 00:24:49.729078", "rc": 1, "start": "2015-12-17 00:24:49.725508", "warnings": []}

FATAL: all hosts have already failed -- aborting

PLAY RECAP ********************************************************************
           to retry, use: --limit @/root/site.retry

localhost                  : ok=1    changed=0    unreachable=0    failed=1

1 个答案:

答案 0 :(得分:34)

正如nikobelia在评论中指出的那样grep returns an exit code of 1 when it doesn't match any lines。 Ansible然后将此(实际上是来自shell /命令任务的0以外的任何状态代码)解释为错误,因此会立即失败。

您可以使用ignore_errors告诉Ansible忽略shell /命令任务中的响应代码。虽然使用grep这会忽略实际错误(由返回代码2给出),因此您可能希望使用failed_when这样:

- name: register version check
  shell: cat /root/versions.js | grep -q {{VERSION}}
  register: current_version
  failed_when: current_version.rc == 2