Ansible技巧:assert模块示例中成功时显示评估表达式

备忘-提醒

在assert模块中,当评估结果成功时,评估表达式不会被显示,并且很难作为Ansible日志中已成功状态的证据使用。

一個例子是在成功時顯示評價表評估。

可以将评估公式以循环方式运行,并在循环标签处将评估公式记录到日志中。

- name: asserts for some tests
  assert:
    that:
    - "{{ item }}"
    success_msg: 'Passed: {{ item }}'
    fail_msg: 'FAILED: {{ item }}'
  register: r
  ignore_errors: true                   # summaryを出力させる為、failedでも継続
  loop:                                 # 評価式のlist
  - 1 == 1
  - "'a' in ['a','b']"
  - ansible_distribution in ['AIX']     # <= fail
  - ansible_distribution in ['MacOSX']  # <= success

- name: summary of asserts              # サマリー出力
  debug: var=r.results|map(attribute='msg')|list

- assert:                   # 上のassertでfailedがあった場合に停止
    that:
    - "{{ r is not failed }}"

执行结果

TASK [ansible-assert : asserts for some tests that=['{{ item }}'], success_msg=Passed: {{ item }}, fail_msg=FAILED: {{ item }}] ***
ok: [localhost] => (item=1 == 1) => {
    "ansible_loop_var": "item",
    "changed": false,
    "item": "1 == 1",
    "msg": "Passed: 1 == 1"
}
ok: [localhost] => (item='a' in ['a','b']) => {
    "ansible_loop_var": "item",
    "changed": false,
    "item": "'a' in ['a','b']",
    "msg": "Passed: 'a' in ['a','b']"
}
failed: [localhost] (item=ansible_distribution in ['AIX']) => {
    "ansible_loop_var": "item",
    "assertion": "ansible_distribution in ['AIX']",
    "changed": false,
    "evaluated_to": false,
    "item": "ansible_distribution in ['AIX']",
    "msg": "FAILED: ansible_distribution in ['AIX']"
}
ok: [localhost] => (item=ansible_distribution in ['MacOSX']) => {
    "ansible_loop_var": "item",
    "changed": false,
    "item": "ansible_distribution in ['MacOSX']",
    "msg": "Passed: ansible_distribution in ['MacOSX']"
}
...ignoring

TASK [ansible-assert : summary of asserts var=r.results|map(attribute='msg')|list] *************************
ok: [localhost] => {
    "r.results|map(attribute='msg')|list": [
        "Passed: 1 == 1",
        "Passed: 'a' in ['a','b']",
        "FAILED: ansible_distribution in ['AIX']",
        "Passed: ansible_distribution in ['MacOSX']"
    ]
}

TASK [ansible-assert : assert that=['{{ r is not failed }}']] **********************************************
fatal: [localhost]: FAILED! => {
    "assertion": false,
    "changed": false,
    "evaluated_to": false,
    "msg": "Assertion failed"

广告
将在 10 秒后关闭
bannerAds