簡體   English   中英

Ansible 設置失敗的事實

[英]Ansible set fact for a failure

當主機無法訪問時,我正在嘗試在 Ansible 中創建一個自定義事實。 如果主機無法訪問或有其他故障類型,我想用自定義字典設置一個事實。 我可以使用 when 語句為可訪問的主機分配事實,但不能為無法訪問的主機分配事實。 有沒有辦法在失敗時設置自定義事實?

示例劇本:

---
  - hosts: myhosts
    gather_facts: False

    tasks:
    - name: Get Dict
      shell: "cat /path/dict_file"
      register: result
      ignore_errors: True

    - set_fact:
        result_dict={"cause": "connection timed out"}
      when: result is failed

    - set_fact:
       result_dict="{{ result.stdout }}"
      when: result is success

當我嘗試設置事實並將 result_dict var 分配給自定義字典值時,出現以下語法錯誤。

錯誤:

ERROR! Syntax Error while loading YAML.
  expected <block end>, but found '}'

無法訪問的主機上 result_dict 的期望輸出:

ok: [host-b] => {
    "result_dict": {"cause": "connection timed out"}
}

可以使用塊錯誤處理“以類似於大多數編程語言中的異常的方式處理錯誤” 例如

- hosts: myhosts
  gather_facts: false
  tasks:

    - block:
        - command: "head -1 /etc/motd"
          register: result
      rescue:
        - meta: clear_host_errors

    - set_fact:
        result_dict: "{{ result.failed|
                         ternary('cause: connection timed out',
                         result.stdout) }}"
    - debug:
        var: result_dict

ok: [test_01] => {
    "result_dict": "FreeBSD 12.0-RELEASE r341666 GENERIC "
}
ok: [test_02] => {
    "result_dict": "FreeBSD 12.0-RELEASE r341666 GENERIC "
}
ok: [test_03] => {
    "result_dict": "FreeBSD 12.0-RELEASE r341666 GENERIC "
}
ok: [test_04] => {
    "result_dict": "cause: connection timed out"
}

我能夠通過將 playbook 關鍵字ignore_unreachable設置為true以允許任務繼續無法訪問的主機然后使用 when 語句僅為無法訪問的主機分配超時字典來完成此操作。 我還需要更正超時指令的格式。

當語句:

- name: FAILED
  set_fact:
    result_dict:
      cause: 'Timeout'
  when: "'unreachable' in result"

- name: PASSED
  set_fact:
   result_dict="{{ result.stdout | from_json }}"
  when: "'unreachable' not in result"
- debug: var=result_dict

輸出:

ok: [localhost] => {
    "my_final_map": {
        "cause": "Timeout", 
        "host_a": [
            {
                "ip-1": {
                    "port": "22", 
                    "service": "ssh"
                }
            }, 
            {
                "ip-2": {
                    "port": "21", 
                    "service": "ftp"
                }
            }
        ]
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM