Ansible 中的语法错误是常见的问题之一,通常会导致 Playbook 无法正常运行。这些错误通常是由于 YAML 文件中的语法问题(如缺少引号、拼写错误或格式问题)引起的。

在实际演示中,我们将从错误信息入手,逐步排查问题的根本原因并修复它。

Ansible 故障排除:语法错误

错误示例

以下是一个包含语法错误的 Ansible Playbook 示例:

---
- name: win_copy module demo
  hosts: all
  become: false
  gather_facts: false
  vars:
    source: "report.txt"
    destination: "Desktop/report.txt"
  tasks:
    - name: copy report.txt
      ansible.windows.win_copy:
        src: "{{ source }}"
        dest: "{{ destination }}"

错误信息

运行上述 Playbook 时,可能会遇到以下错误:

$ ansible-playbook -i win/inventory troubleshooting/syntax_error.yml
ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each:
JSON: Expecting value: line 1 column 1 (char 0)

Syntax Error while loading YAML.
found unexpected end of stream

The error appears to be in 'ansible-pilot/troubleshooting/syntax_error.yml': line 14, column 1, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

src: "{{ source }}"
dest: "{{ destination }}
^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:

with_items:
- {{ foo }}

Should be written as:

with_items:
- "{{ foo }}"

问题原因

  1. 缺少引号:dest 参数的值 {{ destination }} 缺少闭合的双引号。
  2. YAML 格式问题:YAML 文件中可能存在其他格式问题,例如缩进不一致或拼写错误。

修复方法

  1. 修复引号问题:确保所有模板表达式(如 {{ }})都被正确引用。
  2. 检查 YAML 格式:确保整个文件的格式正确,包括缩进和拼写。

修复后的 Playbook 如下所示:

---
- name: win_copy module demo
  hosts: all
  become: false
  gather_facts: false
  vars:
    source: "report.txt"
    destination: "Desktop/report.txt"
  tasks:
    - name: copy report.txt
      ansible.windows.win_copy:
        src: "{{ source }}"
        dest: "{{ destination }}"

修复步骤

  1. 修复引号问题:在 dest 参数的值 {{ destination }} 后添加闭合的双引号。
  2. 检查 YAML 格式:使用在线 YAML 验证工具(如 YAML Lint)检查 Playbook 的格式是否正确。
  3. 重新运行 Playbook:修复问题后,重新运行 Playbook 以验证是否解决了问题。

验证修复

修复问题后,重新运行 Playbook:

$ ansible-playbook -i win/inventory troubleshooting/syntax_fix.yml

如果 Playbook 成功运行,您将看到类似以下的输出:

PLAY [win_copy module demo] **************************************************

TASK [copy report.txt] *******************************************************
ok: [WindowsServer]

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

总结

Ansible 中的语法错误通常是由于以下原因导致的:

  1. 缺少引号:模板表达式(如 {{ }})未正确引用。
  2. YAML 格式问题:缩进不一致、拼写错误或格式问题。

通过以下步骤可以有效解决语法错误:

  1. 修复引号问题:确保所有模板表达式都被正确引用。
  2. 检查 YAML 格式:使用在线工具验证 YAML 文件的格式。
  3. 重新运行 Playbook:验证修复是否有效。

如果问题仍未解决,可以参考 Ansible 的 官方文档或社区支持获取更多帮助。